Ayesha-Majeed commited on
Commit
0747a4b
·
verified ·
1 Parent(s): e59a373

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +264 -71
app.py CHANGED
@@ -1,46 +1,53 @@
1
- import gradio as gr
2
  import json
 
3
  from pathlib import Path
4
  from typing import List, Dict, Any
 
5
  from PIL import Image
6
  import PyPDF2
7
  import pytesseract
8
- import google.generativeai as genai
9
- import tempfile
 
 
 
10
 
11
 
12
- # ==================== Configure Gemini API ====================
13
  GEMINI_API_KEY = "AIzaSyB2b80YwNHs3Yj6RZOTL8wjXk2YhxCluOA"
14
  if GEMINI_API_KEY:
15
  genai.configure(api_key=GEMINI_API_KEY)
16
 
 
17
  EXTRACTION_PROMPT = """You are a shipping document data extraction specialist. Extract structured data from the provided shipping/logistics documents.
 
18
  Extract the following fields into a JSON format:
 
19
  {
20
  "poNumber": "Purchase Order Number",
21
  "shipFrom": "Origin/Ship From Location",
22
  "carrierType": "Transportation type (RAIL/TRUCK/etc)",
23
  "originCarrier": "Carrier name (CN/CPRS/etc)",
24
  "railCarNumber": "Rail car identifier",
25
- "totalQuantity": "Total quantity as number",
26
  "totalUnits": "Unit type (UNIT/MBF/MSFT/etc)",
27
  "accountName": "Customer/Account name",
28
  "inventories": {
29
  "items": [
30
  {
31
- "quantityShipped": "Quantity as number",
32
- "inventoryUnits": "Unit type",
33
  "productName": "Full product description",
34
  "productCode": "Product code/SKU",
35
  "product": {
36
  "category": "Product category (OSB/Lumber/etc)",
37
- "unit": "Unit count as number",
38
  "pcs": "Pieces per unit",
39
  "mbf": "Thousand board feet (if applicable)",
40
  "sf": "Square feet (if applicable)",
41
  "pcsHeight": "Height in inches",
42
  "pcsWidth": "Width in inches",
43
- "pcsLength": "Length in feet"
44
  },
45
  "customFields": [
46
  "Mill||Mill Name",
@@ -50,18 +57,27 @@ Extract the following fields into a JSON format:
50
  ]
51
  }
52
  }
 
53
  IMPORTANT INSTRUCTIONS:
54
  1. Extract ALL products/items found in the document
55
  2. Convert text numbers to actual numbers (e.g., "54" → 54)
56
- 3. Parse dimensions carefully, Do NOT convert units
57
  4. Calculate MBF/SF when possible from dimensions and piece count
58
- 5. If a field is not found, use null
59
- 6. For multiple products, create separate items
60
- 7. Extract custom fields like Mill, Vendor
 
 
61
  Return ONLY valid JSON, no markdown formatting or explanations."""
62
 
63
- # ==================== Utility functions ====================
 
 
 
 
 
64
  def extract_text_from_pdf(pdf_file) -> str:
 
65
  try:
66
  pdf_reader = PyPDF2.PdfReader(pdf_file)
67
  text = ""
@@ -71,115 +87,292 @@ def extract_text_from_pdf(pdf_file) -> str:
71
  except Exception as e:
72
  return f"Error extracting PDF text: {str(e)}"
73
 
 
74
  def convert_pdf_to_images(pdf_file) -> List[Image.Image]:
 
75
  try:
76
  from pdf2image import convert_from_path
77
  images = convert_from_path(pdf_file)
78
  return images
 
 
79
  except Exception as e:
80
  print(f"Error converting PDF to images: {e}")
81
  return []
82
 
83
- def extract_text_from_image(img: Image.Image) -> str:
 
 
84
  try:
85
- text = pytesseract.image_to_string(img)
86
- return text
 
 
 
 
 
 
 
 
 
 
 
87
  except Exception as e:
88
- print(f"Error extracting text from image: {e}")
89
  return ""
90
 
 
91
  def process_files(files: List[str]) -> Dict[str, Any]:
 
92
  processed_data = {
93
  "files": [],
94
  "combined_text": "",
95
  "images": []
96
  }
97
-
 
 
 
98
  for file_path in files:
99
  file_name = Path(file_path).name
100
  file_ext = Path(file_path).suffix.lower()
101
- file_data = {"filename": file_name, "type": file_ext, "content": ""}
102
-
 
 
 
 
 
103
  try:
