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不给大陆使用.请自行想办法解决.

相关推荐
外收内放12 小时前
面向对象高级(实战案例)
开发语言·python·学习
专业程序开发源13 小时前
springboot欧缇蔓月子中心管理系统82697-计算机课程设计、毕业设计
java·spring boot·后端·python·spring·django·课程设计
FPGA小迷弟13 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
卷无止境13 小时前
面向arm64桌面客户端开发全景:语言、框架与生态
后端·python
fanruitian13 小时前
python else用法
开发语言·python
Thinker QAQ14 小时前
并发编程(十一):Shared Memory 与 Message Passing——关系与组合使用
java·python·go·并发编程·shared memory·message passing
用户83562907805114 小时前
如何使用 Python 对 Excel 数据进行分组和分级显示
后端·python
vx_Biye_Design14 小时前
django房屋租赁推荐系统78455-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·express
学Linux的语莫16 小时前
python中类的常见写法
开发语言·python·状态模式
垆边人似月.17 小时前
Python中如何使用get函数实现频次查询
服务器·前端·python