Create a function that generates an Excel file export (download option) from a generic, Pydantic-based document structure. The export should be adaptable to any document type (e.g., invoice, receipt, etc.) and follow this structure:
- Top-level (Document-level) Entities:
- Create a sheet (e.g., named "Document_Metadata") that contains standalone fields extracted from the document (e.g., invoice_number, invoice_date) as rows.
- Each row must include the following columns:
- Label: The hierarchical name of the field (e.g., "invoice_number", "seller.name").
- Value: The extracted value.
- Confidence: The model’s confidence score (e.g., 0.95).
- Source_Type: How the value was obtained (e.g., "OCR", "Rule-Based").
- Source_Text: The raw text from which the value was derived.
- Tables / List Entities:
- For each table-like entity (e.g., line_items, payment_details) or any list field:
- Create a separate sheet named according to the entity (e.g., "Line_Items").
- Represent each individual list item as a group of rows.
- Use an additional Group_ID column to group rows belonging to the same logical list item.
- Follow the same metadata columns (Label, Value, Confidence, Source_Type, Source_Text) for every row.
- Single-Row Lists:
- If a list contains only one row, treat it as a 1-row table (still keeping the same structure).
- Generality & Extensibility:
- The function should work generically for any document type defined by a Pydantic model.
- Implementation Notes:
- Use Python libraries such as pandas and openpyxl (or xlsxwriter) for generating the Excel file.
- Organize the code so that each sheet is built from converting the Pydantic objects (or their nested parts) into DataFrames, and then written into the Excel workbook.
Example (Invoice):
For an invoice, the first sheet ("Document_Metadata") would include fields like "invoice_number", "invoice_date" along with their confidence, source type, etc. Subsequent sheets (e.g., "Seller_Details", "Buyer_Details", "Line_Items", "Totals", "Payment_Details") would represent nested or list entities with Group_IDs as needed.
Deliverable:
Provide the Python code for this export functionality in a modular way so that it can be reused for any document type.
This should give your coding assistant clear guidance on creating an Excel export download option based on the agreed structure.