python调用gemini2.0接口识别图片文字

python 复制代码
import os
import base64
import google.generativeai as genai

# 配置 Google API Key
# 可以在系统环境变量设置 GOOGLE_API_KEY
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "AIzaSXXXXXXXXXXXXXX")  # 替换成你的 API Key

# 设置 Gemini 模型名称
model_name = "gemini-2.0-flash-exp"

# 设置图片路径(这里使用一个在线图片URL)
image_path = "c:\\111.png"  # 替换成你的图片路径

# 设置文本提示
prompt = "请提取图片上的文字返回"  # 修改为你需要的提示语


def call_gemini_api(image_path, prompt, model_name, api_key):
    """
    调用 Gemini API,并返回文本响应。
    """
    # 配置 google.generativeai
    genai.configure(api_key=api_key)
    model = genai.GenerativeModel(model_name=model_name)

    try:
        # 读取图片文件
        with open(image_path, 'rb') as f:
            image_data = f.read()
    except FileNotFoundError:
        print(f"错误:图片文件未找到:{image_path}")
        return ""

    # 将图片数据编码为 Base64 字符串
    base64_image = base64.b64encode(image_data).decode('utf-8')

    # 构建请求体
    contents = [
        {
            "parts": [
                {
                    "inline_data": {
                        "mime_type": "image/png",  # 假设图片为 JPEG 格式, 可根据你的图片类型修改
                        "data": base64_image
                    }
                },
                {
                    "text": prompt
                }
            ]
        }
    ]

    try:
        # 发送请求并获取响应
        response = model.generate_content(contents=contents)
        response.resolve()
        if response and response.text:
            return response.text
        else:
            return ""  # 请求失败或者没有文本
    except Exception as e:
        print(f"请求失败: {e}")
        return ""


if __name__ == "__main__":
    response_text = call_gemini_api(image_path, prompt, model_name, GOOGLE_API_KEY)

    if response_text:
        print("Gemini API 响应:")
        print(response_text)
    else:
        print("调用 Gemini API 失败")

识别结果跟图片

虽然有点小误差.但是可以接受.

GEMINI不给大陆使用.请自行想办法解决.

相关推荐
52Hz1181 天前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
weixin_462446231 天前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
毕设源码-钟学长1 天前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
百***78751 天前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191771 天前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python
忧郁的橙子.1 天前
26期_01_Pyhton基本语法
python
sunfove1 天前
实战篇:用 Python 徒手实现模拟退火算法解决 TSP 问题
开发语言·python·模拟退火算法
我是菜鸟0713号1 天前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
我是一只小青蛙8881 天前
TraeCNIDE Python开发全流程指南
python
欣然~1 天前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python