File size: 3,874 Bytes
fd842a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from __future__ import annotations

import os
import csv
import tempfile
from pathlib import Path

import gradio as gr

from document_processing import extract_text, is_image_document, to_data_uri
from receipt_ai import extract_receipt_json, extract_receipt_json_from_image
from receipt_results import build_empty_result


RESULT_COLUMNS = [
    "source_file",
    "document_type",
    "fecha",
    "fecha_vencimiento",
    "cuit_proveedor",
    "description_proveedor",
    "moneda",
    "subtotal",
    "taxes",
    "total",
    "confidence",
]


def parse_uploaded_file(client, model: str, file_path: str) -> dict:
    path = Path(file_path)
    if is_image_document(path):
        result = extract_receipt_json_from_image(client, model, path, to_data_uri(path))
    else:
        text = extract_text(path)
        if not text.strip():
            return build_empty_result(path.name)
        result = extract_receipt_json(client, model, path, text)

    result["source_file"] = path.name
    return result


def rows_to_table(rows: list[dict]) -> list[list[object]]:
    return [[row.get(column) for column in RESULT_COLUMNS] for row in rows]


def build_csv_download(rows: list[dict]) -> str:
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline="", encoding="utf-8")
    with temp_file as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=RESULT_COLUMNS)
        writer.writeheader()
        for row in rows:
            writer.writerow({column: row.get(column) for column in RESULT_COLUMNS})

    return temp_file.name


def process_files(files: list[str] | None, existing_rows: list[dict] | None, model: str):
    from dotenv import load_dotenv
    from openai import OpenAI

    load_dotenv()
    client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

    rows = list(existing_rows or [])
    if not files:
        return rows, gr.update(value=rows_to_table(rows)), "No files selected."

    for file_path in files:
        rows.append(parse_uploaded_file(client, model, file_path))

    return rows, gr.update(value=rows_to_table(rows)), f"Parsed {len(files)} file(s). Total rows: {len(rows)}."


def clear_results():
    return [], gr.update(value=[]), "Results cleared."


def build_app() -> gr.Blocks:
    default_model = os.getenv("OPENAI_MODEL", "gpt-4o")

    with gr.Blocks(title="Document Parser", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# Purchase Receipt Parser\nUpload one or more files and append the extracted receipt data into the grid.")

        with gr.Row():
            files = gr.File(label="Upload files", file_count="multiple", type="filepath")
            model = gr.Textbox(label="Model", value=default_model)

        status = gr.Markdown("Ready.")
        results_state = gr.State([])
        results_grid = gr.Dataframe(
            label="Parsed documents",
            headers=RESULT_COLUMNS,
            value=[],
            interactive=False,
            wrap=True,
        )

        with gr.Row():
            parse_button = gr.Button("Parse documents", variant="primary")
            clear_button = gr.Button("Clear grid")
            download_button = gr.DownloadButton(label="Download CSV", variant="secondary", value=build_csv_download, inputs=[results_state])

        parse_button.click(
            process_files,
            inputs=[files, results_state, model],
            outputs=[results_state, results_grid, status],
        )

        clear_button.click(
            clear_results,
            inputs=[],
            outputs=[results_state, results_grid, status],
        )

    return demo


if __name__ == "__main__":
    share_enabled = True

    try:
        build_app().launch(share=True)
    except Exception as exc:
        print(f"Share link unavailable ({exc}). Starting local-only Gradio app instead.")
        build_app().launch(share=False)