Seth0330 commited on
Commit
918613a
·
verified ·
1 Parent(s): cae838a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -269
app.py CHANGED
@@ -1,303 +1,126 @@
1
  import streamlit as st
2
- import io
3
  import requests
4
  import json
5
- import re
6
  import os
 
7
 
8
- from main import read_pdf, extract_key_phrases, score_sentences, summarize_text
9
-
10
- st.set_page_config(page_title="PDF Tools", layout="wide")
11
 
12
- MODELS = {
13
- "DeepSeek v3": {
14
- "api_url": "https://api.deepseek.com/v1/chat/completions",
15
- "model": "deepseek-chat",
16
- "key_env": "DEEPSEEK_API_KEY",
17
- "response_format": {"type": "json_object"},
18
- },
19
- "DeepSeek R1": {
20
- "api_url": "https://api.deepseek.com/v1/chat/completions",
21
- "model": "deepseek-reasoner",
22
- "key_env": "DEEPSEEK_API_KEY",
23
- "response_format": None,
24
- },
25
- "OpenAI GPT-4.1": {
26
- "api_url": "https://api.openai.com/v1/chat/completions",
27
- "model": "gpt-4-1106-preview",
28
- "key_env": "OPENAI_API_KEY",
29
- "response_format": None,
30
- "extra_headers": {},
31
- },
32
- "Mistral Small": {
33
- "api_url": "https://openrouter.ai/api/v1/chat/completions",
34
- "model": "mistralai/mistral-small-3.1-24b-instruct:free",
35
- "key_env": "OPENROUTER_API_KEY",
36
- "response_format": {"type": "json_object"},
37
- "extra_headers": {
38
- "HTTP-Referer": "https://huggingface.co",
39
- "X-Title": "Invoice Extractor",
40
- },
41
- },
42
- }
43
-
44
- def get_api_key(model_choice):
45
- key = os.getenv(MODELS[model_choice]["key_env"])
46
  if not key:
47
- st.error(f"❌ {MODELS[model_choice]['key_env']} not set")
48
  st.stop()
49
  return key
50
 
51
- def query_llm(model_choice, prompt):
52
- cfg = MODELS[model_choice]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  headers = {
54
- "Authorization": f"Bearer {get_api_key(model_choice)}",
55
- "Content-Type": "application/json",
56
  }
57
- if cfg.get("extra_headers"):
58
- headers.update(cfg["extra_headers"])
59
  payload = {
60
- "model": cfg["model"],
61
- "messages": [{"role": "user", "content": prompt}],
62
- "temperature": 0.1,
63
- "max_tokens": 2000,
64
  }
65
- if cfg.get("response_format"):
66
- payload["response_format"] = cfg["response_format"]
67
- try:
68
- with st.spinner(f"🔍 Querying {model_choice}..."):
69
- r = requests.post(cfg["api_url"], headers=headers, json=payload, timeout=90)
70
- if r.status_code != 200:
71
- if "No instances available" in r.text or r.status_code == 503:
72
- st.error(f"{model_choice} is currently unavailable. Please try again later or select another model.")
73
- else:
74
- st.error(f"🚨 API Error {r.status_code}: {r.text}")
75
- return None
76
- content = r.json()["choices"][0]["message"]["content"]
77
- st.session_state.last_api = content
78
- st.session_state.last_raw = r.text
79
- return content
80
- except Exception as e:
81
- st.error(f"Connection error: {e}")
82
  return None
 
83
 
84
  def clean_json_response(text):
85
  if not text:
86
  return None
87
- orig = text
88
- # strip ``` fences
89
- text = re.sub(r'```(?:json)?', '', text).strip()
90
- # find outer braces
 
 
 
 
 
 
91
  start, end = text.find('{'), text.rfind('}') + 1
92
  if start < 0 or end < 1:
93
- st.error("Couldn't locate JSON in response.")
94
- st.code(orig)
95
  return None
96
  frag = text[start:end]
97
- # remove stray trailing commas
98
- frag = re.sub(r',\s*([}\]])', r'\1', frag)
99
  try:
100
  return json.loads(frag)
