jayanth-2005 commited on
Commit
a7465cd
Β·
verified Β·
1 Parent(s): 0ac74a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -22
app.py CHANGED
@@ -7,13 +7,13 @@ import cv2
7
  import numpy as np
8
  import re
9
  import os
10
- from groq import Groq
11
  import json
 
12
 
13
- st.set_page_config(page_title="Invoice Intelligence Engine", layout="wide")
14
 
15
- st.title("πŸš€ Invoice Intelligence Engine")
16
- st.write("Upload ANY invoice / receipt document")
17
 
18
  uploaded_file = st.file_uploader(
19
  "Upload File",
@@ -44,11 +44,12 @@ def extract_text(uploaded_file):
44
 
45
 
46
  # ---------------------------------------------------------
47
- # STRUCTURED GST PARSER (FAST + ACCURATE)
48
  # ---------------------------------------------------------
49
 
50
  def extract_structured_gst(text):
51
 
 
52
  text = text.replace("INVO1CE", "INVOICE")
53
  text = text.replace("GSTlN", "GSTIN")
54
  text = text.replace("T0tal", "Total")
@@ -86,7 +87,7 @@ def extract_structured_gst(text):
86
 
87
 
88
  # ---------------------------------------------------------
89
- # AI FALLBACK (FOR UNKNOWN FORMATS)
90
  # ---------------------------------------------------------
91
 
92
  def ai_extract_invoice(text):
@@ -94,13 +95,36 @@ def ai_extract_invoice(text):
94
  client = Groq(api_key=os.getenv("GROQ_API_KEY"))
95
 
96
  prompt = f"""
97
- Extract purchase/invoice information from this document.
98
-
99
- Return JSON array with:
100
- invoice_or_order_number, invoice_date,
101
- vendor_name, total_amount.
102
-
103
- If no purchase found, return [].
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  Document:
106
  {text}
@@ -117,38 +141,56 @@ def ai_extract_invoice(text):
117
  result = result.replace("```json", "").replace("```", "")
118
  return json.loads(result)
119
 
120
- except:
 
121
  return []
122
 
123
 
124
  # ---------------------------------------------------------
125
- # MAIN EXECUTION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  # ---------------------------------------------------------
127
 
128
  if uploaded_file:
129
 
130
  raw_text = extract_text(uploaded_file)
131
 
132
- st.subheader("Raw Text Preview")
133
- st.text_area("Preview", raw_text[:2000], height=200)
134
 
135
- # Try structured GST extraction first
136
  invoices = extract_structured_gst(raw_text)
137
 
138
- # If none found β†’ use AI
139
  if not invoices:
140
  invoices = ai_extract_invoice(raw_text)
141
 
142
  if invoices:
143
  df = pd.DataFrame(invoices)
144
- st.success(f"βœ… {len(df)} invoice(s) detected")
 
 
145
  st.dataframe(df, use_container_width=True)
146
 
147
  st.download_button(
148
- "Download CSV",
149
  df.to_csv(index=False),
150
  "invoice_output.csv",
151
  "text/csv"
152
  )
153
  else:
154
- st.warning("⚠ No invoice detected.")
 
7
  import numpy as np
8
  import re
9
  import os
 
10
  import json
11
+ from groq import Groq
12
 
13
+ st.set_page_config(page_title="AI Invoice Intelligence Engine", layout="wide")
14
 
15
+ st.title("πŸš€ AI Invoice Intelligence Engine")
16
+ st.write("Upload ANY invoice, receipt, subscription, or purchase document")
17
 
18
  uploaded_file = st.file_uploader(
19
  "Upload File",
 
44
 
45
 
46
  # ---------------------------------------------------------
47
+ # STRUCTURED GST PARSER (FAST)
48
  # ---------------------------------------------------------
49
 
50
  def extract_structured_gst(text):
51
 
52
+ # Fix OCR noise
53
  text = text.replace("INVO1CE", "INVOICE")
54
  text = text.replace("GSTlN", "GSTIN")
55
  text = text.replace("T0tal", "Total")
 
87
 
88
 
89
  # ---------------------------------------------------------
90
+ # AI FALLBACK (UNIVERSAL)
91
  # ---------------------------------------------------------
92
 
93
  def ai_extract_invoice(text):
 
95
  client = Groq(api_key=os.getenv("GROQ_API_KEY"))
96
 
97
  prompt = f"""
98
+ You are a financial document extraction engine.
99
+
100
+ If this document contains:
101
+ - payment confirmation
102
+ - subscription charge
103
+ - invoice
104
+ - receipt
105
+ - order confirmation
106
+ - total amount charged
107
+
108
+ Extract structured JSON array.
109
+
110
+ Format:
111
+
112
+ [
113
+ {{
114
+ "document_type": "",
115
+ "invoice_or_order_number": "",
116
+ "invoice_date": "",
117
+ "vendor_name": "",
118
+ "vendor_gstin": null,
119
+ "taxable_amount": null,
120
+ "cgst": null,
121
+ "sgst": null,
122
+ "igst": null,
123
+ "total_amount": null
124
+ }}
125
+ ]
126
+
127
+ If not purchase-related, return [].
128
 
129
  Document:
130
  {text}
 
141
  result = result.replace("```json", "").replace("```", "")
142
  return json.loads(result)
143
 
144
+ except Exception as e:
145
+ print("AI error:", e)
146
  return []
147
 
148
 
149
  # ---------------------------------------------------------
150
+ # CONFIDENCE SCORE
151
+ # ---------------------------------------------------------
152
+
153
+ def calculate_confidence(row):
154
+
155
+ total_fields = len(row.keys())
156
+ filled_fields = sum(
157
+ 1 for v in row.values()
158
+ if v not in [None, "", "null"]
159
+ )
160
+
161
+ return round((filled_fields / total_fields) * 100, 2)
162
+
163
+
164
+ # ---------------------------------------------------------
165
+ # MAIN
166
  # ---------------------------------------------------------
167
 
168
  if uploaded_file:
169
 
170
  raw_text = extract_text(uploaded_file)
171
 
172
+ st.subheader("πŸ“„ Raw Text Preview")
173
+ st.text_area("Preview", raw_text[:3000], height=200)
174
 
175
+ # Step 1: Try structured GST parsing
176
  invoices = extract_structured_gst(raw_text)
177
 
178
+ # Step 2: If none found, use AI fallback
179
  if not invoices:
180
  invoices = ai_extract_invoice(raw_text)
181
 
182
  if invoices:
183
  df = pd.DataFrame(invoices)
184
+ df["confidence_%"] = df.apply(calculate_confidence, axis=1)
185
+
186
+ st.success(f"βœ… {len(df)} document(s) detected")
187
  st.dataframe(df, use_container_width=True)
188
 
189
  st.download_button(
190
+ "⬇ Download CSV",
191
  df.to_csv(index=False),
192
  "invoice_output.csv",
193
  "text/csv"
194
  )
195
  else:
196
+ st.warning("⚠ No financial transaction detected.")