首页 > 编程问答 >将提示和 PDF 传递到 Gemini API 时“无法创建‘Blob’”

将提示和 PDF 传递到 Gemini API 时“无法创建‘Blob’”

时间:2024-07-23 14:33:14浏览次数:7  
标签:python google-gemini

我正在尝试将提示和 PDF 文件传递​​给 Google Gemini API。我遵循了所有文档,但由于某种原因我仍然遇到问题。

这是代码:

def get_vision_response(pdf_file):
    try:
        genai.configure(api_key=GOOGLE_API_KEY)

        model = genai.GenerativeModel(
            model_name="gemini-1.5-pro-latest",
            system_instruction=[
                "You are a helpful transcriber that can accurately transcribe text from images and PDFs.",
                "Your mission is to transcribe text from the provided PDF file.",
            ],
        )

        pdf_part = Part.from_data(pdf_file, mime_type="application/pdf")

        prompt = "Please transcribe the text in this PDF document."

        full_content = [prompt, pdf_part]
        
        response = model.generate_content(full_content)
        
        return response.text
        
    except Exception as e:
        print("An error occurred during the model invocation")
        
        # Save the error message to a text file
        with open("error_log.txt", "w") as error_file:
            error_file.write(f"An error occurred: {str(e)}\n")

当我尝试在异常中打印我的错误时,它充满了垃圾字符,所以我不得不将其保存到一份文件。这是我的错误的标头部分:

