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

相关推荐
夏天拐跑了西瓜7 小时前
一文入门LangChain:从框架认知到构建你的第一个AI Agent
python·langchain·conda·agent
魔猴疯猿8 小时前
从0到1用Python开发第一个智能体
人工智能·python·深度学习·神经网络·机器学习
xiaoqi01959 小时前
机器学习因子分析实战:从量化特征到可视化决策
人工智能·python·机器学习
Escalating_xu9 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
happylifetree9 小时前
Python14:核心语法-数据存储与运算-字符串定义
python
hhb_61810 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
小静AI工程实验室10 小时前
asyncio.Queue 有界队列实战:背压、task_done、join 与异常收尾
python
小凡geo10 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
Zhou14113610 小时前
SpringBoot_03_Web开发
前端·spring boot·python
weixin1997010801610 小时前
《1688物流API接口边界:logistics.trace.get 与 freight.template.list 的隐藏约束》(附Python源码)
windows·python·list