跳到内容

使用 GPT-Vision 提取表格

本文演示了如何使用 Python 的类型注解和 OpenAI 新的视觉模型从图像中提取表格并将其转换为 Markdown 格式。这种方法对于数据分析和自动化任务特别有用。

完整代码可在 GitHub 上获取

构建 Markdown 表格的自定义类型

首先,我们定义一个自定义类型 `MarkdownDataFrame`,用于处理以 Markdown 格式表示的 pandas DataFrame。这种类型使用 Python 的 `Annotated` 和 `InstanceOf` 类型,以及 `@BeforeValidator` 和 `@PlainSerializer` 装饰器来处理和序列化数据。

from io import StringIO
from typing import Annotated, Any
from pydantic import BeforeValidator, PlainSerializer, InstanceOf, WithJsonSchema
import pandas as pd


def md_to_df(data: Any) -> Any:
    # Convert markdown to DataFrame
    if isinstance(data, str):
        return (
            pd.read_csv(
                StringIO(data),  # Process data
                sep="|",
                index_col=1,
            )
            .dropna(axis=1, how="all")
            .iloc[1:]
            .applymap(lambda x: x.strip())
        )
    return data


MarkdownDataFrame = Annotated[
    InstanceOf[pd.DataFrame],
    BeforeValidator(md_to_df),
    PlainSerializer(lambda df: df.to_markdown()),
    WithJsonSchema(
        {
            "type": "string",
            "description": "The markdown representation of the table, each one should be tidy, do not try to join tables that should be seperate",
        }
    ),
]

定义 Table 类

`Table` 类对于组织提取的数据至关重要。它包括一个标题和一个 DataFrame,这些都以 Markdown 表格格式处理。由于大部分复杂性由 `MarkdownDataFrame` 类型处理,因此 `Table` 类非常直观!

from pydantic import BaseModel



class Table(BaseModel):
    caption: str
    dataframe: MarkdownDataFrame

从图像中提取表格

`extract_table` 函数使用 OpenAI 的视觉模型来处理图像 URL 并以 Markdown 格式提取表格。我们利用 `instructor` 库来修补 OpenAI 客户端以实现此目的。

import instructor
from openai import OpenAI
from typing import Iterable


# Apply the patch to the OpenAI client to support response_model
# Also use MD_JSON mode since the vision model does not support any special structured output mode
client = instructor.from_openai(OpenAI(), mode=instructor.function_calls.Mode.MD_JSON)


def extract_table(url: str) -> Iterable[Table]:
    return client.chat.completions.create(
        model="gpt-4o-mini",
        response_model=Iterable[Table],
        max_tokens=1800,
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Extract table from image."},
                    {"type": "image_url", "image_url": {"url": url}},
                ],
            }
        ],
    )

实际示例

在此示例中,我们应用该方法从一张图像中提取数据,该图像显示了 2023 年 10 月爱尔兰收入最高的应用。

url = "https://a.storyblok.com/f/47007/2400x2000/bf383abc3c/231031_uk-ireland-in-three-charts_table_v01_b.png"
tables = extract_table(url)
for table in tables:

    print(table.dataframe)
    """
                                      Android App   ... Category
     Android Rank                                   ...
    1                                   Google One  ...    Social networking
    2                                      Disney+  ...        Entertainment
    3                TikTok - Videos, Music & LIVE  ...        Entertainment
    4                             Candy Crush Saga  ...        Entertainment
    5               Tinder: Dating, Chat & Friends  ...                Games
    6                                  Coin Master  ...        Entertainment
    7                                       Roblox  ...               Dating
    8               Bumble - Dating & Make Friends  ...                Games
    9                                  Royal Match  ...             Business
    10                 Spotify: Music and Podcasts  ...            Education

    [10 rows x 5 columns]
    """
点击展开查看输出

Top 10 Grossing Apps in October 2023 for Ireland

2023 年 10 月 (爱尔兰) Android 平台收入最高的 10 款应用

排名 应用名称 类别
1 Google One 生产力
2 Disney+ 娱乐
3 TikTok - Videos, Music & LIVE 娱乐
4 Candy Crush Saga 游戏
5 Tinder: Dating, Chat & Friends 社交网络
6 Coin Master 游戏
7 Roblox 游戏
8 Bumble - Dating & Make Friends 交友
9 Royal Match 游戏
10 Spotify: Music and Podcasts 音乐与音频

2023 年 10 月 (爱尔兰) iOS 平台收入最高的 10 款应用

排名 应用名称 类别
1 Tinder: Dating, Chat & Friends 社交网络
2 Disney+ 娱乐
3 YouTube: Watch, Listen, Stream 娱乐
4 Audible: Audio Entertainment 娱乐
5 Candy Crush Saga 游戏
6 TikTok - Videos, Music & LIVE 娱乐
7 Bumble - Dating & Make Friends 交友
8 Roblox 游戏
9 LinkedIn: Job Search & News 商业
10 Duolingo - Language Lessons 教育