104
  if file_ext == '.pdf':
105
  text = extract_text_from_pdf(file_path)
106
  file_data["content"] = text
107
  processed_data["combined_text"] += f"\n--- {file_name} ---\n{text}\n"
 
108
  images = convert_pdf_to_images(file_path)
109
  processed_data["images"].extend(images)
110
-
111
- elif file_ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif']:
112
  img = Image.open(file_path)
113
  processed_data["images"].append(img)
114
- text = extract_text_from_image(img)
115
- processed_data["combined_text"] += f"\n--- {file_name} ---\n{text}\n"
116
  file_data["content"] = f"Image file: {file_name}"
117
-
 
 
 
 
 
118
  elif file_ext in ['.txt']:
119
  with open(file_path, 'r', encoding='utf-8') as f:
120
  text = f.read()
121
- processed_data["combined_text"] += f"\n--- {file_name} ---\n{text}\n"
122
  file_data["content"] = text
123
-
 
124
  processed_data["files"].append(file_data)
 
125
  except Exception as e:
126
  file_data["content"] = f"Error processing file: {str(e)}"
127
  processed_data["files"].append(file_data)
128
-
129
  return processed_data
130
 
131
- def extract_with_gemini(processed_data: Dict[str, Any]) -> Dict[str, Any]:
 
 
 
 
 
 
132
  try:
133
- model = genai.GenerativeModel('models/gemini-2.5-flash')
 
 
 
 
 
 
 
 
134
  content = [EXTRACTION_PROMPT]
135
  if processed_data["combined_text"]:
136
  content.append(f"\nDocument Text:\n{processed_data['combined_text']}")
 
137
  for img in processed_data["images"][:5]:
138
  content.append(img)
 
139
  response = model.generate_content(content)
140
  response_text = response.text.strip()
141
- # Clean Markdown
142
- for mark in ["```json", "```"]:
143
- response_text = response_text.replace(mark, "")
 
 
 
 
 
144
  extracted_data = json.loads(response_text)
145
- return extracted_data
 
 
 
 
 
 
 
 
 
 
 
 
146
  except Exception as e:
147
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- # ==================== Gradio function ====================
150
- def gradio_extraction(uploaded_files):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  file_paths = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
- for file in uploaded_files:
154
- src_path = Path(file.name)
155
- file_name = src_path.name
156
- tmp_path = Path(tempfile.gettempdir()) / file_name
157
-
158
- with open(src_path, "rb") as src, open(tmp_path, "wb") as dst:
159
- dst.write(src.read())
160
-
161
- file_paths.append(str(tmp_path))
162
-
163
- processed_data = process_files(file_paths)
164
- extracted_data = extract_with_gemini(processed_data)
165
-
166
- with open("output.json", "w", encoding="utf-8") as f:
167
- json.dump(extracted_data, f, indent=2)
168
-
169
- return json.dumps(extracted_data, indent=2), "output.json"
170
-
171
-
172
- # ==================== Gradio Interface ====================
173
- iface = gr.Interface(
174
- fn=gradio_extraction,
175
- inputs = gr.File(file_types=[".pdf", ".jpg", ".jpeg", ".png", ".bmp", ".txt"], file_count="multiple"),
176
- outputs=[
177
- gr.Textbox(label="Extracted JSON",lines=15, max_lines=30),
178
- gr.File(label="Download JSON")
179
- ],
180
- title="Shipping Document Text Extractor",
181
- description="Upload PDFs or images of shipping/logistics documents and get structured JSON output.",
182
- theme=gr.themes.Base(primary_hue="blue")
183
- )
184
-
185
- iface.launch()
 
 
1
  import json
2
+ import os
3
  from pathlib import Path
4
  from typing import List, Dict, Any
5
+ import google.generativeai as genai
6
  from PIL import Image
7
  import PyPDF2
8
  import pytesseract
9
+ from doctr.io import DocumentFile
10
+ from doctr.models import ocr_predictor
11
+
12
+ # Optional: Gradio for a lightweight UI
13
+ import gradio as gr
14
 
15
 
16
+ # Configure Gemini API
17
  GEMINI_API_KEY = "AIzaSyB2b80YwNHs3Yj6RZOTL8wjXk2YhxCluOA"
18
  if GEMINI_API_KEY:
19
  genai.configure(api_key=GEMINI_API_KEY)
20
 