发生错误:无法创建 Blob ,预期 Blob dict Image 类型( PIL.Image.Image IPython.display.Image )。有一个: <class 'vertexai.generative_models. generative_models.Part'> 值: inline_data { mime_type:“应用程序/pdf”数据: "%PDF-1.7\n%\302\265\302\266\n\n1 0 obj\n<</类型/目录/页数 2 0 R>>\nendobj\n\n2 0 obj\n<</类型/页数/计数 1/儿童[669 0 R]>>\nendobj\n\n3 0 obj\n<</Filter/FlateDecode/Length 9963>>\n流\nx\001\305\235\313\256t\307m\205\347\347)z\234\301Q\357[ \200 \003+\201\221\241a\001\031\307Jd \200\0238\377\373\003\371X\227E\262\252Z\323\3000$\365\256\033\271H\026k\025\367>\177\277\375\351\366\367 \333\235\377=\266\375\366|\357\267\377\375\317\333\277\335\37

有谁知道如何解决这个问题?


此错误消息表明 Gemini API 期望图像作为输入而不是原始 PDF 数据。尽管 Gemini 可以处理 PDF 文件,但需要先将这些文件转换为图像表示形式,然后再将其发送到 API。

可以通过以下两种方法解决此问题:

1. 使用 Python 库在本地转换 PDF 为图像:

可以使用一个库(如 pdf2image PyMuPDF )将 PDF 页面渲染为图像。然后,可以将这些图像传递给 Gemini API。

以下是如何使用 pdf2image 的示例:

from pdf2image import convert_from_bytes

def get_vision_response(pdf_file):
    try:
        images = convert_from_bytes(pdf_file) 

        genai.configure(api_key=GOOGLE_API_KEY)

        model = genai.GenerativeModel(
            model_name="gemini-1.5-pro-latest",
            system_instruction=[
                "You are a helpful transcriber that can accurately transcribe text from images and PDFs.",
                "Your mission is to transcribe text from the provided PDF file.",
            ],
        )

        parts = []
        for image in images:
            # 将 PIL 图像转换为字节
            from io import BytesIO
            buffered = BytesIO()
            image.save(buffered, format="PNG")
            image_bytes = buffered.getvalue()
            parts.append(Part.from_data(image_bytes, mime_type="image/png"))

        prompt = "Please transcribe the text in this PDF document."
        full_content = [prompt, *parts] 

        response = model.generate_content(full_content)

        return response.text

    except Exception as e:
        print("An error occurred during the model invocation")

        # Save the error message to a text file
        with open("error_log.txt", "w") as error_file:
            error_file.write(f"An error occurred: {str(e)}\n")

2. 使用 Google Cloud AI Document AI API:

更强大的方法是使用 Google Cloud AI Document AI API。此 API 可以分析的 PDF,提取文本、表格和更多结构化数据。然后,可以将此结构化数据传递给 Gemini API 以获得更准确的转录。

以下是如何使用 Document AI API 的示例:

import os
from google.cloud import documentai_v1 as documentai

def get_vision_response(pdf_file):
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "YOUR_SERVICE_ACCOUNT_KEY.json" 

    client = documentai.DocumentProcessorServiceClient()

    # 需要更新此名称以匹配的 Document AI 处理器位置
    name = f"projects/{project_id}/locations/{location}/processors/{processor_id}"

    image = {"content": pdf_file, "mime_type": "application/pdf"}
    request = {"name": name, "raw_document": image}

    result = client.process_request(request=request)
    document = result.document

    text = document.text

    genai.configure(api_key=GOOGLE_API_KEY)

    model = genai.GenerativeModel(
        model_name="gemini-1.5-pro-latest",
        system_instruction=[
            "You are a helpful transcriber that can accurately transcribe text.",
            "Your mission is to transcribe the following text."
        ],
    )

    prompt = f"Please transcribe the following text: {text}"

    response = model.generate_content(prompt)

    return response.text 

请记住,需要安装必要的库 ( pdf2image documentai ) 并为 Document AI API 设置的 Google Cloud 项目。

通过使用这些方法,可以有效地将 PDF 数据传递给 Gemini API 并利用其功能进行转录或其他基于语言的任务。

标签:python,google-gemini
From: 78685076

相关文章

  • Python中如何实现字符串的查询和替换?
    在Python中,字符串的查询和替换是编程中常见的任务,它们可以通过Python的内置方法和库来高效实现。这些操作对于文本处理、数据清洗、日志分析等场景尤为重要。下面,我将详细阐述如何在Python中实现字符串的查询和替换,包括基础方法、高级技巧以及在实际应用中的注意事项。字符......
  • Python中的`range()`函数及其用法
    range()函数是Python中的一个内置函数,它用于生成一个数字序列。这个函数在循环结构中尤其有用,因为它允许我们迭代一系列的数字,而无需显式地创建这些数字的列表。range()函数通过指定起始值、结束值(不包括)和步长(可选)来工作,返回一个可迭代对象,通常用于for循环中。下面将......
  • python 的注释(例如数据类)可以扩展到它生成的代码中吗?
    能看出python的注释扩展成​​什么吗?例如,对于与数据类相关的错误,有时试图找出它实际生成的代码有点棘手。例如:@dataclass(order=True)classPerson:name:strage:int=0classPerson:def__init__(self,name:str,age=0):self.name=name......
  • Docker:无法在 docker 映像中使用 pythonnet 和 |无法创建默认的 .NET 运行时,该运行时
    我正在尝试使用clrfromPythonnet使用.DLL引用将一种文件类型转换为另一种文件类型。这就是我的代码的样子-importclrclr.AddReference(dll_path)importRxLibrary#ConverttoASCFormat-----------input_file=f"./{filename}.rxd"......
  • 在 Python 中以非常高的质量保存图像
    如何以非常高的质量保存Python绘图?也就是说,当我不断放大PDF文件中保存的对象时,为什么没有任何模糊?另外,什么是最好的模式将其保存在?png,eps?或者其他的?我不能pdf,因为有一个隐藏的数字会扰乱Latexmk编译。要以非常高的质量保存Py......
  • Python字符串:提取重复和随机合并的子字符串
    重复和合并字符串的示例:16.01068.0%08p%.a.p.a.要提取的所需子字符串:16.008%p.a.完整示例:CCoonnttiinnggeennttCCoouuppoonn16.01068.0%08p%.a.p(.Ma.o(nMtholyn)thly)所需子字符串:ContingentCoupon16.008%p.a.(Monthly)我的问题是当原始......
  • Python Pandas 从使用第 3 部分 API 自动生成的 Excel 文件中读取不一致的日期格式
    我正在使用PDF4meAPI将PDF发票转换为Excel文件。API可以正确读取日期。但是,当我打开Excel文件时,日期显示不一致:某些日期以正确的格式(dd/mm/yyyy)显示,而其他日期以错误的mm/dd/yyyy格式显示。当该月的某天小于或等于12时,似乎会出现这种不一致。......
  • python-input键盘输入
     str=input("请输入:")#用户键盘输入#str表示一个字符串类型的变量,input会将读取到的字符串放入str中print(str) aa='请输入:'str=input(aa)#用户键盘输入#str表示一个字符串类型的变量,input会将读取到的字符串放入str中print(str)      ......
  • Python从0到100(四十五):从字符串到前后端分离
    前言:零基础学Python:Python从0到100最新最全教程。想做这件事情很久了,这次我更新了自己所写过的所有博客,汇集成了Python从0到100,共一百节课,帮助大家一个月时间里从零基础到学习Python基础语法、Python爬虫、Web开发、计算机视觉、机器学习、神经网络以及人工智能相关知......
  • Python的运算符与条件表达式
    一、运算符Python数据是通过使用运算符来进行操作的,与数学运算符类似,主要运用于数字计算,比较大小和逻辑运算。Python中的运算符主要包括算术运算符、赋值运算符、比较运算符、逻辑运算符和位运算符。1.算术运算符算术运算符用在数字表达式中,作用和在数学中是一样的。Python......