Spaces:
Running
Running
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,174 +0,0 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
import os
|
| 3 |
-
|
| 4 |
-
# Ensure project root is in python path for Hugging Face / Docker
|
| 5 |
-
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 6 |
-
|
| 7 |
-
import tempfile
|
| 8 |
-
import pandas as pd
|
| 9 |
-
import gradio as gr
|
| 10 |
-
from io import BytesIO
|
| 11 |
-
from src.extractor import PassportExtractor
|
| 12 |
-
from src.formats import format_fly_dubai, format_iraqi, format_fly_baghdad
|
| 13 |
-
from src.utils import parse_date
|
| 14 |
-
|
| 15 |
-
# Initialize extractor globally (Hugging Face Spaces will cache this)
|
| 16 |
-
import torch
|
| 17 |
-
use_gpu = torch.cuda.is_available()
|
| 18 |
-
extractor = PassportExtractor(use_gpu=use_gpu)
|
| 19 |
-
|
| 20 |
-
def process_passports(files, airline, include_all_files, progress=gr.Progress()):
|
| 21 |
-
if not files:
|
| 22 |
-
return None, None, None, "Please upload at least one file."
|
| 23 |
-
|
| 24 |
-
all_results = []
|
| 25 |
-
problematic_files = []
|
| 26 |
-
|
| 27 |
-
progress(0, desc="Starting processing...")
|
| 28 |
-
|
| 29 |
-
for i, file_path in enumerate(files):
|
| 30 |
-
file_name = os.path.basename(file_path)
|
| 31 |
-
progress((i / len(files)), desc=f"Processing {file_name}...")
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
is_pdf = file_name.lower().endswith('.pdf')
|
| 35 |
-
|
| 36 |
-
if is_pdf:
|
| 37 |
-
results = extractor.process_pdf(file_path, airline=airline.lower())
|
| 38 |
-
if not results:
|
| 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 |
-
result = extractor.get_data(file_path, airline=airline.lower())
|
| 48 |
-
results = [result] if result else []
|
| 49 |
-
|
| 50 |
-
mrz_found_in_file = False
|
| 51 |
-
for res in results:
|
| 52 |
-
res['source_file'] = file_name
|
| 53 |
-
if res.get('mrz_found', False):
|
| 54 |
-
mrz_found_in_file = True
|
| 55 |
-
|
| 56 |
-
all_results.extend(results)
|
| 57 |
-
|
| 58 |
-
if not results or not mrz_found_in_file:
|
| 59 |
-
problematic_files.append({
|
| 60 |
-
'file_name': file_name,
|
| 61 |
-
'reason': 'MRZ data not found or file unreadable'
|
| 62 |
-
})
|
| 63 |
-
|
| 64 |
-
except Exception as e:
|
| 65 |
-
problematic_files.append({
|
| 66 |
-
'file_name': file_name,
|
| 67 |
-
'reason': f'Error: {str(e)}'
|
| 68 |
-
})
|
| 69 |
-
|
| 70 |
-
good_results = []
|
| 71 |
-
for result in all_results:
|
| 72 |
-
is_problematic = any(p['file_name'] == result.get('source_file') for p in problematic_files)
|
| 73 |
-
if not is_problematic:
|
| 74 |
-
good_results.append(result)
|
| 75 |
-
|
| 76 |
-
if not good_results and not include_all_files:
|
| 77 |
-
return None, None, None, "No valid data could be extracted from the uploaded files."
|
| 78 |
-
|
| 79 |
-
if airline == "Fly Dubai":
|
| 80 |
-
df = format_fly_dubai(good_results)
|
| 81 |
-
elif airline == "Iraqi":
|
| 82 |
-
df = format_iraqi(good_results)
|
| 83 |
-
elif airline == "Fly Baghdad":
|
| 84 |
-
df = format_fly_baghdad(good_results)
|
| 85 |
-
else:
|
| 86 |
-
df = pd.DataFrame(good_results)
|
| 87 |
-
|
| 88 |
-
if include_all_files and problematic_files:
|
| 89 |
-
placeholder_data = []
|
| 90 |
-
for p in problematic_files:
|
| 91 |
-
if airline == "Fly Dubai":
|
| 92 |
-
placeholder_data.append({
|
| 93 |
-
"TYPE": "Adult", "TITLE": "MR", "FIRST NAME": "•••", "LAST NAME": "•••",
|
| 94 |
-
"DOB (DD/MM/YYYY)": "•••", "GENDER": "Male"
|
| 95 |
-
})
|
| 96 |
-
elif airline == "Iraqi":
|
| 97 |
-
placeholder_data.append({
|
| 98 |
-
"Last Name": "•••", "First Name and Middle Name": "•••", "Title": "MR",
|
| 99 |
-
"PTC": "ADT", "Gender": "M", "Date of Birth": "•••",
|
| 100 |
-
"Passport Last Name": "•••", "Passport First Name": "•••",
|
| 101 |
-
"Passport Middle Name": "", "Passport Number": "•••",
|
| 102 |
-
"Passport Nationality": "•••", "Passport Issue Country": "•••",
|
| 103 |
-
"Passport Expiry Date": "•••", "Visa Number": "", "Visa Type": "",
|
| 104 |
-
"Visa Issue Date": "", "Place of Birth": "", "Visa Place of Issue": "",
|
| 105 |
-
"Visa Country of Application": "", "Address Type": "", "Address Country": "",
|
| 106 |
-
"Address Details": "", "Address City": "", "Address State": "", "Address Zip Code": ""
|
| 107 |
-
})
|
| 108 |
-
elif airline == "Fly Baghdad":
|
| 109 |
-
placeholder_data.append({
|
| 110 |
-
"Sequence": len(good_results) + len(placeholder_data) + 1,
|
| 111 |
-
"Traveling With": "", "Pax Type": "ADT", "Title": "MR", "First Name": "•••",
|
| 112 |
-
"Last Name": "•••", "Gender": "MALE", "DOB (dd/mm/yyyy)": "•••",
|
| 113 |
-
"Nationality": "•••", "Passport Number": "•••",
|
| 114 |
-
"Passport Expiry (dd/mm/yyyy)": "•••", "Passport Issued Country": "•••"
|
| 115 |
-
})
|
| 116 |
-
else:
|
| 117 |
-
placeholder_data.append({
|
| 118 |
-
'source_file': p['file_name'], 'surname': '•••', 'given_names': '•••',
|
| 119 |
-
'passport_number': '•••', 'nationality': '•••', 'date_of_birth': '•••',
|
| 120 |
-
'sex': '•••', 'expiration_date': '•••', 'personal_number': '•••',
|
| 121 |
-
'mrz_found': False
|
| 122 |
-
})
|
| 123 |
-
|
| 124 |
-
if placeholder_data:
|
| 125 |
-
df = pd.concat([df, pd.DataFrame(placeholder_data)], ignore_index=True)
|
| 126 |
-
|
| 127 |
-
temp_dir = tempfile.gettempdir()
|
| 128 |
-
csv_path = os.path.join(temp_dir, f"passport_data_{airline.lower().replace(' ', '_')}.csv")
|
| 129 |
-
excel_path = os.path.join(temp_dir, f"passport_data_{airline.lower().replace(' ', '_')}.xlsx")
|
| 130 |
-
|
| 131 |
-
df.to_csv(csv_path, index=False)
|
| 132 |
-
df.to_excel(excel_path, index=False)
|
| 133 |
-
|
| 134 |
-
status_msg = f"✅ Successfully processed {len(good_results)} passports."
|
| 135 |
-
if problematic_files:
|
| 136 |
-
status_msg += f" ⚠️ {len(problematic_files)} files had issues."
|
| 137 |
-
|
| 138 |
-
return df, csv_path, excel_path, status_msg
|
| 139 |
-
|
| 140 |
-
# Gradio Interface
|
| 141 |
-
with gr.Blocks(title="Passport OCR Extractor") as demo:
|
| 142 |
-
gr.Markdown("# 🛂 Passport OCR Extractor")
|
| 143 |
-
gr.Markdown("Upload passport images or PDFs to extract data into structured formats.")
|
| 144 |
-
|
| 145 |
-
with gr.Row():
|
| 146 |
-
with gr.Column(scale=1):
|
| 147 |
-
files_input = gr.File(label="Upload Passport Files", file_count="multiple", file_types=[".png", ".jpg", ".jpeg", ".pdf", ".webp"])
|
| 148 |
-
airline_input = gr.Dropdown(choices=["Default", "Fly Dubai", "Iraqi", "Fly Baghdad"], value="Default", label="Choose Airline Format")
|
| 149 |
-
include_all_checkbox = gr.Checkbox(label="Include all files in export", info="Show placeholders for missing/invalid data")
|
| 150 |
-
process_btn = gr.Button("Extract Data", variant="primary")
|
| 151 |
-
|
| 152 |
-
with gr.Column(scale=2):
|
| 153 |
-
status_output = gr.Markdown("Status: Ready")
|
| 154 |
-
dataframe_output = gr.Dataframe(label="Extracted Data")
|
| 155 |
-
with gr.Row():
|
| 156 |
-
csv_output = gr.File(label="Download CSV")
|
| 157 |
-
excel_output = gr.File(label="Download Excel")
|
| 158 |
-
|
| 159 |
-
process_btn.click(
|
| 160 |
-
fn=process_passports,
|
| 161 |
-
inputs=[files_input, airline_input, include_all_checkbox],
|
| 162 |
-
outputs=[dataframe_output, csv_output, excel_output, status_output]
|
| 163 |
-
)
|
| 164 |
-
|
| 165 |
-
gr.Markdown("""
|
| 166 |
-
### ℹ️ Instructions
|
| 167 |
-
1. Upload one or more passport images or PDF files.
|
| 168 |
-
2. Select the desired airline format from the dropdown.
|
| 169 |
-
3. Click 'Extract Data' to start the OCR process.
|
| 170 |
-
4. View the results in the table and download them as CSV or Excel files.
|
| 171 |
-
""")
|
| 172 |
-
|
| 173 |
-
if __name__ == "__main__":
|
| 174 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|