21
+
22
  EXTRACTION_PROMPT = """You are a shipping document data extraction specialist. Extract structured data from the provided shipping/logistics documents.
23
+
24
  Extract the following fields into a JSON format:
25
+
26
  {
27
  "poNumber": "Purchase Order Number",
28
  "shipFrom": "Origin/Ship From Location",
29
  "carrierType": "Transportation type (RAIL/TRUCK/etc)",
30
  "originCarrier": "Carrier name (CN/CPRS/etc)",
31
  "railCarNumber": "Rail car identifier",
32
+ "totalQuantity": "Total number of packages",
33
  "totalUnits": "Unit type (UNIT/MBF/MSFT/etc)",
34
  "accountName": "Customer/Account name",
35
  "inventories": {
36
  "items": [
37
  {
38
+ "quantityShipped": "Quantity as number, no of packages",
39
+ "inventoryUnits": "Unit type from document (MBF, FBM, SF, UNIT etc.)",
40
  "productName": "Full product description",
41
  "productCode": "Product code/SKU",
42
  "product": {
43
  "category": "Product category (OSB/Lumber/etc)",
44
+ "unit": "Unit type from document (MBF, FBM, SF, UNIT etc.)",
45
  "pcs": "Pieces per unit",
46
  "mbf": "Thousand board feet (if applicable)",
47
  "sf": "Square feet (if applicable)",
48
  "pcsHeight": "Height in inches",
49
  "pcsWidth": "Width in inches",
50
+ "pcsLength": "Length in the same unit as document"
51
  },
52
  "customFields": [
53
  "Mill||Mill Name",
 
57
  ]
58
  }
59
  }
60
+
61
  IMPORTANT INSTRUCTIONS:
62
  1. Extract ALL products/items found in the document
63
  2. Convert text numbers to actual numbers (e.g., "54" → 54)
64
+ 3. Parse dimensions carefully, Do NOT convert units(e.g., "2x6x14" means height=6, width=14, length=2)
65
  4. Calculate MBF/SF when possible from dimensions and piece count
66
+ 5. If a field is not found, use null (not empty string)
67
+ 6. For multiple products, create separate items in the inventories.items array
68
+ 7. Extract custom fields like Mill, Vendor from document metadata
69
+ 8. Unit types must be (PCS/PKG/MBF/MSFT/etc)
70
+
71
  Return ONLY valid JSON, no markdown formatting or explanations."""
72
 
73
+
74
+ # Temporary: print available models
75
+ #for model in genai.list_models():
76
+ # print(model)
77
+
78
+
79
  def extract_text_from_pdf(pdf_file) -> str:
80
+ """Extract text from PDF file"""
81
  try:
82
  pdf_reader = PyPDF2.PdfReader(pdf_file)
83
  text = ""
 
87
  except Exception as e:
88
  return f"Error extracting PDF text: {str(e)}"
89
 
90
+
91
  def convert_pdf_to_images(pdf_file) -> List[Image.Image]:
92
+ """Convert PDF pages to images"""
93
  try:
94
  from pdf2image import convert_from_path
95
  images = convert_from_path(pdf_file)
96
  return images
97
+ except ImportError:
98
+ return []
99
  except Exception as e:
100
  print(f"Error converting PDF to images: {e}")
101
  return []
102
 
103
+
104
+ def extract_text_from_image(img_path: str) -> str:
105
+ """Extract text using DocTR for better structure"""
106
  try:
107
+ doc = DocumentFile.from_images(img_path)
108
+ result = ocr_model(doc)
109
+ export = result.export()
110
+ lines = []
111
+
112
+ # Collect line-wise text preserving order
113
+ for page in export['pages']:
114
+ for block in page['blocks']:
115
+ for line in block['lines']:
116
+ line_text = " ".join([w['value'] for w in line['words']])
117
+ lines.append(line_text)
118
+
119
+ return "\n".join(lines)
120
  except Exception as e:
121
+ print(f"Error extracting text from image {img_path}: {e}")
122
  return ""
123
 
124
+
125
  def process_files(files: List[str]) -> Dict[str, Any]:
126
+ """Process uploaded files and extract text/images"""
127
  processed_data = {
128
  "files": [],
129
  "combined_text": "",
130
  "images": []
131
  }
132
+
133
+ if not files:
134
+ return processed_data
135
+
136
  for file_path in files:
137
  file_name = Path(file_path).name
138
  file_ext = Path(file_path).suffix.lower()
139
+
140
+ file_data = {
141
+ "filename": file_name,
142
+ "type": file_ext,
143
+ "content": ""
144
+ }
145
+
146
  try:
147
  if file_ext == '.pdf':
148
  text = extract_text_from_pdf(file_path)