101
- except json.JSONDecodeError as e:
102
- # attempt to insert missing commas between adjacent fields
103
- repaired = re.sub(r'"\s*"\s*(?="[^"]+"\s*:)', '","', frag)
104
- try:
105
- return json.loads(repaired)
106
- except json.JSONDecodeError:
107
- st.error(f"JSON parse error: {e}")
108
- st.code(frag)
109
- return None
110
-
111
- def fallback_supplier(text):
112
- for line in text.splitlines():
113
- line = line.strip()
114
- if line:
115
- return line
116
- return None
117
-
118
- def get_extraction_prompt(model_choice, txt):
119
- return (
120
- "You are an expert invoice parser. "
121
- "Extract data according to the visible table structure and column headers in the invoice. "
122
- "For every line item, only extract fields that correspond to the table columns for that row (do not include header/shipment fields in line items). "
123
- "Merge all multi-line content within a single cell into that field (especially for the 'description' and 'notes'). "
124
- "Shipment/invoice-level fields such as CAR NUMBER, SHIPPING POINT, SHIPMENT NUMBER, CURRENCY, etc., must go ONLY into the 'invoice_header', not as line item fields.\n"
125
- "Use this schema:\n"
126
- '{\n'
127
- ' "invoice_header": {\n'
128
- ' "car_number": "string or null",\n'
129
- ' "shipment_number": "string or null",\n'
130
- ' "shipping_point": "string or null",\n'
131
- ' "currency": "string or null",\n'
132
- ' "invoice_number": "string or null",\n'
133
- ' "invoice_date": "string or null",\n'
134
- ' "order_number": "string or null",\n'
135
- ' "customer_order_number": "string or null",\n'
136
- ' "our_order_number": "string or null",\n'
137
- ' "sales_order_number": "string or null",\n'
138
- ' "purchase_order_number": "string or null",\n'
139
- ' "order_date": "string or null",\n'
140
- ' "supplier_name": "string or null",\n'
141
- ' "supplier_address": "string or null",\n'
142
- ' "supplier_phone": "string or null",\n'
143
- ' "supplier_email": "string or null",\n'
144
- ' "supplier_tax_id": "string or null",\n'
145
- ' "customer_name": "string or null",\n'
146
- ' "customer_address": "string or null",\n'
147
- ' "customer_phone": "string or null",\n'
148
- ' "customer_email": "string or null",\n'
149
- ' "customer_tax_id": "string or null",\n'
150
- ' "ship_to_name": "string or null",\n'
151
- ' "ship_to_address": "string or null",\n'
152
- ' "bill_to_name": "string or null",\n'
153
- ' "bill_to_address": "string or null",\n'
154
- ' "remit_to_name": "string or null",\n'
155
- ' "remit_to_address": "string or null",\n'
156
- ' "tax_id": "string or null",\n'
157
- ' "tax_registration_number": "string or null",\n'
158
- ' "vat_number": "string or null",\n'
159
- ' "payment_terms": "string or null",\n'
160
- ' "payment_method": "string or null",\n'
161
- ' "payment_reference": "string or null",\n'
162
- ' "bank_account_number": "string or null",\n'
163
- ' "iban": "string or null",\n'
164
- ' "swift_code": "string or null",\n'
165
- ' "total_before_tax": "string or null",\n'
166
- ' "tax_amount": "string or null",\n'
167
- ' "tax_rate": "string or null",\n'
168
- ' "shipping_charges": "string or null",\n'
169
- ' "discount": "string or null",\n'
170
- ' "total_due": "string or null",\n'
171
- ' "amount_paid": "string or null",\n'
172
- ' "balance_due": "string or null",\n'
173
- ' "due_date": "string or null",\n'
174
- ' "invoice_status": "string or null",\n'
175
- ' "reference_number": "string or null",\n'
176
- ' "project_code": "string or null",\n'
177
- ' "department": "string or null",\n'
178
- ' "contact_person": "string or null",\n'
179
- ' "notes": "string or null",\n'
180
- ' "additional_info": "string or null"\n'
181
- ' },\n'
182
- ' "line_items": [\n'
183
- ' {\n'
184
- ' "quantity": "string or null",\n'
185
- ' "units": "string or null",\n'
186
- ' "description": "string or null",\n'
187
- ' "footage": "string or null",\n'
188
- ' "price": "string or null",\n'
189
- ' "amount": "string or null",\n'
190
- ' "notes": "string or null"\n'
191
- ' }\n'
192
- ' ]\n'
193
- '}'
194
- "\nIf a field is missing for a line item or header, use null. "
195
- "Do not invent fields. Do not add any header or shipment data to any line item. Return ONLY the JSON object, no explanation.\n"
196
- "\nInvoice Text:\n"
197
- f"{txt}"
198
- )
199
-
200
- def extract_invoice_info(model_choice, text):
201
- prompt = get_extraction_prompt(model_choice, text)
202
- raw = query_llm(model_choice, prompt)
203
- if not raw:
204
- return None
205
- data = clean_json_response(raw)
206
- if not data:
207
  return None
208
 
