当前位置:   article > 正文

GPT-4o 上线 | 利用它助力图像结构化信息提取

gpt4o可以直接返回图片吗

点击下方卡片,关注“小白玩转Python”公众号

OpenAI最近发布了GPT-4o——据称是OpenAI最好的AI模型,但价格只有GPT-4的一半!这个新模型提供了实时的多模态能力,涵盖文本、视觉和音频,其智能水平与GPT-4Turbo相同,但效率更高——这意味着它具有更低的延迟,文本生成速度快2倍,而且非常重要的是,它的价格是GPT-4Turbo的一半。

动机

如果你需要分析图像以收集结构化信息,你来对地方了。在这篇文章中,我们将快速学习如何使用OpenAI最新最先进的模型——GPT-4o,从图像中提取结构化信息。

工作流程

首先导入相关的库:

  1. import base64
  2. import json
  3. import os
  4. import os.path
  5. import re
  6. import sys
  7. import pandas as pd
  8. import tiktoken
  9. import openai
  10. from openai import OpenAI

在本文中,我将使用以下图像进行演示。你可以对自己的图像应用相同的原理,提出任何问题:

424e4fd69687246124011a3629c6c3f2.jpeg用来提取信息的图像

步骤1:加载和编码图像

图像主要有两种方式提供给模型:通过传递图像链接或通过在请求中直接传递base64编码的图像。Base64是一种编码算法,可以将图像转换为可读的字符串。你可以在用户、系统和助手消息中传递图像。

由于我的图像存储在本地,让我们将本地图像编码为base64 URL。以下函数读取图像文件,确定其MIME类型,并将其编码为base64数据URL,适合传输到API:

  1. import base64
  2. from mimetypes import guess_type
  3. # Function to encode a local image into data URL
  4. def local_image_to_data_url(image_path):
  5. # Guess the MIME type of the image based on the file extension
  6. mime_type, _ = guess_type(image_path)
  7. if mime_type is None:
  8. mime_type = "application/octet-stream" # Default MIME type if none is found
  9. # Read and encode the image file
  10. with open(image_path, "rb") as image_file:
  11. base64_encoded_data = base64.b64encode(image_file.read()).decode("utf-8")
  12. # Construct the data URL
  13. return f"data:{mime_type};base64,{base64_encoded_data}"

步骤2:设置API客户端和模型

要构建流水线,首先使用我们的API密钥设置OpenAI API客户端:

  1. openai.api_key = 'your api key'
  2. client = OpenAI(api_key = openai.api_key)
  3. model = "gpt-4o"

这一步初始化OpenAI客户端,使我们能够与GPT-vision模型进行交互。现在,我们准备好运行流水线。

步骤3:运行GPT-4o流水线以处理图像并获取响应

在此代码中,我们遍历指定目录中的图像,编码每个图像,并向GPT-4o模型发送请求。模型被指示分析图像并提取结构化信息,返回的应该是JSON格式。

  1. #define the base directory for the images, encode them into base64, and use the model to extract structured information:
  2. base_dir = "data/"
  3. data_urls = []
  4. responses = []
  5. path = os.path.join(base_dir, "figures")
  6. if os.path.isdir(path): # Ensure it's a directory
  7. # use the image and ask question
  8. for image_file in os.listdir(path)[:1]:
  9. image_path = os.path.join(path, image_file)
  10. try:
  11. print(f"processing image: {image_path}")
  12. data_url = local_image_to_data_url(image_path)
  13. response = client.chat.completions.create(
  14. model=model,
  15. messages=[
  16. {
  17. "role": "system",
  18. "content": """
  19. You are `gpt-4o`, the latest OpenAI model that can interpret images and can describe images provided by the user
  20. in detail. The user has attached an image to this message for
  21. you to answer a question, there is definitely an image attached,
  22. you will never reply saying that you cannot see the image
  23. because the image is absolutely and always attached to this
  24. message. Answer the question asked by the user based on the
  25. image provided. Do not give any further explanation. Do not
  26. reply saying you can't answer the question. The answer has to be
  27. in a JSON format. If the image provided does not contain the
  28. necessary data to answer the question, return 'null' for that
  29. key in the JSON to ensure consistent JSON structure.
  30. """,
  31. },
  32. {
  33. "role": "user",
  34. "content": [
  35. {
  36. "type": "text",
  37. "text": """
  38. You are tasked with accurately interpreting detailed charts and
  39. text from the images provided. You will focus on extracting the price for all the DRINKS from the menu.
  40. Guidelines:
  41. - Include all the drinks in the menu
  42. - The output must be in JSON format, with the following structure and fields strictly adhered to:
  43. Response Format:
  44. The output must be in JSON format, with the following structure and key strictly adhered to:
  45. - dish: the name of the appetizer dish
  46. - price: the price of the appetizer dish
  47. - currency: the currency
  48. """,
  49. },
  50. {"type": "image_url", "image_url": {"url": data_url}},
  51. ],
  52. },
  53. ],
  54. max_tokens=3000,
  55. )
  56. content = response.choices[0].message.content
  57. responses.append(
  58. { "image": image_file, "response": content}
  59. )
  60. except Exception as e:
  61. print(f"error processing image {image_path}: {e}")
  62. responses

响应输出变量以JSON格式返回,按照我的提示请求,它看起来与参考照片一致。

  1. ```json
  2. [
  3. {
  4. "drink": "Purified Water",
  5. "price": 3.99,
  6. "currency": "$"
  7. },
  8. {
  9. "drink": "Sparkling Water",
  10. "price": 3.99,
  11. "currency": "$"
  12. },
  13. {
  14. "drink": "Soda In A Bottle",
  15. "price": 4.50,
  16. "currency": "$"
  17. },
  18. {
  19. "drink": "Orange Juice",
  20. "price": 6.00,
  21. "currency": "$"
  22. },
  23. {
  24. "drink": "Fresh Lemonade",
  25. "price": 7.50,
  26. "currency": "$"
  27. }
  28. ]
  29. ```

步骤4:将JSON格式转换为数据框

你还可以通过以下代码将JSON输出解析为数据框,从而创建结构化数据格式:

  1. def format_output_qa(output, debug = False):
  2. print(f"Raw model output: {output}")
  3. try:
  4. # cleanup the json output
  5. output_text = output.replace("\n", "")
  6. output_text=output_text.replace("```json", "")
  7. output_text=output_text.replace("```", "")
  8. if debug is True:
  9. return output_text
  10. # Now load it into a Python dictionary
  11. output_dict = json.loads(output_text)
  12. # create a df
  13. df = pd.DataFrame(output_dict)
  14. except Exception as e:
  15. print(f"Error processing output: {e}")
  16. df = pd.DataFrame({"error": str(e)}, index=[0])
  17. return df
  18. # Now process each response in the list
  19. df_output = pd.DataFrame()
  20. for response_dict in responses:
  21. response = response_dict["response"]
  22. df = format_output_qa(response)
  23. df["image"] = response_dict["image"]
  24. df_output = pd.concat([df_output, df], ignore_index=True)
  25. df_output

结果如下:

d653b121b933cd1737fe7d4c6a6d62ea.png

结论

这是一个简单而强大的流水线,利用GPT-4o的视觉能力从图像中提取数据,将非结构化的视觉数据转化为结构化数据以供进一步分析。无论你是在收集和分析视觉内容,这些步骤都为将图像处理集成到AI工作流程中提供了坚实的基础。

·  END  ·

HAPPY LIFE

f9fd513c92ef019158feb729d13af521.png

本文仅供学习交流使用,如有侵权请联系作者删除

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/954398
推荐阅读
相关标签
  

闽ICP备14008679号