149
  file_data["content"] = text
150
  processed_data["combined_text"] += f"\n--- {file_name} ---\n{text}\n"
151
+
152
  images = convert_pdf_to_images(file_path)
153
  processed_data["images"].extend(images)
154
+
155
+ elif file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
156
  img = Image.open(file_path)
157
  processed_data["images"].append(img)
 
 
158
  file_data["content"] = f"Image file: {file_name}"
159
+ processed_data["combined_text"] += f"\n--- {file_name} (Image) ---\n"
160
+
161
+ # ===== Add OCR here =====
162
+ text = pytesseract.image_to_string(img)
163
+ processed_data["combined_text"] += f"\n--- {file_name} (Image) ---\n{text}\n"
164
+
165
  elif file_ext in ['.txt']:
166
  with open(file_path, 'r', encoding='utf-8') as f:
167
  text = f.read()
 
168
  file_data["content"] = text
169
+ processed_data["combined_text"] += f"\n--- {file_name} ---\n{text}\n"
170
+
171
  processed_data["files"].append(file_data)
172
+
173
  except Exception as e:
174
  file_data["content"] = f"Error processing file: {str(e)}"
175
  processed_data["files"].append(file_data)
176
+
177
  return processed_data
178
 
179
+
180
+ def extract_with_gemini(processed_data: Dict[str, Any], api_key: str) -> Dict[str, Any]:
181
+ """Extract structured data using Gemini API"""
182
+
183
+ if not api_key:
184
+ return {"error": "Gemini API key not provided"}
185
+
186
  try:
187
+ genai.configure(api_key=api_key)
188
+
189
+ #model = genai.GenerativeModel('gemini-1.5-flash')
190
+ model = genai.GenerativeModel('models/gemini-2.5-flash') # recommended
191
+ # ya phir agar Cloud AI API hai to 'text-bison-001'
192
+
193
+ print("available models : ", genai.list_models())
194
+
195
+ # Prepare content
196
  content = [EXTRACTION_PROMPT]
197
  if processed_data["combined_text"]:
198
  content.append(f"\nDocument Text:\n{processed_data['combined_text']}")
199
+
200
  for img in processed_data["images"][:5]:
201
  content.append(img)
202
+
203
  response = model.generate_content(content)
204
  response_text = response.text.strip()
205
+
206
+ if response_text.startswith("```json"):
207
+ response_text = response_text[7:]
208
+ if response_text.startswith("```"):
209
+ response_text = response_text[3:]
210
+ if response_text.endswith("```"):
211
+ response_text = response_text[:-3]
212
+
213
  extracted_data = json.loads(response_text)
214
+
215
+ return {
216
+ "success": True,
217
+ "data": extracted_data,
218
+ "raw_response": response_text
219
+ }
220
+
221
+ except json.JSONDecodeError as e:
222
+ return {
223
+ "success": False,
224
+ "error": f"JSON parsing error: {str(e)}",
225
+ "raw_response": response.text if 'response' in locals() else None
226
+ }
227
  except Exception as e:
228
+ return {
229
+ "success": False,
230
+ "error": f"Extraction error: {str(e)}"
231
+ }
232
+
233
+
234
+ def process_documents(files, api_key):
235
+ """Main processing function"""
236
+
237
+ if not files:
238
+ print("⚠️ Please provide at least one document.")
239
+ return
240
+
241
+ if not api_key:
242
+ print("⚠️ Please provide your Gemini API key.")
243
+ return
244
+
245
+ # Step 1: Process files
246
+ print("📄 Processing files...")
247
+ processed_data = process_files(files)
248
+
249
+ # Step 2: Extract with Gemini
250
+ print("🤖 Extracting data with Gemini AI...")
251
+ result = extract_with_gemini(processed_data, api_key)
252
 
253
+ if result.get("success"):
254
+ json_output = json.dumps(result["data"], indent=2)
255
+ print(" Extraction Successful!")
256
+ print(json_output)
257
+ # ===== Save to output.json =====
258
+ output_file = "output.json"
259
+ with open(output_file, "w", encoding="utf-8") as f:
260
+ f.write(json_output)
261
+ print(f"JSON saved to {output_file}")
262
+ return json_output
263
+ else:
264
+ print(f" Extraction Failed: {result.get('error', 'Unknown error')}")
265
+ print("Raw Response:", result.get('raw_response', 'No response'))
266
+ return None
267
+
268
+
269
+ # ---------------------------
270
+ # Lightweight web UI wrapper
271
+ # ---------------------------
272
+ # This UI layer calls the exact same processing functions above.
273
+ # It does not modify extraction logic, only provides a user-friendly front end.
274
+
275
+ def _gradio_wrapper(uploaded_files):
276
+ """
277
+ uploaded_files: list of temporary file dicts that Gradio provides.
278
+ Returns: status_message, json_text, preview_text
279
+ """
280
+ if not uploaded_files:
281
+ return ("No files uploaded.", "{}", "")
282
+
283
+ # Map Gradio file objects to file paths that process_documents expects
284
  file_paths = []