209
- # DeepSeek models: flat format, but we standardize to always return "invoice_header" and "line_items"
210
- if model_choice.startswith("DeepSeek"):
211
- # Put all keys except "line_items" into invoice_header
212
- header = {k: v for k, v in data.items() if k != "line_items"}
213
- items = data.get("line_items", [])
214
- if not isinstance(items, list):
215
- items = []
216
- for itm in items:
217
- if not isinstance(itm, dict):
218
- continue
219
- for k in ("description","quantity","unit_price","total_price"):
220
- itm.setdefault(k, None)
221
- return {"invoice_header": header, "line_items": items}
222
- # Other models (OpenAI GPT-4.1, Mistral): expect proper structure
223
- hdr = data.get("invoice_header", {})
224
- if not hdr and any(k in data for k in ("invoice_number","supplier_name","customer_name")):
225
- # If model returned flat, treat top-level keys as header
226
- hdr = data
227
- for k in ("invoice_number","invoice_date","po_number","invoice_value","supplier_name","customer_name"):
228
- hdr.setdefault(k, None)
229
- if not hdr.get("supplier_name"):
230
- hdr["supplier_name"] = fallback_supplier(text)
231
- items = data.get("line_items", [])
232
- if not isinstance(items, list):
233
- items = []
234
- for itm in items:
235
- if not isinstance(itm, dict):
236
- continue
237
- for k in ("item_number","description","quantity","unit_price","total_price"):
238
- itm.setdefault(k, None)
239
- return {"invoice_header": hdr, "line_items": items}
240
 
241
- # ---- UI ----
242
- tab1, tab2 = st.tabs(["PDF Summarizer","Invoice Extractor"])
243
 
244
  with tab1:
