Hztech commited on
Commit
9bcaa84
·
verified ·
1 Parent(s): 8f59e6e
Files changed (1) hide show
  1. app.py +181 -548
app.py CHANGED
@@ -1,548 +1,181 @@
1
- import sys
2
- import os
3
-
4
- # Ensure project root is in python path
5
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
6
-
7
- import streamlit as st
8
- import tempfile
9
- import pandas as pd
10
- import time
11
- from src.extractor import PassportExtractor
12
- from src.validators import validate_passport_data
13
- from src.formats import format_fly_dubai, format_iraqi, format_fly_baghdad
14
- from src.utils import parse_date
15
-
16
-
17
- def process_pdf_file(uploaded_file, airline="iraqi"):
18
- """
19
- Process a single uploaded PDF file and extract passport data.
20
-
21
- Args:
22
- uploaded_file: Uploaded file object (Streamlit or similar)
23
- airline (str): Airline format for date formatting ("iraqi", "default", "fly dubai", "fly baghdad")
24
-
25
- Returns:
26
- List[dict]: Extracted passport data for each page/passport
27
- """
28
- extractor = PassportExtractor(use_gpu=True)
29
- results = []
30
- tmp_path = None
31
-
32
- try:
33
- # Save uploaded file to temporary location
34
- suffix = os.path.splitext(uploaded_file.name)[1]
35
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
36
- tmp.write(uploaded_file.getvalue())
37
- tmp_path = tmp.name
38
-
39
- # Extract passport data from PDF with airline-specific formatting
40
- try:
41
- results = extractor.process_pdf(tmp_path, airline=airline.lower(), progress_callback=None)
42
- if not results:
43
- print(f"⚠️ No passport data found in PDF: {uploaded_file.name}")
44
- # Return placeholder result for PDFs without MRZ
45
- results = [{
46
- "surname": "•••",
47
- "name": "•••",
48
- "country": "•••",
49
- "nationality": "•••",
50
- "passport_number": "•••",
51
- "sex": "•••",
52
- "date_of_birth": "•••",
53
- "expiration_date": "•••",
54
- "personal_number": "•••",
55
- "mrz_full_string": "",
56
- "valid_score": 0,
57
- "mrz_found": False
58
- }]
59
- except Exception as e:
60
- print(f"⚠️ Error processing PDF {uploaded_file.name}: {str(e)}")
61
- # Return placeholder result for PDFs with processing errors
62
- results = [{
63
- "surname": "•••",
64
- "name": "•••",
65
- "country": "•••",
66
- "nationality": "•••",
67
- "passport_number": "•••",
68
- "sex": "•••",
69
- "date_of_birth": "•••",
70
- "expiration_date": "•••",
71
- "personal_number": "•••",
72
- "mrz_full_string": "",
73
- "valid_score": 0,
74
- "mrz_found": False
75
- }]
76
-
77
- # Attach source file name to each result
78
- for res in results:
79
- res['source_file'] = uploaded_file.name
80
-
81
- except Exception as e:
82
- print(f"❌ Error processing {uploaded_file.name}: {str(e)}")
83
- import traceback
84
- print(f"Debug info: {traceback.format_exc()}")
85
- results = []
86
-
87
- finally:
88
- # Clean up temp file
89
- if tmp_path and os.path.exists(tmp_path):
90
- try:
91
- os.remove(tmp_path)
92
- except Exception as cleanup_error:
93
- print(f"Warning: Could not clean up temp file: {cleanup_error}")
94
-
95
- return results
96
-
97
- # Set page configuration
98
- st.set_page_config(
99
- page_title="Passport OCR Tool",
100
- page_icon="🛂",
101
- layout="wide"
102
- )
103
-
104
- # Initialize Extractor (cached to avoid reloading model)
105
- @st.cache_resource
106
- def get_extractor():
107
- return PassportExtractor(use_gpu=True)
108
-
109
- def save_uploaded_file(uploaded_file):
110
- """Save uploaded file to a temporary location and return the path."""
111
- try:
112
- suffix = os.path.splitext(uploaded_file.name)[1]
113
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_file:
114
- tmp_file.write(uploaded_file.getvalue())
115
- return tmp_file.name
116
- except Exception as e:
117
- st.error(f"Error saving file: {e}")
118
- return None
119
-
120
- def main():
121
- st.title("🛂 Passport OCR Extractor")
122
-
123
- # Add a description
124
- st.markdown("""
125
- This tool extracts data from passport MRZ (Machine-Readable Zone) codes.
126
- Upload passport images or PDFs, and the app will return a structured table of the extracted information.
127
- You can also select an airline-specific format for the output data.
128
- """)
129
-
130
- # Sidebar Configuration
131
- st.sidebar.header("Settings")
132
- st.sidebar.info("💡 Optimized for performance - GPU enabled")
133
- airline = st.sidebar.selectbox("Choose Airline Format", ["Default", "Fly Dubai", "Iraqi", "Fly Baghdad"])
134
-
135
- # Export settings - simplified
136
- st.sidebar.header("Export Settings")
137
- export_all_files = st.sidebar.checkbox(
138
- "Include all files in export",
139
- value=False,
140
- help="When checked, includes files with missing/invalid data (shows ••• for missing fields)"
141
- )
142
- st.session_state.export_all_files = export_all_files
143
-
144
- # File Uploader
145
- uploaded_files = st.file_uploader(
146
- "Upload Passport Files",
147
- type=['png', 'jpg', 'jpeg', 'pdf', 'avif', 'webp', 'bmp', 'tiff'],
148
- accept_multiple_files=True
149
- )
150
-
151
- # Initialize session state to prevent crashes from rapid clicks
152
- if 'processing' not in st.session_state:
153
- st.session_state.processing = False
154
- if 'results_df' not in st.session_state:
155
- st.session_state.results_df = None
156
- if 'airline_format' not in st.session_state:
157
- st.session_state.airline_format = None
158
- if 'download_counter' not in st.session_state:
159
- st.session_state.download_counter = 0
160
- if 'show_results' not in st.session_state:
161
- st.session_state.show_results = False
162
- if 'clear_and_extract' not in st.session_state:
163
- st.session_state.clear_and_extract = False
164
-
165
- # Create a container for results - this will be cleared when new extraction starts
166
- results_container = st.container()
167
-
168
- # Display existing results if available and not processing
169
- if st.session_state.results_df is not None and not st.session_state.processing and st.session_state.show_results:
170
- with results_container:
171
- st.subheader("📊 Extracted Data")
172
- st.dataframe(st.session_state.results_df)
173
-
174
- # Show export options for existing results
175
- st.subheader("📥 Export Data")
176
- col1, col2, col3 = st.columns(3)
177
-
178
- with col1:
179
- csv = st.session_state.results_df.to_csv(index=False).encode('utf-8')
180
- st.download_button(
181
- label="Download data as CSV",
182
- data=csv,
183
- file_name=f"passport_data_{st.session_state.airline_format.lower()}.csv",
184
- mime="text/csv",
185
- key=f"existing_csv_{st.session_state.download_counter}"
186
- )
187
-
188
- with col2:
189
- # Create an in-memory Excel file
190
- from io import BytesIO
191
- output = BytesIO()
192
- with pd.ExcelWriter(output, engine='openpyxl') as writer:
193
- st.session_state.results_df.to_excel(writer, index=False, sheet_name='PassportData')
194
-
195
- st.download_button(
196
- label="Download data as Excel",
197
- data=output.getvalue(),
198
- file_name=f"passport_data_{st.session_state.airline_format.lower()}.xlsx",
199
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
200
- key=f"existing_excel_{st.session_state.download_counter}"
201
- )
202
-
203
- with col3:
204
- if st.button("Clear Results"):
205
- st.session_state.results_df = None
206
- st.session_state.airline_format = None
207
- st.session_state.show_results = False
208
- st.rerun()
209
-
210
- if uploaded_files and not st.session_state.processing:
211
- if st.button("Extract Data"):
212
- # First, clear results like Clear Results button does
213
- st.session_state.results_df = None
214
- st.session_state.airline_format = None
215
- st.session_state.show_results = False
216
- st.session_state.download_counter += 1
217
- st.session_state.clear_and_extract = True
218
-
219
- # Force immediate UI update to clear old results
220
- st.rerun()
221
-
222
- # Check if we need to start extraction after clearing
223
- if st.session_state.clear_and_extract:
224
- st.session_state.clear_and_extract = False
225
- st.session_state.processing = True
226
-
227
- try:
228
- # Initialize extractor inside the button click to use the latest settings
229
- extractor = PassportExtractor(use_gpu=True)
230
-
231
- all_results = []
232
- problematic_files = [] # Track files with issues
233
-
234
- # Create a container for processing status
235
- status_container = st.container()
236
- progress_container = st.container()
237
-
238
- with progress_container:
239
- main_progress_bar = st.progress(0)
240
-
241
- # Show single status line at the beginning
242
- with status_container:
243
- status_text = st.empty()
244
- status_text.write(f"🔄 Processing {len(uploaded_files)} files...")
245
-
246
- for i, file in enumerate(uploaded_files):
247
-
248
- # Check file size for Streamlit free tier
249
- try:
250
- file_size = len(file.getvalue())
251
- if file_size > 10 * 1024 * 1024: # 10 MB
252
- st.error(f"❌ File too large: {file.name} ({file_size / (1024*1024):.1f} MB). Max 10 MB allowed.")
253
- problematic_files.append({
254
- 'file_name': file.name,
255
- 'reason': f'File too large ({file_size / (1024*1024):.1f} MB). Max 10 MB allowed.'
256
- })
257
- with progress_container:
258
- main_progress_bar.progress((i + 1) / len(uploaded_files))
259
- continue
260
- except Exception as e:
261
- st.error(f"❌ Error checking file size for {file.name}: {str(e)}")
262
- problematic_files.append({
263
- 'file_name': file.name,
264
- 'reason': f'Error checking file size: {str(e)}'
265
- })
266
- with progress_container:
267
- main_progress_bar.progress((i + 1) / len(uploaded_files))
268
- continue
269
-
270
- with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as tmp:
271
- tmp.write(file.getvalue())
272
- tmp_path = tmp.name
273
-
274
- try:
275
- # Check both MIME type and file extension for PDF detection
276
- is_pdf = file.type == "application/pdf" or file.name.lower().endswith('.pdf')
277
-
278
- file_processed = False
279
- if is_pdf:
280
- try:
281
- # Use the new standalone PDF processing function
282
- results = process_pdf_file(file, airline=airline.lower())
283
- if results:
284
- file_processed = True
285
- except Exception as e:
286
- results = []
287
- pass
288
- else:
289
- try:
290
- result = extractor.get_data(tmp_path, airline=airline.lower())
291
- if result:
292
- results = [result]
293
- file_processed = True
294
- else:
295
- results = []
296
- except Exception as e:
297
- results = []
298
- pass
299
-
300
- # Add source file to results and extend all_results
301
- mrz_found_in_file = False
302
- for res in results:
303
- res['source_file'] = file.name
304
- # Check if MRZ was found in any result
305
- if res.get('mrz_found', False):
306
- mrz_found_in_file = True
307
- all_results.extend(results)
308
-
309
- # Track problematic files - check if MRZ was found OR if no results
310
- if not file_processed:
311
- problematic_files.append({
312
- 'file_name': file.name,
313
- 'reason': 'File could not be processed - unsupported format or corrupted file'
314
- })
315
- elif not results:
316
- problematic_files.append({
317
- 'file_name': file.name,
318
- 'reason': 'No passport data detected - image may be blurry or passport not visible'
319
- })
320
- elif not mrz_found_in_file:
321
- problematic_files.append({
322
- 'file_name': file.name,
323
- 'reason': 'MRZ data not found - passport may be damaged or partially visible'
324
- })
325
- # Debug output
326
- print(f"DEBUG: Added problematic file: {file.name} (file_processed: {file_processed}, results: {len(results)}, mrz_found: {mrz_found_in_file})")
327
-
328
- except Exception as e:
329
- # Track files that caused errors
330
- problematic_files.append({
331
- 'file_name': file.name,
332
- 'reason': f'Processing error: {str(e)}'
333
- })
334
- pass
335
-
336
- finally:
337
- # Safely remove temp file
338
- try:
339
- if os.path.exists(tmp_path):
340
- os.remove(tmp_path)
341
- except:
342
- pass
343
-
344
- # Update main progress bar - use container to avoid state issues
345
- with progress_container:
346
- main_progress_bar.progress((i + 1) / len(uploaded_files))
347
-
348
- # Update status to show completion
349
- with status_container:
350
- status_text.write(f"✅ Processing complete!")
351
-
352
- # Debug output for problematic files
353
- print(f"DEBUG: Total problematic files: {len(problematic_files)}")
354
- print(f"DEBUG: Total results: {len(all_results)}")
355
- for problem in problematic_files:
356
- print(f"DEBUG: Problematic: {problem.get('file_name', '<unknown>')} - {problem.get('reason') or problem.get('issue') or problem.get('message') or problem.get('error') or '<unspecified>'}")
357
-
358
- # Filter out problematic results from all_results
359
- good_results = []
360
- for result in all_results:
361
- # Check if this result belongs to a problematic file
362
- is_problematic = any(problem['file_name'] == result.get('source_file') for problem in problematic_files)
363
- if not is_problematic:
364
- good_results.append(result)
365
-
366
- # Show results only after all processing is complete
367
- successful_files = len(set(result.get('source_file', '') for result in good_results))
368
- total_files = len(uploaded_files)
369
- failed_files = total_files - successful_files
370
-
371
- # Display success/failure summary
372
- if failed_files > 0:
373
- st.warning(f"⚠️ {successful_files}/{total_files} passports were successfully extracted")
374
-
375
- # Show detailed list of failed passports
376
- with st.expander("📋 Click to see failed passport details"):
377
- st.write("**Failed Passports:**")
378
- for problem in problematic_files:
379
- display_name = None
380
- for res in all_results:
381
- if res.get('source_file') == problem.get('file_name'):
382
- display_name = (
383
- res.get('surname') or
384
- res.get('given_names') or
385
- res.get('name') or
386
- res.get('Last Name') or
387
- res.get('First Name and Middle Name')
388
- )
389
- break
390
- if display_name:
391
- st.write(f"• {problem.get('file_name', '<unknown>')} - {display_name} - {problem.get('reason') or problem.get('issue') or problem.get('message') or problem.get('error') or '<unspecified>'}")
392
- else:
393
- st.write(f"• {problem.get('file_name', '<unknown>')} - {problem.get('reason') or problem.get('issue') or problem.get('message') or problem.get('error') or '<unspecified>'}")
394
- else:
395
- st.success(f"✅ All {successful_files} passports were successfully imported")
396
-
397
- if not good_results:
398
- st.warning("No data could be extracted. Please check the files or try again.")
399
- st.session_state.processing = False
400
- st.session_state.results_df = None
401
- st.session_state.airline_format = None
402
- return
403
-
404
- if not good_results:
405
- st.warning("No data could be extracted. Please check the files or try again.")
406
- st.session_state.processing = False
407
- st.session_state.results_df = None
408
- st.session_state.airline_format = None
409
- return
410
-
411
- # Format data based on airline selection
412
- if airline == "Fly Dubai":
413
- df = format_fly_dubai(good_results)
414
- elif airline == "Iraqi":
415
- df = format_iraqi(good_results)
416
- elif airline == "Fly Baghdad":
417
- df = format_fly_baghdad(good_results)
418
- else:
419
- df = pd.DataFrame(good_results)
420
-
421
- # If export_all_files is checked, add placeholder data to display table
422
- if st.session_state.export_all_files and problematic_files:
423
- # Create placeholder data that matches the airline format
424
- placeholder_data = []
425
-
426
- for problem in problematic_files:
427
- if airline == "Fly Dubai":
428
- placeholder_data.append({
429
- "TYPE": "Adult", # Default for problematic files
430
- "TITLE": "MR",
431
- "FIRST NAME": "•••",
432
- "LAST NAME": "•••",
433
- "DOB (DD/MM/YYYY)": "•••",
434
- "GENDER": "Male"
435
- })
436
- elif airline == "Iraqi":
437
- placeholder_data.append({
438
- "Last Name": "•••",
439
- "First Name and Middle Name": "•••",
440
- "Title": "MR",
441
- "PTC": "ADT", # Default to Adult
442
- "Gender": "M",
443
- "Date of Birth": "•••",
444
- "Passport Last Name": "•••",
445
- "Passport First Name": "•••",
446
- "Passport Middle Name": "",
447
- "Passport Number": "•••",
448
- "Passport Nationality": "•••",
449
- "Passport Issue Country": "•••",
450
- "Passport Expiry Date": "•••",
451
- "Visa Number": "", "Visa Type": "", "Visa Issue Date": "", "Place of Birth": "",
452
- "Visa Place of Issue": "", "Visa Country of Application": "", "Address Type": "",
453
- "Address Country": "", "Address Details": "", "Address City": "",
454
- "Address State": "", "Address Zip Code": ""
455
- })
456
- elif airline == "Fly Baghdad":
457
- placeholder_data.append({
458
- "Sequence": len(good_results) + len(placeholder_data) + 1,
459
- "Traveling With": "",
460
- "Pax Type": "ADT",
461
- "Title": "MR",
462
- "First Name": "•••",
463
- "Last Name": "•••",
464
- "Gender": "MALE",
465
- "DOB (dd/mm/yyyy)": "•••",
466
- "Nationality": "•••",
467
- "Passport Number": "•••",
468
- "Passport Expiry (dd/mm/yyyy)": "•••",
469
- "Passport Issued Country": "•••"
470
- })
471
- else: # Default format
472
- placeholder_data.append({
473
- 'source_file': problem['file_name'],
474
- 'surname': '•••',
475
- 'given_names': '•••',
476
- 'passport_number': '•••',
477
- 'nationality': '•••',
478
- 'date_of_birth': '•••',
479
- 'sex': '•••',
480
- 'expiration_date': '•••',
481
- 'personal_number': '•••',
482
- 'mrz_found': False
483
- })
484
-
485
- if placeholder_data:
486
- placeholder_df = pd.DataFrame(placeholder_data)
487
- df = pd.concat([df, placeholder_df], ignore_index=True)
488
-
489
- # Store results in session state
490
- st.session_state.results_df = df
491
- st.session_state.airline_format = airline
492
- st.session_state.show_results = True
493
-
494
- # Display results in the container
495
- with results_container:
496
- st.subheader("📊 Extracted Data")
497
- st.dataframe(df)
498
-
499
- # Prepare export dataframe (same as display dataframe now)
500
- export_df = df
501
-
502
- # Download buttons - now export_df is guaranteed to be defined
503
- col1, col2 = st.columns(2)
504
-
505
- with col1:
506
- csv = export_df.to_csv(index=False).encode('utf-8')
507
- st.download_button(
508
- label="Download data as CSV",
509
- data=csv,
510
- file_name=f"passport_data_{airline.lower()}.csv",
511
- mime="text/csv",
512
- key=f"csv_download_{airline}_{st.session_state.get('download_counter', 0)}"
513
- )
514
-
515
- with col2:
516
- # Create an in-memory Excel file
517
- from io import BytesIO
518
- output = BytesIO()
519
- with pd.ExcelWriter(output, engine='openpyxl') as writer:
520
- export_df.to_excel(writer, index=False, sheet_name='PassportData')
521
-
522
- st.download_button(
523
- label="Download data as Excel",
524
- data=output.getvalue(),
525
- file_name=f"passport_data_{airline.lower()}.xlsx",
526
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
527
- key=f"excel_download_{airline}_{st.session_state.get('download_counter', 0)}"
528
- )
529
-
530
- # Increment counter for next extraction to avoid duplicate IDs
531
- st.session_state.download_counter += 1
532
-
533
- # Reset processing state
534
- st.session_state.processing = False
535
-
536
- except Exception as e:
537
- st.error(f"❌ Unexpected error during processing: {str(e)}")
538
- import traceback
539
- st.error(f"Debug info: {traceback.format_exc()}")
540
- st.session_state.processing = False
541
-
542
- finally:
543
- # Ensure processing state is reset even if an error occurs
544
- if 'processing' in st.session_state:
545
- st.session_state.processing = False
546
-
547
- if __name__ == "__main__":
548
- main()
 
