natalis3405 commited on
Commit
fe67e79
·
1 Parent(s): 9dd47a2

selection

Browse files
Files changed (1) hide show
  1. app.py +109 -16
app.py CHANGED
@@ -5,6 +5,10 @@ import pytesseract
5
  import re
6
  import json
7
 
 
 
 
 
8
  def clean_ocr_text(raw_text):
9
  """Clean OCR text using regex - only for cleaning, not extraction"""
10
  # Remove extra whitespace and normalize
@@ -21,35 +25,88 @@ def clean_ocr_text(raw_text):
21
 
22
  return cleaned.strip()
23
 
24
- def extract_dl_info(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """
26
  Extracts driver's license information from an image file using OCR and AI model processing.
27
 
28
  Args:
29
  image: PIL Image object from Gradio
 
 
 
30
 
31
  Returns:
32
  tuple: (raw_ocr_text, cleaned_ocr_text, json_result)
33
  """
34
  try:
35
- # Convert Gradio image to RGB
36
- if hasattr(image, 'convert'):
37
- image = image.convert("RGB")
38
-
39
- # Use Tesseract OCR to extract text
40
- print("Extracting text with Tesseract OCR...")
41
- raw_text = pytesseract.image_to_string(image)
42
- print(f"Raw OCR text: {raw_text}")
43
-
44
- # Clean the OCR text using regex (only for cleaning, not extraction)
45
- cleaned_text = clean_ocr_text(raw_text)
46
- print(f"Cleaned OCR text: {cleaned_text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Use AI model to process cleaned OCR text and extract structured information
49
  print("Processing cleaned OCR text with AI model...")
50
 
51
- # Load a text generation pipeline for structured extraction
52
- generator = pipeline("text2text-generation", model="google/flan-t5-base")
 
 
 
 
 
53
 
54
  # Create specific prompts for the AI model to extract individual fields
55
  name_prompt = f"From this driver's license text, what is the person's full name? Text: {cleaned_text} Answer:"
@@ -131,6 +188,32 @@ with gr.Blocks(title="Driver's License Information Extractor") as demo:
131
  type="pil",
132
  height=400
133
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  submit_btn = gr.Button("Extract Information", variant="primary")
135
 
136
  with gr.Column():
@@ -150,9 +233,19 @@ with gr.Blocks(title="Driver's License Information Extractor") as demo:
150
  label="Extracted Information (JSON)"
151
  )
152
 
 
 
 
 
 
 
 
 
 
 
153
  submit_btn.click(
154
  fn=extract_dl_info,
155
- inputs=[image_input],
156
  outputs=[raw_ocr, cleaned_text, json_result]
157
  )
158
 
 
5
  import re
6
  import json
7
 
8
+ # Global variable to store the loaded model
9
+ loaded_generator = None
10
+ current_model = None
11
+
12
  def clean_ocr_text(raw_text):
13
  """Clean OCR text using regex - only for cleaning, not extraction"""
14
  # Remove extra whitespace and normalize
 
25
 
26
  return cleaned.strip()
27
 
28
+ def load_model(model_choice):
29
+ """Load the AI model only when needed"""
30
+ global loaded_generator, current_model
31
+
32
+ model_map = {
33
+ "FLAN-T5 Small (60M)": "google/flan-t5-small",
34
+ "FLAN-T5 Base (220M)": "google/flan-t5-base",
35
+ "FLAN-T5 Large (770M)": "google/flan-t5-large",
36
+ "FLAN-T5 XL (3B)": "google/flan-t5-xl"
37
+ }
38
+
39
+ selected_model = model_map.get(model_choice, "google/flan-t5-base")
40
+
41
+ # Only load if different model is requested
42
+ if current_model != selected_model:
43
+ print(f"Loading model: {selected_model}")
44
+ try:
45
+ loaded_generator = pipeline("text2text-generation", model=selected_model)
46
+ current_model = selected_model
47
+ print(f"Model {selected_model} loaded successfully")
48
+ except Exception as e:
49
+ print(f"Error loading model {selected_model}: {e}")
50
+ # Fallback to base model
51
+ if selected_model != "google/flan-t5-base":
52
+ print("Falling back to base model...")
53
+ loaded_generator = pipeline("text2text-generation", model="google/flan-t5-base")
54
+ current_model = "google/flan-t5-base"
55
+ else:
56
+ raise e
57
+
58
+ return loaded_generator
59
+
60
+ def extract_dl_info(image, model_choice, manual_text, use_manual_text):
61
  """
62
  Extracts driver's license information from an image file using OCR and AI model processing.
63
 
64
  Args:
65
  image: PIL Image object from Gradio
66
+ model_choice: Selected model from radio button
67
+ manual_text: Manual text input from user
68
+ use_manual_text: Boolean to determine if manual text should be used instead of OCR
69
 
70
  Returns:
71
  tuple: (raw_ocr_text, cleaned_ocr_text, json_result)
72
  """
73
  try:
74
+ # Determine text source
75
+ if use_manual_text and manual_text and manual_text.strip():
76
+ # Use manual text input
77
+ print("Using manual text input...")
78
+ raw_text = manual_text.strip()
79
+ cleaned_text = clean_ocr_text(raw_text)
80
+ print(f"Manual text: {raw_text}")
81
+ print(f"Cleaned text: {cleaned_text}")
82
+ else:
83
+ # Use OCR on image
84
+ if image is None:
85
+ return "No image provided", "No image provided", json.dumps({"error": "No image provided"}, indent=2)
86
+
87
+ # Convert Gradio image to RGB
88
+ if hasattr(image, 'convert'):
89
+ image = image.convert("RGB")
90
+
91
+ # Use Tesseract OCR to extract text
92
+ print("Extracting text with Tesseract OCR...")
93
+ raw_text = pytesseract.image_to_string(image)
94
+ print(f"Raw OCR text: {raw_text}")
95
+
96
+ # Clean the OCR text using regex (only for cleaning, not extraction)
97
+ cleaned_text = clean_ocr_text(raw_text)
98
+ print(f"Cleaned OCR text: {cleaned_text}")
99
 
100
  # Use AI model to process cleaned OCR text and extract structured information
101
  print("Processing cleaned OCR text with AI model...")
102
 
103
+ # Load model only when needed
104
+ try:
105
+ generator = load_model(model_choice)
106
+ except Exception as e:
107
+ error_msg = f"Failed to load AI model: {str(e)}"
108
+ print(error_msg)
109
+ return raw_text, cleaned_text, json.dumps({"error": error_msg}, indent=2)
110
 
111
  # Create specific prompts for the AI model to extract individual fields
112
  name_prompt = f"From this driver's license text, what is the person's full name? Text: {cleaned_text} Answer:"
 
188
  type="pil",
189
  height=400
190
  )
