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

相关推荐
MyhEhud28 分钟前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
狐凄42 分钟前
Python实例题:pygame开发打飞机游戏
python·游戏·pygame
漫谈网络1 小时前
Telnet 类图解析
python·自动化·netdevops·telnetlib·网络自动化运维
农夫山泉2号2 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI3 小时前
Flask Docker Demo 项目指南
python·docker·flask
码上淘金7 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo7 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552878 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子8 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174298 小时前
Python Day23 学习
python·学习