1
+ import os
2
+ import tempfile
3
+ import pandas as pd
4
+ import gradio as gr
5
+ from io import BytesIO
6
+ from src.extractor import PassportExtractor
7
+ from src.formats import format_fly_dubai, format_iraqi, format_fly_baghdad
8
+ from src.utils import parse_date
9
+
10
+ # Initialize extractor globally (Hugging Face Spaces will cache this)
11
+ # Note: On CPU-only spaces, use_gpu should be False.
12
+ # We'll try to detect if GPU is available.
13
+ import torch
14
+ use_gpu = torch.cuda.is_available()
15
+ extractor = PassportExtractor(use_gpu=use_gpu)
16
+
17
+ def process_passports(files, airline, include_all_files, progress=gr.Progress()):
18
+ if not files:
19
+ return None, None, None, "Please upload at least one file."
20
+
21
+ all_results = []
22
+ problematic_files = []
23
+
24
+ progress(0, desc="Starting processing...")
25
+
26
+ for i, file_path in enumerate(files):
27
+ file_name = os.path.basename(file_path)
28
+ progress((i / len(files)), desc=f"Processing {file_name}...")
29
+
30
+ try:
31
+ is_pdf = file_name.lower().endswith('.pdf')
32
+
33
+ if is_pdf:
34
+ # Use extractor's PDF processing
35
+ # Pass airline.lower() to match internal logic if needed
36
+ results = extractor.process_pdf(file_path, airline=airline.lower())
37
+ if not results:
38
+ # Placeholder for failed PDF
39
+ results = [{
40
+ "surname": "•••", "name": "•••", "country": "•••",
41
+ "nationality": "•••", "passport_number": "•••",
42
+ "sex": "•••", "date_of_birth": "•••",
43
+ "expiration_date": "•••", "personal_number": "•••",
44
+ "mrz_full_string": "", "valid_score": 0, "mrz_found": False
45
+ }]
46
+ else:
47
+ # Process as image
48
+ result = extractor.get_data(file_path, airline=airline.lower())
49
+ results = [result] if result else []
50
+
51
+ # Attach source file name and check if MRZ found
52
+ mrz_found_in_file = False
53
+ for res in results:
54
+ res['source_file'] = file_name
55
+ if res.get('mrz_found', False):
56
+ mrz_found_in_file = True
57
+
58
+ all_results.extend(results)
59
+
60
+ # Track problematic files
61
+ if not results or not mrz_found_in_file:
62
+ problematic_files.append({
63
+ 'file_name': file_name,
64
+ 'reason': 'MRZ data not found or file unreadable'
65
+ })
66
+
67
+ except Exception as e:
68
+ problematic_files.append({
69
+ 'file_name': file_name,
70
+ 'reason': f'Error: {str(e)}'
71
+ })
72
+
73
+ # Filter good results
74
+ good_results = []
75
+ for result in all_results:
76
+ is_problematic = any(p['file_name'] == result.get('source_file') for p in problematic_files)
77
+ if not is_problematic:
78
+ good_results.append(result)
79
+
80
+ if not good_results and not include_all_files:
81
+ return None, None, None, "No valid data could be extracted from the uploaded files."
82
+
83
+ # Format data based on selection
84
+ if airline == "Fly Dubai":
85
+ df = format_fly_dubai(good_results)
86
+ elif airline == "Iraqi":
87
+ df = format_iraqi(good_results)
88
+ elif airline == "Fly Baghdad":
89
+ df = format_fly_baghdad(good_results)
90
+ else:
91
+ df = pd.DataFrame(good_results)
92
+
93
+ # Handle placeholders if requested
94
+ if include_all_files and problematic_files:
95
+ placeholder_data = []
96
+ for p in problematic_files:
97
+ if airline == "Fly Dubai":
98
+ placeholder_data.append({
99
+ "TYPE": "Adult", "TITLE": "MR", "FIRST NAME": "•••", "LAST NAME": "•••",
100
+ "DOB (DD/MM/YYYY)": "•••", "GENDER": "Male"
101
+ })
102
+ elif airline == "Iraqi":
103
+ placeholder_data.append({
104
+ "Last Name": "•••", "First Name and Middle Name": "•••", "Title": "MR",
105
+ "PTC": "ADT", "Gender": "M", "Date of Birth": "•••",
106
+ "Passport Last Name": "•••", "Passport First Name": "•••",
107
+ "Passport Middle Name": "", "Passport Number": "•••",
108
+ "Passport Nationality": "•••", "Passport Issue Country": "•••",
109
+ "Passport Expiry Date": "•••", "Visa Number": "", "Visa Type": "",
110
+ "Visa Issue Date": "", "Place of Birth": "", "Visa Place of Issue": "",
111
+ "Visa Country of Application": "", "Address Type": "", "Address Country": "",
112
+ "Address Details": "", "Address City": "", "Address State": "", "Address Zip Code": ""
113
+ })
114
+ elif airline == "Fly Baghdad":
115
+ placeholder_data.append({
116
+ "Sequence": len(good_results) + len(placeholder_data) + 1,
117
+ "Traveling With": "", "Pax Type": "ADT", "Title": "MR", "First Name": "•••",
118
+ "Last Name": "•••", "Gender": "MALE", "DOB (dd/mm/yyyy)": "•••",
119
+ "Nationality": "•••", "Passport Number": "•••",
120
+ "Passport Expiry (dd/mm/yyyy)": "•••", "Passport Issued Country": "•••"
121
+ })
122
+ else:
123
+ placeholder_data.append({
124
+ 'source_file': p['file_name'], 'surname': '•••', 'given_names': '•••',
125
+ 'passport_number': '•••', 'nationality': '•••', 'date_of_birth': '•••',
126
+ 'sex': '•••', 'expiration_date': '•••', 'personal_number': '•••',
127
+ 'mrz_found': False
128
+ })
129
+
130
+ if placeholder_data:
131
+ df = pd.concat([df, pd.DataFrame(placeholder_data)], ignore_index=True)
132
+
133
+ # Generate output files
134
+ temp_dir = tempfile.gettempdir()
135
+ csv_path = os.path.join(temp_dir, f"passport_data_{airline.lower().replace(' ', '_')}.csv")
136
+ excel_path = os.path.join(temp_dir, f"passport_data_{airline.lower().replace(' ', '_')}.xlsx")
137
+
138
+ df.to_csv(csv_path, index=False)
139
+ df.to_excel(excel_path, index=False)
140
+
141
+ status_msg = f"✅ Successfully processed {len(good_results)} passports."
142
+ if problematic_files:
143
+ status_msg += f" ⚠️ {len(problematic_files)} files had issues."
144
+
145
+ return df, csv_path, excel_path, status_msg
146
+
147
+ # Gradio Interface
148
+ with gr.Blocks(title="Passport OCR Extractor") as demo:
149
+ gr.Markdown("# 🛂 Passport OCR Extractor")
150
+ gr.Markdown("Upload passport images or PDFs to extract data into structured formats.")
151
+
152
+ with gr.Row():
153
+ with gr.Column(scale=1):
154
+ files_input = gr.File(label="Upload Passport Files", file_count="multiple", file_types=[".png", ".jpg", ".jpeg", ".pdf", ".webp"])
155
+ airline_input = gr.Dropdown(choices=["Default", "Fly Dubai", "Iraqi", "Fly Baghdad"], value="Default", label="Choose Airline Format")
156
+ include_all_checkbox = gr.Checkbox(label="Include all files in export", info="Show placeholders for missing/invalid data")
157
+ process_btn = gr.Button("Extract Data", variant="primary")
158
+
159
+ with gr.Column(scale=2):
160
+ status_output = gr.Markdown("Status: Ready")
161
+ dataframe_output = gr.Dataframe(label="Extracted Data")
162
+ with gr.Row():
163
+ csv_output = gr.File(label="Download CSV")
164
+ excel_output = gr.File(label="Download Excel")
165
+
166
+ process_btn.click(
167
+ fn=process_passports,
168
+ inputs=[files_input, airline_input, include_all_checkbox],
169
+ outputs=[dataframe_output, csv_output, excel_output, status_output]
170
+ )
171
+
172
+ gr.Markdown("""
173
+ ### ℹ️ Instructions
174
+ 1. Upload one or more passport images or PDF files.
175
+ 2. Select the desired airline format from the dropdown.
176
+ 3. Click 'Extract Data' to start the OCR process.
177
+ 4. View the results in the table and download them as CSV or Excel files.
178
+ """)
179
+
180
+ if __name__ == "__main__":
181
+ demo.launch()