191
+
192
+ model_choice = gr.Radio(
193
+ choices=[
194
+ "FLAN-T5 Small (60M)",
195
+ "FLAN-T5 Base (220M)",
196
+ "FLAN-T5 Large (770M)",
197
+ "FLAN-T5 XL (3B)"
198
+ ],
199
+ value="FLAN-T5 Base (220M)",
200
+ label="Select AI Model",
201
+ info="Larger models are more accurate but slower to load and process"
202
+ )
203
+
204
+ use_manual_text = gr.Checkbox(
205
+ label="Use Manual Text Input",
206
+ value=False,
207
+ info="Check this to type text manually instead of using OCR"
208
+ )
209
+
210
+ manual_text_input = gr.Textbox(
211
+ label="Manual Text Input",
212
+ lines=6,
213
+ placeholder="Type or paste the driver's license text here...",
214
+ visible=False
215
+ )
216
+
217
  submit_btn = gr.Button("Extract Information", variant="primary")
218
 
219
  with gr.Column():
 
233
  label="Extracted Information (JSON)"
234
  )
235
 
236
+ # Show/hide manual text input based on checkbox
237
+ def toggle_manual_input(use_manual):
238
+ return gr.update(visible=use_manual)
239
+
240
+ use_manual_text.change(
241
+ fn=toggle_manual_input,
242
+ inputs=[use_manual_text],
243
+ outputs=[manual_text_input]
244
+ )
245
+
246
  submit_btn.click(
247
  fn=extract_dl_info,
248
+ inputs=[image_input, model_choice, manual_text_input, use_manual_text],
249
  outputs=[raw_ocr, cleaned_text, json_result]
250
  )
251