Ankushbl6 commited on
Commit
56bddc7
·
verified ·
1 Parent(s): 9434c09

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +181 -261
src/streamlit_app.py CHANGED
@@ -781,159 +781,79 @@ def _encode_page(page: Image.Image, page_idx: int, max_dim: int = MAX_DIMENSION_
781
 
782
 
783
  def run_inference_vllm(images: List[Image.Image]) -> str | None:
784
- EXTRACTION_PROMPT = """Extract structured data from the provided invoice image(s). Return a single JSON object with three sections: header, items, summary.
785
-
786
- ## Output Schema
787
-
788
- Return this exact structure. Use empty string "" for any field not found.
789
-
790
- json
791
  {
792
  "header": {
793
- "invoice_no": "",
794
- "po_no": "",
795
- "invoice_date": "",
796
- "payment_terms": "",
797
- "due_date": "",
798
- "sender_name": "",
799
- "sender_addr": "",
800
- "tax_id": "",
801
- "rcpt_name": "",
802
- "rcpt_addr": "",
803
- "bank_iban": "",
804
- "bank_name": "",
805
- "bank_acc_no": "",
806
- "bank_routing": "",
807
- "bank_swift": "",
808
- "bank_acc_name": "",
809
- "bank_branch": ""
810
  },
811
  "items": [
812
  {
813
- "service_name": "",
814
- "service_start_date": "",
815
- "service_end_date": "",
816
- "descriptions": "",
817
- "SKU": "",
818
- "quantity": "",
819
- "unit_price": "",
820
- "amount": "",
821
- "discount_rate_per_item": "",
822
- "discount_amount_per_item": "",
823
- "tax_rate_per_item": "",
824
- "tax_amount_per_item": "",
825
- "line_total": ""
826
  }
827
  ],
828
  "summary": {
829
- "subtotal": "",
830
- "tax_rate": "",
831
- "tax_amount": "",
832
- "discount_rate": "",
833
- "total_discount_amount": "",
834
- "total_amount": "",
835
- "currency": ""
836
  }
837
  }
838
-
839
-
840
-
841
- ## Core Rules
842
-
843
- 1. EXTRACT ONLY WHAT IS EXPLICITLY VISIBLE. Never compute, derive, infer totals, or fill missing values via arithmetic. The following format normalizations and explicit-data operations ARE permitted:
844
- - Bracketed amounts → negative: (100.00) → "-100.00".
845
- - Date ranges → expanded to full start/end dates using the invoice year.
846
- - Language normalization of payment terms → English.
847
- - Summing multiple tax AMOUNTS shown separately into one combined amount.
848
- - Summing multiple discount AMOUNTS shown separately into one combined amount.
849
- - Default quantity to "1.00" when unit_price and amount are both shown and equal, with no quantity printed.
850
- - Setting tax to "0.00" when "No VAT" / "VAT Exempt" is explicitly stated, OR when a tax rate is shown but tax amount is blank AND subtotal equals total as printed.
851
-
852
- 2. Return "" for any field not present or not clearly identifiable.
853
-
854
- 3. PRESERVE ORIGINAL FORMATTING for numbers (commas, decimals) and dates (except for date-range expansion noted above). For tax_rate and discount_rate, preserve exactly as printed including any % symbol.
855
-
856
- 4. STRIP CURRENCY SYMBOLS from all amount/price fields. Place currency code (USD, EUR, GBP, INR, etc.) only in summary.currency. If multiple currencies appear, use the currency of total_amount. If no currency is shown anywhere on the invoice, set summary.currency to "".
857
-
858
- 5. MULTI-PAGE: Merge all pages into one JSON object. Extract every line item as printed — do not deduplicate. Only skip a row if it is clearly a continuation header (e.g., the row repeats the table column titles like "Description / Qty / Price").
859
-
860
- 6. NO DUPLICATION ACROSS SCHEMA SECTIONS: If a value appears in the line items area of the invoice, place it only in the items array of the schema. If it appears in the summary/totals area (the section at the bottom showing subtotal, tax, discount, and total — separate from the itemized table), place it only in the summary object of the schema. Do not copy the same value into both unless the invoice explicitly prints it in both areas.
861
-
862
- 7. OUTPUT ONLY THE JSON. No preamble, no markdown fences, no explanation.
863
-
864
- 8. INCLUDE ALL LINE ITEMS, even those with a zero amount, zero quantity, or negative amount. Never skip a line item because its value is 0 or negative. This applies equally to credit notes and adjustments. Negative quantities, if printed, are extracted as-is (preserve the negative sign).
865
-
866
- 9. NO LINE ITEMS: If the invoice shows no individual line items (e.g., a flat-fee invoice with only a total), return an empty array: "items": [].
867
-
868
- 10. CONFLICTING VALUES: If the invoice shows two different totals (e.g., "Total" and "Amount Due"), prefer the value labeled as the final payable amount ("Amount Due", "Balance Due", "Total Payable", "Grand Total").
869
-
870
- ## Field Rules
871
-
872
- ### Sender & Recipient
873
-
874
- 1.sender_name: The invoicing company/person. Prefer company name over person name.
875
- 2.sender_addr: The full address of the invoicing entity, wherever it appears on the invoice.
876
- 3.tax_id: Always the SENDER's tax ID / VAT number. Never the recipient's.
877
- 4.rcpt_name: The name of the recipient, customer, or entity being billed.
878
- 5.rcpt_addr: The address of the recipient, customer, or entity being billed.
879
-
880
- ### PO Number
881
-
882
- 1.po_no: Extract if a single PO number is shown. If the same PO number appears multiple times on the invoice (e.g., header and footer), extract it once. If multiple DISTINCT PO numbers are present, return "".
883
-
884
- ### Bank Details
885
-
886
- 1.Prefer the bank account matching the invoice currency (USD invoice → USD account).
887
- 2.If no currency-matching account exists, extract the only available account.
888
- 3.If multiple non-matching accounts exist with no currency-matching account, return "" for all bank fields.
889
- 4.bank_acc_name: The name of the account holder. It may also appear in phrases such as “Cheques should be payable to” or “Remittance should be payable to.” Extract the mentioned company/entity name as the bank_acc_name.
890
-
891
- ### Dates
892
-
893
- 5.Preserve the original date format exactly as printed.
894
- 6.Date range exception: When a service period is shown as a range (e.g., "Feb 1-3"), expand to two full dates: service_start_date: "Feb 1 2026", service_end_date: "Feb 3 2026". Use the invoice year if the range omits a year.
895
- 7.due_date: If multiple due dates, extract only the first. If payment terms are "due on receipt" / "due on presentation" / "immediate", set due_date = invoice_date.
896
- 8.payment_terms: Normalize to English ("30 jours" → "30 days", "60 gg df" → "60 days").
897
-
898
- ### Descriptions
899
-
900
- 1.service_name: A short label, product name, or service title (e.g., "Consulting", "Web Hosting", "Premium Plan").
901
- 2.descriptions: The full detailed description text of the line item.
902
- 3.If the line item shows both a short label and a longer expanded text → put the short label in service_name and the longer text in descriptions.
903
- 4.If only one text is available for the line item → place it in descriptions and leave service_name as "".
904
- 5.If a SKU/code appears together with descriptive text (e.g., "SKU-12345 — Premium Web Hosting") → put the SKU in SKU, the descriptive portion in descriptions, and leave service_name as "" unless a separate short label also exists.
905
- 6.Do not extract handwritten annotations or stamps unless they are clearly legible and printed-quality. When in doubt, extract only the printed text.
906
-
907
- ### Amounts, Tax & Discounts
908
-
909
- 1.Preserve original number formatting (commas, decimals) exactly as printed. Do not reinterpret decimal separators — preserve as written (European 1.234,56 stays 1.234,56; US 1,234.56 stays 1,234.56).
910
- 2.Bracketed amounts are negative: (100.00) → "-100.00".
911
- 3."No VAT" / "VAT Exempt" → set relevant tax field to "0.00".
912
- 4.Tax rate shown but tax amount blank AND subtotal equals total as printed → tax amount = "0.00".
913
- 5.Tax-inclusive pricing: If the invoice states "all prices include VAT" or "tax-inclusive pricing", extract amount as printed without separating tax. Extract summary.tax_amount, summary.tax_rate, tax_rate_per_item, and tax_amount_per_item exactly as printed on the invoice — do not attempt to back-calculate.
914
- 6.Summing multiple values:
915
- - Multiple tax AMOUNTS shown separately → sum into one combined amount in the appropriate field.
916
- - Multiple DISCOUNT AMOUNTS shown separately → sum into one combined amount in the appropriate field.
917
- - Multiple tax RATES (e.g., 5% CGST + 12% SGST) → do NOT sum. Concatenate as printed (e.g., "5% + 12%") or extract the dominant rate as printed. Never produce a summed rate like "17%".
918
- 7.0Gross vs. Net amount columns: If both gross and net per-line amounts are shown, use the NET (pre-tax) amount as amount.
919
- 8.Discount/tax as a line item: If discount or tax appears as a row in the line items table — identified by labels such as "Discount", "Rebate", "Tax", "VAT", "Adjustment", or by being a negative-value row with no quantity/unit price — create a separate entry in the items array. Populate ONLY descriptions, the relevant discount/tax fields (discount_rate_per_item, discount_amount_per_item, tax_rate_per_item, tax_amount_per_item), and line_total. Leave quantity, unit_price, and amount as "".
920
- 9.Discount/tax in the totals/summary area: Place only in the summary object of the schema. Do not duplicate into the items array.
921
-
922
- ### Quantity & Unit Price
923
-
924
- 1.If unit_price and amount are shown and equal but no quantity is printed → quantity: "1.00".
925
- 2.If the invoice uses alternate labels for quantity (e.g., impressions, units, hours, sessions, clicks) and unit price (e.g., CPM, rate, cost per unit), map them to quantity and unit_price respectively.
926
- 3.If both a standard quantity and an alternate metric are shown, extract the standard quantity.
927
- 4.Negative quantities (e.g., on credit notes) are preserved as-is with the negative sign.
928
-
929
- ### Line Total
930
-
931
- line_total: Extract ONLY if ALL these conditions are met:
932
- 1. The invoice explicitly prints a dedicated line total column or value for the row.
933
- 2. The invoice has NO separate per-line tax column or per-line tax amount anywhere.
934
- 3. The invoice has NO separate per-line discount column or per-line discount amount anywhere.
935
- If any per-line tax or discount column exists anywhere on the invoice → set line_total to "" for ALL rows.
936
- If no line total column exists on the invoice → line_total = ""."""
937
 
938
  if not images:
939
  st.error("No images provided to run_inference_vllm.")
@@ -2526,127 +2446,127 @@ elif len(st.session_state.batch_results) > 0:
2526
  with frame_right:
2527
  st.subheader(f"Editable Invoice: {current['file_name']}")
2528
 
2529
- with st.form(key=f"edit_form_{selected_hash}", clear_on_submit=False):
2530
- tabs = st.tabs(["Invoice Details", "Sender/Recipient", "Bank Details", "Line Items"])
2531
-
2532
- with tabs[0]:
2533
- st.text_input("Invoice Number", key=f"Invoice Number_{selected_hash}")
2534
- st.text_input("PO Number", key=f"PO Number_{selected_hash}")
2535
-
2536
- st.write("**Invoice Date:**")
2537
- raw_invoice_date = form_data.get("Invoice Date", "")
2538
- if raw_invoice_date:
2539
- st.info(f"📅 Model extracted: {raw_invoice_date}")
2540
- st.date_input("Select date:", key=f"Invoice Date_{selected_hash}",
2541
- format="DD/MM/YYYY", label_visibility="collapsed")
2542
-
2543
- st.text_input("Payment Terms", key=f"Payment Terms_{selected_hash}")
2544
-
2545
- st.write("**Due Date:**")
2546
- raw_due_date = form_data.get("Due Date", "")
2547
- if raw_due_date:
2548
- st.info(f"📅 Model extracted: {raw_due_date}")
2549
- st.date_input("Select date:", key=f"Due Date_{selected_hash}",
2550
- format="DD/MM/YYYY", label_visibility="collapsed")
2551
-
2552
- st.text_input("Tax ID / VAT Number", key=f"Tax ID_{selected_hash}")
2553
-
2554
- curr_options = ["USD", "EUR", "GBP", "INR", "Other"]
2555
- if st.session_state[f"Currency_{selected_hash}"] not in curr_options:
2556
- st.session_state[f"Currency_{selected_hash}"] = "Other"
2557
- st.selectbox("Currency", options=curr_options, key=f"Currency_{selected_hash}")
2558
- if st.session_state.get(f"Currency_{selected_hash}") == "Other":
2559
- st.text_input("Specify Currency", key=f"Currency_Custom_{selected_hash}")
2560
-
2561
- st.number_input("Subtotal", key=f"Subtotal_{selected_hash}", format="%.3f", step=0.001)
2562
- st.number_input("Tax %", key=f"Tax Percentage_{selected_hash}", format="%.3f", step=0.001)
2563
- st.number_input("Total Tax", key=f"Total Tax_{selected_hash}", format="%.3f", step=0.001)
2564
- st.number_input("Discount Rate %", key=f"Discount Rate_{selected_hash}", format="%.3f", step=0.001)
2565
- st.number_input("Total Discount Amount", key=f"Total Discount Amount_{selected_hash}", format="%.3f", step=0.001)
2566
- st.number_input("Total Amount", key=f"Total Amount_{selected_hash}", format="%.3f", step=0.001)
2567
-
2568
- with tabs[1]:
2569
- st.text_input("Sender Name", key=f"Sender Name_{selected_hash}")
2570
- st.text_area ("Sender Address", key=f"Sender Address_{selected_hash}", height=80)
2571
- st.text_input("Recipient Name", key=f"Recipient Name_{selected_hash}")
2572
- st.text_area ("Recipient Address", key=f"Recipient Address_{selected_hash}", height=80)
2573
-
2574
- with tabs[2]:
2575
- st.text_input("Bank Name", key=f"Bank_bank_name_{selected_hash}")
2576
- st.text_input("Account Number", key=f"Bank_bank_account_number_{selected_hash}")
2577
- st.text_input("Account Name", key=f"Bank_bank_acc_name_{selected_hash}")
2578
- st.text_input("IBAN", key=f"Bank_bank_iban_{selected_hash}")
2579
- st.text_input("SWIFT", key=f"Bank_bank_swift_{selected_hash}")
2580
- st.text_input("Routing", key=f"Bank_bank_routing_{selected_hash}")
2581
- st.text_input("Branch", key=f"Bank_bank_branch_{selected_hash}")
2582
-
2583
- with tabs[3]:
2584
- items_state_key = f"items_df_{selected_hash}"
2585
-
2586
- if items_state_key not in st.session_state:
2587
- item_rows = form_data.get("Itemized Data", []) or []
2588
- normalized = []
2589
- for it in item_rows:
2590
- if not isinstance(it, dict):
2591
- it = {}
2592
- normalized.append({
2593
- "Description": it.get("Description", it.get("Item Description", "")),
2594
- "Service Name": it.get("Service Name", ""),
2595
- "Service Start Date": it.get("Service Start Date", ""),
2596
- "Service End Date": it.get("Service End Date", ""),
2597
- "SKU": it.get("SKU", ""),
2598
- "Quantity": editable_numeric_value("Quantity", it.get("Quantity", it.get("Item Quantity", 0.0))),
2599
- "Unit Price": editable_numeric_value("Unit Price", it.get("Unit Price", it.get("Item Unit Price", 0.0))),
2600
- "Amount": editable_numeric_value("Amount", it.get("Amount", it.get("Item Amount", 0.0))),
2601
- "Discount Rate Per Item": editable_numeric_value("Discount Rate Per Item", it.get("Discount Rate Per Item", 0.0)),
2602
- "Discount Amount Per Item": editable_numeric_value("Discount Amount Per Item", it.get("Discount Amount Per Item", 0.0)),
2603
- "Tax Rate Per Item": editable_numeric_value("Tax Rate Per Item", it.get("Tax Rate Per Item", 0.0)),
2604
- "Tax Amount Per Item": editable_numeric_value("Tax Amount Per Item", it.get("Tax Amount Per Item", 0.0)),
2605
- "IO Number/Cost Centre": it.get("IO Number/Cost Centre", ""),
2606
- "Line Total": editable_numeric_value("Line Total", it.get("Line Total", it.get("Item Line Total", 0.0))),
2607
- })
2608
- st.session_state[items_state_key] = coerce_numeric_items_df(
2609
- pd.DataFrame(normalized) if normalized
2610
- else pd.DataFrame(columns=[
2611
- "Description", "Service Name", "Service Start Date", "Service End Date", "SKU",
2612
- "Quantity", "Unit Price", "Amount",
2613
- "Discount Rate Per Item", "Discount Amount Per Item",
2614
- "Tax Rate Per Item", "Tax Amount Per Item",
2615
- "IO Number/Cost Centre", "Line Total"
2616
- ])
2617
- )
2618
 
2619
- items_df = coerce_numeric_items_df(st.session_state[items_state_key])
2620
- st.session_state[items_state_key] = items_df
2621
-
2622
- column_config = {
2623
- "Description": st.column_config.TextColumn("Description", width="large"),
2624
- "Service Name": st.column_config.TextColumn("Service Name", width="medium"),
2625
- "Service Start Date": st.column_config.TextColumn("Svc Start", width="small"),
2626
- "Service End Date": st.column_config.TextColumn("Svc End", width="small"),
2627
- "SKU": st.column_config.TextColumn("SKU", width="small"),
2628
- "Quantity": st.column_config.NumberColumn("Qty", width="small", format="%.3f", step=0.001),
2629
- "Unit Price": st.column_config.NumberColumn("Unit Price", width="small", format="%.3f", step=0.001),
2630
- "Amount": st.column_config.NumberColumn("Amount", width="small", format="%.3f", step=0.001),
2631
- "Discount Rate Per Item": st.column_config.NumberColumn("Disc %", width="small", format="%.3f", step=0.001),
2632
- "Discount Amount Per Item": st.column_config.NumberColumn("Disc Amt", width="small", format="%.3f", step=0.001),
2633
- "Tax Rate Per Item": st.column_config.NumberColumn("Tax %", width="small", format="%.3f", step=0.001),
2634
- "Tax Amount Per Item": st.column_config.NumberColumn("Tax Amt", width="small", format="%.3f", step=0.001),
2635
- "IO Number/Cost Centre": st.column_config.TextColumn("IO/Cost Centre", width="medium"),
2636
- "Line Total": st.column_config.NumberColumn("Line Total", width="small", format="%.3f", step=0.001),
2637
- }
2638
 
2639
- edited_df = st.data_editor(
2640
- items_df,
2641
- num_rows="dynamic",
2642
- key=f"items_editor_{selected_hash}",
2643
- use_container_width=True,
2644
- height=DATA_EDITOR_HEIGHT,
2645
- column_config=column_config,
2646
- )
2647
- st.session_state[items_state_key] = coerce_numeric_items_df(edited_df)
2648
 
2649
- saved = st.form_submit_button("💾 Save All Edits")
2650
 
2651
  currency = st.session_state.get(f"Currency_{selected_hash}", "USD")
2652
  if currency == "Other":
 
781
 
782
 
783
  def run_inference_vllm(images: List[Image.Image]) -> str | None:
784
+ EXTRACTION_PROMPT = """Please carefully examine this invoice image and extract all the information into the following structured JSON format. Pay close attention to details and ensure accuracy in number formatting and text extraction.
785
+ Extract the data into this exact JSON structure:
 
 
 
 
 
786
  {
787
  "header": {
788
+ "invoice_no": "Invoice number or reference ID",
789
+ "po_no": "PO number",
790
+ "invoice_date": "Date the invoice was issued (maintain original format)",
791
+ "payment_terms": "payment terms for the specific invoice",
792
+ "due_date": "Payment due date if specified",
793
+ "sender_name": "Name of the company/person issuing the invoice",
794
+ "sender_addr": "Complete address of the sender/issuer",
795
+ "tax_id": "tax id/VAT no of the sender company",
796
+ "rcpt_name": "Name of the recipient/customer",
797
+ "rcpt_addr": "Address of the recipient/customer",
798
+ "bank_iban": "International Bank Account Number",
799
+ "bank_name": "Name of the bank",
800
+ "bank_acc_no": "Bank account number",
801
+ "bank_routing": "Bank routing number",
802
+ "bank_swift": "SWIFT/BIC code",
803
+ "bank_acc_name": "Account holder name",
804
+ "bank_branch": "Bank branch information"
805
  },
806
  "items": [
807
  {
808
+ "Service_name": "service name if specified",
809
+ "service_start_date": "service start date if specified",
810
+ "service_end_date": "service end date if specified",
811
+ "descriptions": "Detailed description of the item/service",
812
+ "SKU": "Stock Keeping Unit or item code",
813
+ "quantity": "Quantity of items",
814
+ "unit_price": "Price per unit",
815
+ "amount": "Total amount for this line item",
816
+ "discount_rate_per_item": "discount percentage if specified",
817
+ "discount_amount_per_item": "discount amount if specified",
818
+ "tax_rate_per_item": "tax percentage of this line item if specified",
819
+ "tax_amount_per_item": "tax amount of this line item if specified",
820
+ "line_total": "Total amount including tax for this line"
821
  }
822
  ],
823
  "summary": {
824
+ "subtotal": "Subtotal amount before tax",
825
+ "tax_rate": "Tax rate percentage or description",
826
+ "tax_amount": "Total tax amount",
827
+ "discount_rate": "overall discount percentage if specified",
828
+ "total_discount_amount": "total discount amount if specified",
829
+ "total_amount": "Final total amount to be paid",
830
+ "currency": "Currency code (USD, EUR, etc.)"
831
  }
832
  }
833
+ IMPORTANT GUIDELINES:
834
+ The input may include multiple images representing different pages of the same invoice. Extract relevant details from each page and produce a single combined output.
835
+ Extract only the bank account details matching the invoice currency.
836
+ Example:
837
+ Invoice currency = USD → extract the USD bank account.
838
+ Invoice currency = GBP → extract the GBP bank account.
839
+ Sometimes the sender's address appears at the bottom of the invoice, labeled with keywords such as "Registered Office," "Registered In," or "Head Office." In other cases, the address may appear without any label. Identify and provide the sender's address in all such cases.
840
+ Preserve original number formatting (including commas, decimals), Do not include currency symbol for amount field.
841
+ If multiple line items exist, include all of them in the items array
842
+ Use empty string "" for any field that is not present or cannot be clearly identified
843
+ Maintain accuracy in financial figures - double-check all numbers
844
+ Extract text exactly as it appears, including special characters and formatting
845
+ For dates, preserve the original format shown in the invoice
846
+ If both sender and receiver addresses are in the United States, extract ACH; otherwise extract Wire transfer (WT).
847
+ If payment terms are provided (e.g., 30 days), extract only the number of days and set "payment_terms" to that number (e.g., "payment_terms": "30"); if the invoice contains terms like "due on receipt" or "immediate", set "payment_terms": "0"; if both payment terms and a due date are provided, populate both fields accordingly.
848
+ If currency symbols are present, note them appropriately
849
+ for amount fields, give only NUMERIC VALUE, do not include symbol($) or letter("EUR", "USD") to the amount fields.
850
+ If there are multiple discount fields, sum them and assign the result to "total_discount_amount".
851
+ if agency commission is present in the invoice, treat it as a discount as well.
852
+ If "subtotal" is not explicitly provided, calculate "subtotal" as the sum of the "amount" field for all line items present.
853
+ Return only the JSON object with the extracted information
854
+ Agency discount/commision/sales tax mentioned as a separate line item should have the amount filled only in their respective fields :- ex: if agency discount is mentioned, only discount amount per item column will be filled along with line total, if its amount, if its agency discount line item and they have mentioned percentage, then we add it in discount rate per item only
855
+ No calculations/computations must be done, only give whats present in the invoice, no assumptions/calculations.
856
+ Any unit of measurement of quantity and unit price, like impressions should be taken as quantity, CPM is unit price, etc if present in description, has to be taken in the line item field quantity and unit price."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857
 
858
  if not images:
859
  st.error("No images provided to run_inference_vllm.")
 
2446
  with frame_right:
2447
  st.subheader(f"Editable Invoice: {current['file_name']}")
2448
 
2449
+ # Live widgets: keep the data editor outside a form so dynamic row adds/deletes are saved before downloads.
2450
+ tabs = st.tabs(["Invoice Details", "Sender/Recipient", "Bank Details", "Line Items"])
2451
+
2452
+ with tabs[0]:
2453
+ st.text_input("Invoice Number", key=f"Invoice Number_{selected_hash}")
2454
+ st.text_input("PO Number", key=f"PO Number_{selected_hash}")
2455
+
2456
+ st.write("**Invoice Date:**")
2457
+ raw_invoice_date = form_data.get("Invoice Date", "")
2458
+ if raw_invoice_date:
2459
+ st.info(f"📅 Model extracted: {raw_invoice_date}")
2460
+ st.date_input("Select date:", key=f"Invoice Date_{selected_hash}",
2461
+ format="DD/MM/YYYY", label_visibility="collapsed")
2462
+
2463
+ st.text_input("Payment Terms", key=f"Payment Terms_{selected_hash}")
2464
+
2465
+ st.write("**Due Date:**")
2466
+ raw_due_date = form_data.get("Due Date", "")
2467
+ if raw_due_date:
2468
+ st.info(f"📅 Model extracted: {raw_due_date}")
2469
+ st.date_input("Select date:", key=f"Due Date_{selected_hash}",
2470
+ format="DD/MM/YYYY", label_visibility="collapsed")
2471
+
2472
+ st.text_input("Tax ID / VAT Number", key=f"Tax ID_{selected_hash}")
2473
+
2474
+ curr_options = ["USD", "EUR", "GBP", "INR", "Other"]
2475
+ if st.session_state[f"Currency_{selected_hash}"] not in curr_options:
2476
+ st.session_state[f"Currency_{selected_hash}"] = "Other"
2477
+ st.selectbox("Currency", options=curr_options, key=f"Currency_{selected_hash}")
2478
+ if st.session_state.get(f"Currency_{selected_hash}") == "Other":
2479
+ st.text_input("Specify Currency", key=f"Currency_Custom_{selected_hash}")
2480
+
2481
+ st.number_input("Subtotal", key=f"Subtotal_{selected_hash}", format="%.3f", step=0.001)
2482
+ st.number_input("Tax %", key=f"Tax Percentage_{selected_hash}", format="%.3f", step=0.001)
2483
+ st.number_input("Total Tax", key=f"Total Tax_{selected_hash}", format="%.3f", step=0.001)
2484
+ st.number_input("Discount Rate %", key=f"Discount Rate_{selected_hash}", format="%.3f", step=0.001)
2485
+ st.number_input("Total Discount Amount", key=f"Total Discount Amount_{selected_hash}", format="%.3f", step=0.001)
2486
+ st.number_input("Total Amount", key=f"Total Amount_{selected_hash}", format="%.3f", step=0.001)
2487
+
2488
+ with tabs[1]:
2489
+ st.text_input("Sender Name", key=f"Sender Name_{selected_hash}")
2490
+ st.text_area ("Sender Address", key=f"Sender Address_{selected_hash}", height=80)
2491
+ st.text_input("Recipient Name", key=f"Recipient Name_{selected_hash}")
2492
+ st.text_area ("Recipient Address", key=f"Recipient Address_{selected_hash}", height=80)
2493
+
2494
+ with tabs[2]:
2495
+ st.text_input("Bank Name", key=f"Bank_bank_name_{selected_hash}")
2496
+ st.text_input("Account Number", key=f"Bank_bank_account_number_{selected_hash}")
2497
+ st.text_input("Account Name", key=f"Bank_bank_acc_name_{selected_hash}")
2498
+ st.text_input("IBAN", key=f"Bank_bank_iban_{selected_hash}")
2499
+ st.text_input("SWIFT", key=f"Bank_bank_swift_{selected_hash}")
2500
+ st.text_input("Routing", key=f"Bank_bank_routing_{selected_hash}")
2501
+ st.text_input("Branch", key=f"Bank_bank_branch_{selected_hash}")
2502
+
2503
+ with tabs[3]:
2504
+ items_state_key = f"items_df_{selected_hash}"
2505
+
2506
+ if items_state_key not in st.session_state:
2507
+ item_rows = form_data.get("Itemized Data", []) or []
2508
+ normalized = []
2509
+ for it in item_rows:
2510
+ if not isinstance(it, dict):
2511
+ it = {}
2512
+ normalized.append({
2513
+ "Description": it.get("Description", it.get("Item Description", "")),
2514
+ "Service Name": it.get("Service Name", ""),
2515
+ "Service Start Date": it.get("Service Start Date", ""),
2516
+ "Service End Date": it.get("Service End Date", ""),
2517
+ "SKU": it.get("SKU", ""),
2518
+ "Quantity": editable_numeric_value("Quantity", it.get("Quantity", it.get("Item Quantity", 0.0))),
2519
+ "Unit Price": editable_numeric_value("Unit Price", it.get("Unit Price", it.get("Item Unit Price", 0.0))),
2520
+ "Amount": editable_numeric_value("Amount", it.get("Amount", it.get("Item Amount", 0.0))),
2521
+ "Discount Rate Per Item": editable_numeric_value("Discount Rate Per Item", it.get("Discount Rate Per Item", 0.0)),
2522
+ "Discount Amount Per Item": editable_numeric_value("Discount Amount Per Item", it.get("Discount Amount Per Item", 0.0)),
2523
+ "Tax Rate Per Item": editable_numeric_value("Tax Rate Per Item", it.get("Tax Rate Per Item", 0.0)),
2524
+ "Tax Amount Per Item": editable_numeric_value("Tax Amount Per Item", it.get("Tax Amount Per Item", 0.0)),
2525
+ "IO Number/Cost Centre": it.get("IO Number/Cost Centre", ""),
2526
+ "Line Total": editable_numeric_value("Line Total", it.get("Line Total", it.get("Item Line Total", 0.0))),
2527
+ })
2528
+ st.session_state[items_state_key] = coerce_numeric_items_df(
2529
+ pd.DataFrame(normalized) if normalized
2530
+ else pd.DataFrame(columns=[
2531
+ "Description", "Service Name", "Service Start Date", "Service End Date", "SKU",
2532
+ "Quantity", "Unit Price", "Amount",
2533
+ "Discount Rate Per Item", "Discount Amount Per Item",
2534
+ "Tax Rate Per Item", "Tax Amount Per Item",
2535
+ "IO Number/Cost Centre", "Line Total"
2536
+ ])
2537
+ )
2538
 
2539
+ items_df = coerce_numeric_items_df(st.session_state[items_state_key])
2540
+ st.session_state[items_state_key] = items_df
2541
+
2542
+ column_config = {
2543
+ "Description": st.column_config.TextColumn("Description", width="large"),
2544
+ "Service Name": st.column_config.TextColumn("Service Name", width="medium"),
2545
+ "Service Start Date": st.column_config.TextColumn("Svc Start", width="small"),
2546
+ "Service End Date": st.column_config.TextColumn("Svc End", width="small"),
2547
+ "SKU": st.column_config.TextColumn("SKU", width="small"),
2548
+ "Quantity": st.column_config.NumberColumn("Qty", width="small", format="%.3f", step=0.001),
2549
+ "Unit Price": st.column_config.NumberColumn("Unit Price", width="small", format="%.3f", step=0.001),
2550
+ "Amount": st.column_config.NumberColumn("Amount", width="small", format="%.3f", step=0.001),
2551
+ "Discount Rate Per Item": st.column_config.NumberColumn("Disc %", width="small", format="%.3f", step=0.001),
2552
+ "Discount Amount Per Item": st.column_config.NumberColumn("Disc Amt", width="small", format="%.3f", step=0.001),
2553
+ "Tax Rate Per Item": st.column_config.NumberColumn("Tax %", width="small", format="%.3f", step=0.001),
2554
+ "Tax Amount Per Item": st.column_config.NumberColumn("Tax Amt", width="small", format="%.3f", step=0.001),
2555
+ "IO Number/Cost Centre": st.column_config.TextColumn("IO/Cost Centre", width="medium"),
2556
+ "Line Total": st.column_config.NumberColumn("Line Total", width="small", format="%.3f", step=0.001),
2557
+ }
2558
 
2559
+ edited_df = st.data_editor(
2560
+ items_df,
2561
+ num_rows="dynamic",
2562
+ key=f"items_editor_{selected_hash}",
2563
+ use_container_width=True,
2564
+ height=DATA_EDITOR_HEIGHT,
2565
+ column_config=column_config,
2566
+ )
2567
+ st.session_state[items_state_key] = coerce_numeric_items_df(edited_df)
2568
 
2569
+ saved = st.button("💾 Save All Edits", key=f"save_all_edits_{selected_hash}")
2570
 
2571
  currency = st.session_state.get(f"Currency_{selected_hash}", "USD")
2572
  if currency == "Other":