245
- st.title("PDF Bullet Points")
246
- pdf = st.file_uploader("Upload PDF", type="pdf")
247
- pct = st.slider("Summarization %", 1, 100, 20)
248
- if st.button("Summarize") and pdf:
249
- txt = read_pdf(io.BytesIO(pdf.getvalue()))
250
- keys = extract_key_phrases(txt)
251
- scores = score_sentences(txt, keys)
252
- n = max(1, len(scores)*pct//100)
253
- st.markdown(summarize_text(scores, num_points=n))
254
-
255
- with tab2:
256
- st.title("Invoice Extractor")
257
- mdl = st.selectbox("Model", list(MODELS.keys()), key="extract_model")
258
- inv_pdf = st.file_uploader("Invoice PDF", type="pdf")
259
- extracted_info = None
260
-
261
- if st.button("Extract") and inv_pdf:
262
- txt = read_pdf(io.BytesIO(inv_pdf.getvalue()))
263
- extracted_info = extract_invoice_info(mdl, txt)
264
- if extracted_info:
265
  st.success("Extraction Complete")
266
  st.subheader("Invoice Metadata")
267
- st.table([{k.replace("_", " ").title(): v for k, v in extracted_info["invoice_header"].items()}])
268
  st.subheader("Line Items")
269
- st.table(extracted_info["line_items"])
270
- st.session_state["last_extracted_info"] = extracted_info # store in session
 
271
 
272
- # If we've already extracted info, or in this session, show further controls
273
- extracted_info = extracted_info or st.session_state.get("last_extracted_info", None)
274
- if extracted_info:
275
- st.markdown("---")
276
- st.subheader("📝 Fine-tune Extracted Data with Your Own Prompt")
277
- user_prompt = st.text_area(
278
- "Enter your prompt for further processing or transformation (the extracted JSON will be available as context).",
279
- height=120,
280
- key="custom_prompt"
281
- )
282
- model_2 = st.selectbox("Model for Fine-Tuning Prompt", list(MODELS.keys()), key="refine_model")
283
- if st.button("Run Custom Prompt"):
284
- # Compose the prompt for the LLM, including the JSON and user's instruction
285
- refine_input = (
286
- "Here is an extracted invoice in JSON format:\n"
287
- f"{json.dumps(extracted_info, indent=2)}\n"
288
- "Follow this instruction and return the result as a JSON object only (no explanation):\n"
289
- f"{user_prompt}"
290
- )
291
- result = query_llm(model_2, refine_input)
292
- refined_json = clean_json_response(result)
293
- st.subheader("Fine-Tuned Output")
294
- if refined_json:
295
- st.json(refined_json)
296
- else:
297
- st.error("Could not parse a valid JSON output from the model.")
298
- st.caption("The prompt is run on the above-extracted fields as JSON. Try instructions like: 'Add a new field for net_amount (amount minus tax) to each line item', or 'Summarize the total quantity ordered', etc.")
299
-
300
- if "last_api" in st.session_state:
301
- with st.expander("Debug"):
302
- st.code(st.session_state.last_api)
303
- st.code(st.session_state.last_raw)
 
1
  import streamlit as st
 
2
  import requests
3
  import json
4
+ import io
5
  import os
6
+ import base64
7
 
8
+ st.set_page_config(page_title="PDF Invoice Extractor (GPT-4o Vision)", layout="wide")
 
 
9
 
10
+ def get_api_key():
11
+ key = os.getenv("OPENAI_API_KEY")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  if not key:
13
+ st.error("❌ OPENAI_API_KEY not set in your environment")
14
  st.stop()
15
  return key
16
 
17
+ def query_gpt4o_vision(pdf_file, prompt):
18
+ # Read and encode PDF to base64
19
+ encoded_pdf = base64.b64encode(pdf_file.read()).decode('utf-8')
20
+ # Compose the prompt for GPT-4o Vision
21
+ messages = [
22
+ {
23
+ "role": "user",
24
+ "content": [
25
+ {"type": "text", "text": prompt},
26
+ {
27
+ "type": "file",
28
+ "file": {
29
+ "mime_type": "application/pdf",
30
+ "data": encoded_pdf
31
+ }
32
+ }
33
+ ]
34
+ }
35
+ ]
36
  headers = {
37
+ "Authorization": f"Bearer {get_api_key()}",
38
+ "Content-Type": "application/json"
39
  }
 
 
40
  payload = {
41
+ "model": "gpt-4o",
42
+ "messages": messages,
43
+ "max_tokens": 2000
 
44
  }
45
+ with st.spinner("🔍 Querying GPT-4o Vision..."):
46
+ r = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload, timeout=120)
47
+ if r.status_code != 200:
48
+ st.error(f"🚨 API Error {r.status_code}: {r.text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  return None
50
+ return r.json()["choices"][0]["message"]["content"]
51
 
52
  def clean_json_response(text):
53
  if not text:
54
  return None
55
+ # Strip ``` fences and whitespace
56
+ text = text.strip()
57
+ if text.startswith("```json"):
58
+ text = text[7:]
59
+ if text.startswith("```"):
60
+ text = text[3:]
61
+ if text.endswith("```"):
62
+ text = text[:-3]
63
+ text = text.strip()
64
+ # Find the JSON object
65
  start, end = text.find('{'), text.rfind('}') + 1
66
  if start < 0 or end < 1:
 
 
67
  return None
68
  frag = text[start:end]
69
+ # Remove stray trailing commas
70
+ frag = frag.replace(',\n}', '\n}')
71
  try:
72
  return json.loads(frag)
73
+ except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  return None
75
 
76
+ st.title("PDF Invoice Extraction with GPT-4o Vision")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ tab1, tab2 = st.tabs(["Extract Invoice (Vision)", "Custom Prompt (Vision)"])
 
79
 
80
  with tab1:
81
+ st.header("Extract Invoice Metadata from PDF (GPT-4o Vision)")
82
+ pdf = st.file_uploader("Upload Invoice PDF", type="pdf")
83
+ if st.button("Extract Invoice") and pdf:
84
+ prompt = (
85
+ "You are an expert invoice parser. Extract the invoice header fields and all line items from the PDF invoice. "
86
+ "Return the result as a single JSON object with 'invoice_header' and 'line_items' keys, "
87
+ "matching this schema:\n"
88
+ "{\n"
89
+ ' "invoice_header": {...},\n'
90
+ ' "line_items": [ {...}, {...} ]\n'
91
+ "}\n"
92
+ "If a field is missing, use null. Do not invent fields. Do not add explanations—return JSON only."
93
+ )
94
+ pdf.seek(0) # Reset file pointer
95
+ content = query_gpt4o_vision(pdf, prompt)
96
+ st.subheader("Raw Model Output")
97
+ st.code(content)
98
+ result = clean_json_response(content)
99
+ if result:
 
100
  st.success("Extraction Complete")
101
  st.subheader("Invoice Metadata")
102
+ st.json(result.get("invoice_header", {}))
103
  st.subheader("Line Items")
104
+ st.json(result.get("line_items", []))
105
+ else:
106
+ st.error("Could not parse JSON from the output.")
107
 
108
+ with tab2:
109
+ st.header("Send a Custom Prompt with PDF (GPT-4o Vision)")
110
+ pdf2 = st.file_uploader("Upload PDF", type="pdf", key="custom_pdf")
111
+ user_prompt = st.text_area(
112
+ "Enter your own prompt (for example: 'Summarize this invoice in bullet points' or 'Extract only supplier and total amount')",
113
+ height=100
114
+ )
115
+ if st.button("Send Custom Prompt") and pdf2 and user_prompt:
116
+ pdf2.seek(0)
117
+ content = query_gpt4o_vision(pdf2, user_prompt)
118
+ st.subheader("Raw Model Output")
119
+ st.code(content)
120
+ # Optionally try to parse JSON if present
121
+ result = clean_json_response(content)
122
+ if result:
123
+ st.subheader("Parsed JSON Output")
124
+ st.json(result)
125
+
126
+ st.caption("Powered by OpenAI GPT-4o Vision API. Set your OPENAI_API_KEY in your environment to use this app.")