285
+ for f in uploaded_files:
286
+ # Gradio supplies a dict-like object with 'name' pointing to the temp path
287
+ # Accept either direct path or dict with 'name'
288
+ if isinstance(f, str) and os.path.exists(f):
289
+ file_paths.append(f)
290
+ else:
291
+ # f may be a tempfile-like object or dict
292
+ try:
293
+ temp_path = f.name # file-like object
294
+ if os.path.exists(temp_path):
295
+ file_paths.append(temp_path)
296
+ else:
297
+ # attempt to copy bytes to a local temp file
298
+ content = None
299
+ if hasattr(f, "read"):
300
+ content = f.read()
301
+ elif isinstance(f, dict) and "name" in f:
302
+ file_paths.append(f["name"])
303
+ continue
304
+
305
+ if content:
306
+ # create a temp file
307
+ tmp_dir = Path("gradio_tmp")
308
+ tmp_dir.mkdir(exist_ok=True)
309
+ dest = tmp_dir / Path(f.name).name
310
+ with open(dest, "wb") as out:
311
+ out.write(content)
312
+ file_paths.append(str(dest))
313
+ except Exception:
314
+ # last-resort: try to interpret as path string
315
+ try:
316
+ if isinstance(f, dict) and "name" in f and os.path.exists(f["name"]):
317
+ file_paths.append(f["name"])
318
+ except Exception:
319
+ pass
320
+
321
+ if not file_paths:
322
+ return ("Uploaded files could not be located.", "{}", "")
323
+
324
+ status_msg = "Processing..."
325
+ # Call the existing processing pipeline (no changes)
326
+ json_result = process_documents(file_paths, GEMINI_API_KEY)
327
+
328
+ if json_result:
329
+ # process_documents returns JSON string on success
330
+ pretty = json_result
331
+ try:
332
+ parsed = json.loads(pretty)
333
+ preview = ""
334
+ # build a compact preview: show PO and first product name if available
335
+ po = parsed.get("poNumber")
336
+ inv = parsed.get("inventories", {}).get("items", [])
337
+ first_prod = inv[0].get("productName") if inv else None
338
+ preview = f"PO: {po}\nFirst product: {first_prod}"
339
+ except Exception:
340
+ preview = pretty[:100] + "..."
341
+ return ("Extraction completed.", pretty, preview)
342
+ else:
343
+ return ("Extraction failed. Check console for details.", "{}", "")
344
+
345
+
346
+ def build_ui():
347
+ """Create a simple web UI that uses the same processing code above."""
348
+ with gr.Blocks() as ui:
349
+ gr.Markdown("## Document Extractor — Upload files to extract structured shipping data")
350
+
351
+ with gr.Row():
352
+ with gr.Column(scale=2):
353
+ file_input = gr.File(
354
+ label="Select documents (PDF, image, text)",
355
+ file_count="multiple",
356
+ file_types=[".pdf", ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".txt", ".csv", ".doc", ".docx"]
357
+ )
358
+ run_btn = gr.Button("Extract", variant="primary")
359
+
360
+ with gr.Column(scale=3):
361
+ status = gr.Textbox(label="Status", lines=2)
362
+ output_json = gr.Code(label="Extracted JSON", language="json", lines=20)
363
+ preview = gr.Textbox(label="Quick preview", lines=4)
364
+
365
+ run_btn.click(fn=_gradio_wrapper, inputs=[file_input], outputs=[status, output_json, preview])
366
+
367
+ return ui
368
+
369
+
370
+ if __name__ == "__main__":
371
+ # Keep the original hardcoded call unchanged for CLI usage
372
+ files_to_process = ["sample1.pdf"] # Replace with your PDF paths
373
+ # Run CLI extraction (preserves original behavior)
374
+ process_documents(files_to_process, GEMINI_API_KEY)
375
 
376
+ # Launch the UI (optional). Comment out the next lines if you don't want the web UI.
377
+ demo = build_ui()
378
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)