Bhuvi13 commited on
Commit
24dda8b
Β·
verified Β·
1 Parent(s): 1672fbd

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +143 -63
src/streamlit_app.py CHANGED
@@ -789,79 +789,159 @@ def _encode_page(page: Image.Image, page_idx: int, max_dim: int = MAX_DIMENSION_
789
 
790
 
791
  def run_inference_vllm(images: List[Image.Image]) -> str | None:
792
- 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.
793
- Extract the data into this exact JSON structure:
 
 
 
 
 
794
  {
795
  "header": {
796
- "invoice_no": "Invoice number or reference ID",
797
- "po_no": "PO number",
798
- "invoice_date": "Date the invoice was issued (maintain original format)",
799
- "payment_terms": "payment terms for the specific invoice",
800
- "due_date": "Payment due date if specified",
801
- "sender_name": "Name of the company/person issuing the invoice",
802
- "sender_addr": "Complete address of the sender/issuer",
803
- "tax_id": "tax id/VAT no of the sender company",
804
- "rcpt_name": "Name of the recipient/customer",
805
- "rcpt_addr": "Address of the recipient/customer",
806
- "bank_iban": "International Bank Account Number",
807
- "bank_name": "Name of the bank",
808
- "bank_acc_no": "Bank account number",
809
- "bank_routing": "Bank routing number",
810
- "bank_swift": "SWIFT/BIC code",
811
- "bank_acc_name": "Account holder name",
812
- "bank_branch": "Bank branch information"
813
  },
814
  "items": [
815
  {
816
- "Service_name": "service name if specified",
817
- "service_start_date": "service start date if specified",
818
- "service_end_date": "service end date if specified",
819
- "descriptions": "Detailed description of the item/service",
820
- "SKU": "Stock Keeping Unit or item code",
821
- "quantity": "Quantity of items",
822
- "unit_price": "Price per unit",
823
- "amount": "Total amount for this line item",
824
- "discount_rate_per_item": "discount percentage if specified",
825
- "discount_amount_per_item": "discount amount if specified",
826
- "tax_rate_per_item": "tax percentage of this line item if specified",
827
- "tax_amount_per_item": "tax amount of this line item if specified",
828
- "line_total": "Total amount including tax for this line"
829
  }
830
  ],
831
  "summary": {
832
- "subtotal": "Subtotal amount before tax",
833
- "tax_rate": "Tax rate percentage or description",
834
- "tax_amount": "Total tax amount",
835
- "discount_rate": "overall discount percentage if specified",
836
- "total_discount_amount": "total discount amount if specified",
837
- "total_amount": "Final total amount to be paid",
838
- "currency": "Currency code (USD, EUR, etc.)"
839
  }
840
  }
841
- IMPORTANT GUIDELINES:
842
- 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.
843
- Extract only the bank account details matching the invoice currency.
844
- Example:
845
- Invoice currency = USD β†’ extract the USD bank account.
846
- Invoice currency = GBP β†’ extract the GBP bank account.
847
- 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.
848
- Preserve original number formatting (including commas, decimals), Do not include currency symbol for amount field.
849
- If multiple line items exist, include all of them in the items array
850
- Use empty string "" for any field that is not present or cannot be clearly identified
851
- Maintain accuracy in financial figures - double-check all numbers
852
- Extract text exactly as it appears, including special characters and formatting
853
- For dates, preserve the original format shown in the invoice
854
- If both sender and receiver addresses are in the United States, extract ACH; otherwise extract Wire transfer (WT).
855
- 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.
856
- If currency symbols are present, note them appropriately
857
- for amount fields, give only NUMERIC VALUE, do not include symbol($) or letter("EUR", "USD") to the amount fields.
858
- If there are multiple discount fields, sum them and assign the result to "total_discount_amount".
859
- if agency commission is present in the invoice, treat it as a discount as well.
860
- If "subtotal" is not explicitly provided, calculate "subtotal" as the sum of the "amount" field for all line items present.
861
- Return only the JSON object with the extracted information
862
- 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
863
- No calculations/computations must be done, only give whats present in the invoice, no assumptions/calculations.
864
- 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."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865
 
866
  if not images:
867
  st.error("No images provided to run_inference_vllm.")
 
789
 
790
 
791
  def run_inference_vllm(images: List[Image.Image]) -> str | None:
792
+ EXTRACTION_PROMPT = """Extract structured data from the provided invoice image(s). Return a single JSON object with three sections: header, items, summary.
793
+
794
+ ## Output Schema
795
+
796
+ Return this exact structure. Use empty string "" for any field not found.
797
+
798
+ json
799
  {
800
  "header": {
801
+ "invoice_no": "",
802
+ "po_no": "",
803
+ "invoice_date": "",
804
+ "payment_terms": "",
805
+ "due_date": "",
806
+ "sender_name": "",
807
+ "sender_addr": "",
808
+ "tax_id": "",
809
+ "rcpt_name": "",
810
+ "rcpt_addr": "",
811
+ "bank_iban": "",
812
+ "bank_name": "",
813
+ "bank_acc_no": "",
814
+ "bank_routing": "",
815
+ "bank_swift": "",
816
+ "bank_acc_name": "",
817
+ "bank_branch": ""
818
  },
819
  "items": [
820
  {
821
+ "service_name": "",
822
+ "service_start_date": "",
823
+ "service_end_date": "",
824
+ "descriptions": "",
825
+ "SKU": "",
826
+ "quantity": "",
827
+ "unit_price": "",
828
+ "amount": "",
829
+ "discount_rate_per_item": "",
830
+ "discount_amount_per_item": "",
831
+ "tax_rate_per_item": "",
832
+ "tax_amount_per_item": "",
833
+ "line_total": ""
834
  }
835
  ],
836
  "summary": {
837
+ "subtotal": "",
838
+ "tax_rate": "",
839
+ "tax_amount": "",
840
+ "discount_rate": "",
841
+ "total_discount_amount": "",
842
+ "total_amount": "",
843
+ "currency": ""
844
  }
845
  }
846
+
847
+
848
+
849
+ ## Core Rules
850
+
851
+ 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:
852
+ - Bracketed amounts β†’ negative: (100.00) β†’ "-100.00".
853
+ - Date ranges β†’ expanded to full start/end dates using the invoice year.
854
+ - Language normalization of payment terms β†’ English.
855
+ - Summing multiple tax AMOUNTS shown separately into one combined amount.
856
+ - Summing multiple discount AMOUNTS shown separately into one combined amount.
857
+ - Default quantity to "1.00" when unit_price and amount are both shown and equal, with no quantity printed.
858
+ - 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.
859
+
860
+ 2. Return "" for any field not present or not clearly identifiable.
861
+
862
+ 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.
863
+
864
+ 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 "".
865
+
866
+ 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").
867
+
868
+ 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.
869
+
870
+ 7. OUTPUT ONLY THE JSON. No preamble, no markdown fences, no explanation.
871
+
872
+ 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).
873
+
874
+ 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": [].
875
+
876
+ 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").
877
+
878
+ ## Field Rules
879
+
880
+ ### Sender & Recipient
881
+
882
+ 1.sender_name: The invoicing company/person. Prefer company name over person name.
883
+ 2.sender_addr: The full address of the invoicing entity, wherever it appears on the invoice.
884
+ 3.tax_id: Always the SENDER's tax ID / VAT number. Never the recipient's.
885
+ 4.rcpt_name: The name of the recipient, customer, or entity being billed.
886
+ 5.rcpt_addr: The address of the recipient, customer, or entity being billed.
887
+
888
+ ### PO Number
889
+
890
+ 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 "".
891
+
892
+ ### Bank Details
893
+
894
+ 1.Prefer the bank account matching the invoice currency (USD invoice β†’ USD account).
895
+ 2.If no currency-matching account exists, extract the only available account.
896
+ 3.If multiple non-matching accounts exist with no currency-matching account, return "" for all bank fields.
897
+ 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.
898
+
899
+ ### Dates
900
+
901
+ 5.Preserve the original date format exactly as printed.
902
+ 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.
903
+ 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.
904
+ 8.payment_terms: Normalize to English ("30 jours" β†’ "30 days", "60 gg df" β†’ "60 days").
905
+
906
+ ### Descriptions
907
+
908
+ 1.service_name: A short label, product name, or service title (e.g., "Consulting", "Web Hosting", "Premium Plan").
909
+ 2.descriptions: The full detailed description text of the line item.
910
+ 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.
911
+ 4.If only one text is available for the line item β†’ place it in descriptions and leave service_name as "".
912
+ 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.
913
+ 6.Do not extract handwritten annotations or stamps unless they are clearly legible and printed-quality. When in doubt, extract only the printed text.
914
+
915
+ ### Amounts, Tax & Discounts
916
+
917
+ 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).
918
+ 2.Bracketed amounts are negative: (100.00) β†’ "-100.00".
919
+ 3."No VAT" / "VAT Exempt" β†’ set relevant tax field to "0.00".
920
+ 4.Tax rate shown but tax amount blank AND subtotal equals total as printed β†’ tax amount = "0.00".
921
+ 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.
922
+ 6.Summing multiple values:
923
+ - Multiple tax AMOUNTS shown separately β†’ sum into one combined amount in the appropriate field.
924
+ - Multiple DISCOUNT AMOUNTS shown separately β†’ sum into one combined amount in the appropriate field.
925
+ - 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%".
926
+ 7.0Gross vs. Net amount columns: If both gross and net per-line amounts are shown, use the NET (pre-tax) amount as amount.
927
+ 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 "".
928
+ 9.Discount/tax in the totals/summary area: Place only in the summary object of the schema. Do not duplicate into the items array.
929
+
930
+ ### Quantity & Unit Price
931
+
932
+ 1.If unit_price and amount are shown and equal but no quantity is printed β†’ quantity: "1.00".
933
+ 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.
934
+ 3.If both a standard quantity and an alternate metric are shown, extract the standard quantity.
935
+ 4.Negative quantities (e.g., on credit notes) are preserved as-is with the negative sign.
936
+
937
+ ### Line Total
938
+
939
+ line_total: Extract ONLY if ALL these conditions are met:
940
+ 1. The invoice explicitly prints a dedicated line total column or value for the row.
941
+ 2. The invoice has NO separate per-line tax column or per-line tax amount anywhere.
942
+ 3. The invoice has NO separate per-line discount column or per-line discount amount anywhere.
943
+ If any per-line tax or discount column exists anywhere on the invoice β†’ set line_total to "" for ALL rows.
944
+ If no line total column exists on the invoice β†’ line_total = ""."""
945
 
946
  if not images:
947
  st.error("No images provided to run_inference_vllm.")