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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|