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

相关推荐
AI探索者11 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者11 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh13 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅13 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿20 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python