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)