Ayesha-Majeed commited on
Commit
a8f6542
·
verified ·
1 Parent(s): 886d641

Upload app (2).py

Browse files
Files changed (1) hide show
  1. app (2).py +185 -0
app (2).py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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",
47
+ "Vendor||Vendor Name"
48
+ ]
49
+ }
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 = ""
68
+ for page in pdf_reader.pages:
69
+ text += page.extract_text() + "\n"
70
+ return text
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()