ParulPandey commited on
Commit
b283532
·
verified ·
1 Parent(s): 60c3564

Upload 2 files

Browse files
Files changed (2) hide show
  1. app2.py +790 -0
  2. requirements.txt +12 -0
app2.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import platform
3
+ import re
4
+ import os
5
+ import json
6
+ import time
7
+ import hashlib
8
+ import pickle
9
+ import warnings
10
+ import gradio as gr
11
+ import pandas as pd
12
+ import torch
13
+ from transformers import AutoProcessor, AutoModelForImageTextToText, TextStreamer
14
+ from PIL import Image
15
+ import torchaudio
16
+ import numpy as np
17
+ import soundfile as sf
18
+ from dotenv import load_dotenv
19
+ import psutil
20
+ import gc
21
+ import tempfile
22
+ import requests
23
+ from huggingface_hub import HfApi
24
+
25
+ # --- Configuration ---
26
+ GEMMA_MODEL_ID = "google/gemma-3n-E4B-it"
27
+ CACHE_FILE = "image_cache.pkl"
28
+ AUDIO_CACHE_FILE = "audio_cache.pkl"
29
+
30
+ # --- Cache Loading ---
31
+ def load_cache(file_path):
32
+ """Loads a cache file if it exists, otherwise returns an empty dictionary."""
33
+ if os.path.exists(file_path):
34
+ try:
35
+ with open(file_path, "rb") as f:
36
+ return pickle.load(f)
37
+ except Exception as e:
38
+ # Keep this print as it's an important warning about a failed operation.
39
+ print(f"[Cache] Could not load cache from {file_path}: {e}")
40
+ return {}
41
+
42
+ image_cache = load_cache(CACHE_FILE)
43
+ audio_cache = load_cache(AUDIO_CACHE_FILE)
44
+
45
+ # --- Hugging Face Token & Network Check ---
46
+ load_dotenv()
47
+ hf_token = os.getenv("HF_TOKEN")
48
+ if not hf_token:
49
+ warnings.warn("HF_TOKEN not found in .env file. This may cause issues if models aren't cached.")
50
+
51
+ def check_network_connectivity():
52
+ """Checks for a connection to Hugging Face servers."""
53
+ try:
54
+ requests.get("https://huggingface.co", timeout=5)
55
+ return True
56
+ except requests.ConnectionError:
57
+ return False
58
+
59
+ # --- Global Model Variables ---
60
+ processor = None
61
+ model = None
62
+ device = torch.device("cpu")
63
+
64
+ def load_model_with_fallback():
65
+ """Loads the Gemma model, handling offline mode and caching."""
66
+ global processor, model, device
67
+
68
+ if model and model != "cached": return True
69
+
70
+ print("Loading model on CPU...")
71
+ cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
72
+ model_cache_path = os.path.join(cache_dir, f"models--{GEMMA_MODEL_ID.replace('/', '--')}")
73
+
74
+ is_cached = os.path.exists(model_cache_path)
75
+ has_network = check_network_connectivity()
76
+ use_offline = is_cached and not has_network
77
+
78
+ if use_offline:
79
+ print("Network unavailable. Using offline mode with cached model.")
80
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
81
+
82
+ try:
83
+ processor = AutoProcessor.from_pretrained(GEMMA_MODEL_ID, token=hf_token, local_files_only=use_offline)
84
+ model = AutoModelForImageTextToText.from_pretrained(
85
+ GEMMA_MODEL_ID,
86
+ torch_dtype=torch.float32,
87
+ low_cpu_mem_usage=True,
88
+ token=hf_token,
89
+ local_files_only=use_offline
90
+ ).to(device).eval()
91
+ print(f"Gemma model loaded successfully.")
92
+ return True
93
+ except Exception as e:
94
+ print(f"CRITICAL: Model loading failed: {e}", file=sys.stderr)
95
+ return False
96
+
97
+
98
+ # --- Utility Functions ---
99
+ class TokenStreamHandler(TextStreamer):
100
+ """A silent streamer that updates a Gradio progress bar."""
101
+ def __init__(self, tokenizer, progress_callback=None):
102
+ super().__init__(tokenizer)
103
+ self.progress_callback = progress_callback
104
+ self.tokens_generated = 0
105
+
106
+ def put(self, value):
107
+ super().put(value)
108
+ self.tokens_generated += 1
109
+ if self.progress_callback:
110
+ progress_estimate = min(0.5 + (self.tokens_generated / 200) * 0.4, 0.9)
111
+ self.progress_callback(progress_estimate)
112
+
113
+ def on_finalized_text(self, text: str, stream_end: bool = False):
114
+ if stream_end and self.progress_callback:
115
+ self.progress_callback(0.95)
116
+
117
+ def get_image_hash(image_path):
118
+ if not image_path or not os.path.exists(image_path): return None
119
+ with open(image_path, "rb") as f: return hashlib.md5(f.read()).hexdigest()
120
+
121
+ def get_audio_hash(audio_data):
122
+ if isinstance(audio_data, tuple) and len(audio_data) == 2:
123
+ sr, audio_np_array = audio_data
124
+ return hashlib.md5(audio_np_array.tobytes() + str(sr).encode()).hexdigest()
125
+ return None
126
+
127
+ def save_to_csv(data, csv_path="output/forms.csv"):
128
+ """Saves form data to a CSV file in long format."""
129
+ try:
130
+ os.makedirs(os.path.dirname(csv_path), exist_ok=True)
131
+ rows_to_save = [
132
+ {"Timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "Field_Name": field, "Field_Value": value}
133
+ for field, value in data.items()
134
+ ]
135
+
136
+ df = pd.DataFrame(rows_to_save)
137
+ header = not os.path.exists(csv_path)
138
+ df.to_csv(csv_path, mode="a", header=header, index=False)
139
+ # Keep this print as it confirms a critical user action succeeded.
140
+ print(f"[CSV] Data for {len(rows_to_save)} fields saved to {csv_path}")
141
+ except Exception as e:
142
+ raise gr.Error(f"Failed to save to CSV: {e}")
143
+
144
+ # =============================================================================
145
+ # CORE AI PROCESSING FUNCTIONS - Main business logic for form field extraction
146
+ # =============================================================================
147
+
148
+ def extract_fields_from_image(image_path, progress=None):
149
+ """
150
+ Main extraction function - Extracts form field labels from images using Gemma 3n 4B
151
+
152
+ This is the core AI function that:
153
+ 1. Loads and preprocesses form images (photos of paper forms)
154
+ 2. Uses Google's Gemma 3n vision-language model to identify field labels
155
+ 3. Parses the AI output to extract clean field names
156
+ 4. Caches results to avoid re-processing the same image
157
+
158
+ Args:
159
+ image_path (str): Path to uploaded form image
160
+ progress (callable): Gradio progress callback for UI updates
161
+
162
+ Returns:
163
+ list: Clean list of extracted field names (e.g., ["Name", "Age", "Village"])
164
+
165
+ Performance: 30-60 seconds on CPU for 4B model
166
+ """
167
+ global model, processor, device
168
+ start_time = time.time()
169
+
170
+ # Console logging for monitoring AI processing pipeline
171
+ print(f"\n{'='*60}")
172
+ print(f"[EXTRACTION START] Processing: {os.path.basename(image_path) if image_path else 'None'}")
173
+ print(f"[EXTRACTION START] Timestamp: {time.strftime('%H:%M:%S')}")
174
+ print(f"[EXTRACTION START] Using Gemma 3n 4B Vision-Language Model")
175
+ print(f"{'='*60}")
176
+
177
+ # Lazy loading: Load model only when first needed
178
+ if model == "cached":
179
+ print("[Model] Loading Gemma 3n 4B model on first use...")
180
+ if not load_model_with_fallback():
181
+ return ["[Error] Failed to load model on first use."]
182
+
183
+ if progress:
184
+ progress(0.05, desc="Starting image processing...")
185
+ print("[Status] AI extraction pipeline initialized")
186
+
187
+ # Smart caching: Check if we've processed this exact image before
188
+ print("[Cache] Checking for previously processed results...")
189
+ image_hash = get_image_hash(image_path)
190
+ print(f"[Cache] Image hash: {image_hash[:12] if image_hash else 'None'}...")
191
+
192
+ if image_hash in image_cache:
193
+ cached_fields = image_cache[image_hash]
194
+ elapsed = time.time() - start_time
195
+ print(f"[Cache] CACHE HIT! Found {len(cached_fields)} pre-extracted fields in {elapsed:.2f}s")
196
+ print(f"[Cache] Cached fields: {cached_fields}")
197
+ if progress:
198
+ for p in [0.3, 0.6, 0.9, 1.0]:
199
+ progress(p, desc="Using cached results...")
200
+ time.sleep(0.05)
201
+ return cached_fields
202
+
203
+ print("[Cache] New image detected - proceeding with fresh extraction...")
204
+
205
+ # Image preprocessing: Load and validate the uploaded form image
206
+ print("[Image] Loading and validating uploaded form...")
207
+ try:
208
+ image = Image.open(image_path).convert("RGB")
209
+ print(f"[Image] Successfully loaded! Original dimensions: {image.size}")
210
+ except Exception as e:
211
+ print(f"[Image] Failed to load image: {e}")
212
+ return []
213
+
214
+ if progress:
215
+ progress(0.15, desc="Optimizing image for processing...")
216
+
217
+ # Smart resizing: Balance quality vs speed for CPU processing
218
+ original_size = image.size
219
+ max_size = 512 # Optimized for 4B model on CPU
220
+ if image.width > max_size or image.height > max_size:
221
+ print(f"[Image] Resizing from {image.size} to fit {max_size}px...")
222
+ image.thumbnail((max_size, max_size), Image.Resampling.BICUBIC)
223
+ print(f"[Image] Optimized to: {image.size}")
224
+ else:
225
+ print(f"[Image] Size acceptable, keeping: {image.size}")
226
+
227
+ if progress:
228
+ progress(0.25, desc="Preparing prompt...")
229
+
230
+ # Prompt engineering: Carefully crafted prompt for multilingual form extraction
231
+ prompt = "<image_soft_token> Extract all form field labels from this image. Return ONLY a JSON object where keys are field names and values are 'text'. For Hindi/Devanagari forms, preserve the original script. Do NOT include any introductory or concluding text."
232
+ print(f"[Prompt] Using engineered prompt: {prompt[:80]}...")
233
+
234
+ if progress:
235
+ progress(0.35, desc="Tokenizing inputs...")
236
+
237
+ # Tokenization: Convert image and text to model input format
238
+ print("[Tokenizer] Converting image and text to neural network format...")
239
+ tokenize_start = time.time()
240
+ inputs = processor(images=image, text=prompt, return_tensors="pt")
241
+ inputs = {k: v.to(model.device) if hasattr(v, 'to') else v for k, v in inputs.items()}
242
+ tokenize_time = time.time() - tokenize_start
243
+ print(f"[Tokenizer] Tokenization completed in {tokenize_time:.2f}s")
244
+ print(f"[Tokenizer] Input shapes: {', '.join([f'{k}: {v.shape}' for k, v in inputs.items() if hasattr(v, 'shape')])}")
245
+
246
+ if progress:
247
+ progress(0.50, desc="Running AI model (CPU processing)...")
248
+
249
+ # Model inference: Run Gemma 3n 4B on the form image
250
+ print("[Model] Starting Gemma 3n 4B inference...")
251
+ print("[Model] CPU Processing: Expected time 30-60 seconds")
252
+ generation_start = time.time()
253
+
254
+ with torch.no_grad():
255
+ outputs = model.generate(
256
+ **inputs,
257
+ max_new_tokens=128, # Optimized for CPU speed
258
+ do_sample=False, # Deterministic output
259
+ num_beams=1, # Single beam for efficiency
260
+ temperature=0.1, # Low temperature for consistency
261
+ repetition_penalty=1.1, # Prevent repetition
262
+ length_penalty=1.0,
263
+ early_stopping=True,
264
+ pad_token_id=processor.tokenizer.eos_token_id
265
+ )
266
+
267
+ generation_time = time.time() - generation_start
268
+ print(f"[Model] Inference complete! Processing time: {generation_time:.2f}s")
269
+
270
+ # Output decoding: Convert model output back to readable text
271
+ print("[Decoder] Converting model output to text...")
272
+ decode_start = time.time()
273
+ text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
274
+ decode_time = time.time() - decode_start
275
+ print(f"[Decoder] Decoding completed in {decode_time:.3f}s")
276
+ print(f"[Output] Raw AI response preview: {text[:200]}...")
277
+
278
+ # JSON parsing: Extract structured field names from AI response
279
+ print("[Parser] Analyzing AI response for field data...")
280
+ fields = []
281
+ json_match = re.search(r"{.*}", text, re.DOTALL)
282
+ json_str = None
283
+
284
+ if json_match:
285
+ json_str = json_match.group(0)
286
+ print(f"[Parser] Found JSON structure: {json_str[:100]}...")
287
+ try:
288
+ parsed_json = json.loads(json_str)
289
+ print(f"[Parser] JSON parsed successfully, {len(parsed_json)} field definitions found")
290
+
291
+ # Handle nested JSON structures
292
+ def flatten_json(json_obj):
293
+ """Recursively flatten JSON to extract field names"""
294
+ flat = {}
295
+ for k, v in json_obj.items():
296
+ if isinstance(v, dict) and "type" in v:
297
+ flat[k] = v["type"]
298
+ elif isinstance(v, dict):
299
+ flat.update(flatten_json(v))
300
+ else:
301
+ flat[k] = v
302
+ return flat
303
+
304
+ flat_json = flatten_json(parsed_json)
305
+ fields = list(flat_json.keys())
306
+ print(f"[Parser] Extracted {len(fields)} fields: {fields}")
307
+ except Exception as e:
308
+ print(f"[Parser] JSON parsing failed: {e}")
309
+ else:
310
+ print("[Parser] No JSON structure detected in output")
311
+
312
+ # Fallback extraction: Use regex patterns if JSON parsing fails
313
+ if not fields:
314
+ print("[Fallback] Using regex-based field extraction...")
315
+ lines = [line.strip() for line in text.split('\n') if line.strip()]
316
+ numbered_pattern = re.compile(r'^\s*(\d+)[\.|\)]?\s*(.+?)(?:\s*[::](.*))?$')
317
+ fallback_fields = []
318
+
319
+ for i, line in enumerate(lines):
320
+ # Skip instructional text from AI
321
+ if "extract" in line.lower() or "json" in line.lower() or "example" in line.lower():
322
+ continue
323
+
324
+ field_name = None
325
+ match = numbered_pattern.match(line)
326
+ if match:
327
+ raw_field = match.group(2).strip()
328
+ field_name = raw_field.rstrip('::')
329
+ elif ":" in line:
330
+ field_name = line.split(":", 1)[0].strip()
331
+
332
+ # Quality filter for reasonable field names
333
+ if field_name and 2 < len(field_name) < 50:
334
+ fallback_fields.append(field_name)
335
+ print(f"[Fallback] Line {i+1}: '{line}' -> '{field_name}'")
336
+
337
+ fields = fallback_fields
338
+ print(f"[Fallback] Extracted {len(fields)} fields using pattern matching")
339
+
340
+ # Final processing: Clean up results
341
+ clean_fields = [f.strip() for f in fields if f.strip()]
342
+ total_time = time.time() - start_time
343
+
344
+ # Results summary
345
+ print(f"\n[RESULT] Successfully extracted {len(clean_fields)} form fields:")
346
+ for i, field in enumerate(clean_fields, 1):
347
+ print(f"[RESULT] {i}. {field}")
348
+
349
+ # Cache results for future use
350
+ if image_hash and clean_fields:
351
+ print(f"[Cache] Saving {len(clean_fields)} extracted fields to cache...")
352
+ image_cache[image_hash] = clean_fields
353
+ with open(CACHE_FILE, "wb") as f:
354
+ pickle.dump(image_cache, f)
355
+ print("[Cache] Results cached successfully")
356
+
357
+ # Performance summary
358
+ print(f"\n{'='*60}")
359
+ print(f"[EXTRACTION COMPLETE] Total time: {total_time:.2f}s")
360
+ print(f"[EXTRACTION COMPLETE] Status: {'SUCCESS' if len(clean_fields) > 0 else 'NO FIELDS FOUND'}")
361
+ print(f"[EXTRACTION COMPLETE] Ready for digital form filling")
362
+ print(f"{'='*60}\n")
363
+
364
+ if progress:
365
+ progress(1.0, desc="Extraction complete")
366
+ return clean_fields
367
+
368
+ def transcribe_audio(audio_data, progress=gr.Progress()):
369
+ """Fast audio transcription using Gemma for STT with caching"""
370
+ global model, processor, device, audio_cache
371
+ if progress:
372
+ progress(0.05, desc="Starting audio transcription...")
373
+ audio_hash = get_audio_hash(audio_data)
374
+ if audio_hash and audio_hash in audio_cache:
375
+ cached_result = audio_cache[audio_hash]
376
+ if progress:
377
+ progress(1.0, desc="Transcription complete!")
378
+ return cached_result
379
+ if model == "cached":
380
+ if not load_model_with_fallback():
381
+ return "[Error] Failed to load Gemma model on first use."
382
+ if model is None or processor is None:
383
+ return "[Error] Gemma model or processor not loaded properly."
384
+ if audio_data is None:
385
+ return "[Error] No audio provided."
386
+ # manage_memory() # Uncomment if you have a manage_memory function
387
+ audio_np_array, sr = (None, None)
388
+ if isinstance(audio_data, str):
389
+ audio_np_array, sr = sf.read(audio_data)
390
+ elif isinstance(audio_data, tuple) and len(audio_data) == 2:
391
+ sr, audio_np_array = audio_data
392
+ else:
393
+ return "[Error] Invalid audio input format."
394
+ if audio_np_array is None or len(audio_np_array) == 0:
395
+ return "[Error] Empty audio data."
396
+ if audio_np_array.ndim > 1:
397
+ audio_np_array = np.mean(audio_np_array, axis=1)
398
+ if np.max(np.abs(audio_np_array)) > 0:
399
+ audio_np_array = audio_np_array / (np.max(np.abs(audio_np_array)) + 1e-9)
400
+ target_sr = 16000
401
+ if sr != target_sr:
402
+ ratio = target_sr / sr
403
+ new_length = int(len(audio_np_array) * ratio)
404
+ audio_np_array = np.interp(
405
+ np.linspace(0, len(audio_np_array), new_length),
406
+ np.arange(len(audio_np_array)),
407
+ audio_np_array
408
+ )
409
+ sr = target_sr
410
+ prompt = "Transcribe this audio in Hindi (Devanagari script)."
411
+ messages = [
412
+ {
413
+ "role": "user",
414
+ "content": [
415
+ {"type": "audio", "audio": audio_np_array},
416
+ {"type": "text", "text": prompt}
417
+ ]
418
+ }
419
+ ]
420
+ if progress:
421
+ progress(0.2, desc="Tokenizing audio and prompt...")
422
+ input_dict = processor.apply_chat_template(
423
+ messages,
424
+ add_generation_prompt=True,
425
+ tokenize=True,
426
+ return_dict=True,
427
+ return_tensors="pt",
428
+ sampling_rate=sr
429
+ )
430
+ final_inputs_for_model = {k: v.to(model.device) for k, v in input_dict.items()}
431
+ if progress:
432
+ progress(0.6, desc="Generating transcription...")
433
+ with torch.inference_mode():
434
+ predicted_ids = model.generate(
435
+ **final_inputs_for_model,
436
+ max_new_tokens=32, # Lowered for faster short-form transcription
437
+ do_sample=False,
438
+ num_beams=1
439
+ )
440
+ if progress:
441
+ progress(0.9, desc="Decoding transcription...")
442
+ transcription = processor.batch_decode(
443
+ predicted_ids,
444
+ skip_special_tokens=True
445
+ )[0].strip()
446
+ # Remove any 'user:' or 'model:' tokens anywhere in the output
447
+ transcription = re.sub(r'\b(user|model)\s*[::\-]+', '', transcription, flags=re.IGNORECASE)
448
+ # Remove standalone 'user' or 'model' words (with or without surrounding whitespace)
449
+ transcription = re.sub(r'\b(user|model)\b', '', transcription, flags=re.IGNORECASE)
450
+ # Remove the prompt text anywhere in the output (not just at the start)
451
+ prompt_text = "Transcribe this audio in Hindi (Devanagari script)."
452
+ transcription = transcription.replace(prompt_text, '')
453
+ # Remove extra whitespace and leading/trailing punctuation
454
+ transcription = transcription.strip(' :\n\t-')
455
+ if not transcription or transcription.strip() == "":
456
+ transcription = "Audio not clear."
457
+ if audio_hash and transcription:
458
+ audio_cache[audio_hash] = transcription
459
+ with open(AUDIO_CACHE_FILE, "wb") as f:
460
+ pickle.dump(audio_cache, f)
461
+ if progress:
462
+ progress(1.0, desc="Transcription complete!")
463
+ return transcription
464
+
465
+ # --- Gradio UI ---
466
+ def main_ui():
467
+ """Builds the main Gradio user interface."""
468
+
469
+ with gr.Blocks(theme=gr.themes.Soft(), css="""
470
+ /* Apple-like system font stack */
471
+ .gradio-container {
472
+ font-family: -apple-system, BlinkMacSystemFont, 'San Francisco', 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
473
+ background: #fff !important; /* white background */
474
+ }
475
+ .skyblue-btn button {
476
+ background: #87ceeb !important;
477
+ color: #1565c0 !important;
478
+ border: none !important;
479
+ font-weight: 600 !important;
480
+ transition: background 0.2s;
481
+ }
482
+ .skyblue-btn button:disabled {
483
+ background: #b3e5fc !important;
484
+ color: #90a4ae !important;
485
+ }
486
+ .skyblue-btn button:hover:not(:disabled) {
487
+ background: #4fc3f7 !important;
488
+ color: #0d47a1 !important;
489
+ }
490
+ .asha-title {
491
+ font-family: -apple-system, BlinkMacSystemFont, 'San Francisco', 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
492
+ font-size: 2.2rem;
493
+ font-weight: 700;
494
+ color: #1565c0; /* deeper skyblue for title */
495
+ letter-spacing: 0.5px;
496
+ margin-bottom: 0.5em;
497
+ text-align: center;
498
+ }
499
+ .asha-subtitle {
500
+ font-family: -apple-system, BlinkMacSystemFont, 'San Francisco', 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
501
+ font-size: 1.2rem;
502
+ color: #1976d2;
503
+ margin-bottom: 1.2em;
504
+ text-align: center;
505
+ }
506
+ .asha-section { background: #e3f2fd; border-radius: 14px; box-shadow: 0 2px 12px #b3e5fc; padding: 2.2em 2em 1.5em 2em; margin-bottom: 1.5em; }
507
+ .asha-list { font-size: 1.08rem; color: #263238; margin-bottom: 1.2em; }
508
+ .asha-list li { margin-bottom: 0.5em; }
509
+ .asha-note { color: #01579b; font-size: 1.05rem; font-style: italic; margin-top: 1em; }
510
+ .tab-disabled { opacity: 0.5 !important; pointer-events: none !important; }
511
+ .tab-enabled { opacity: 1 !important; }
512
+ .sample-img { border: 2px solid #b3e5fc; border-radius: 8px; margin: 4px; max-width: 120px; cursor: pointer; transition: border 0.2s; }
513
+ .sample-img:hover { border: 2px solid #0288d1; }
514
+ .cancel-audio-x {
515
+ display: inline-block;
516
+ color: #d32f2f;
517
+ font-size: 1.3em;
518
+ font-weight: bold;
519
+ cursor: pointer;
520
+ margin-left: 0.5em;
521
+ vertical-align: middle;
522
+ user-select: none;
523
+ transition: color 0.2s;
524
+ }
525
+ .cancel-audio-x:hover {
526
+ color: #b71c1c;
527
+ }
528
+ /* Icon-style button for cancel audio */
529
+ .cancel-audio-x-btn button {
530
+ background: transparent !important;
531
+ border: none !important;
532
+ box-shadow: none !important;
533
+ color: #d32f2f !important;
534
+ font-size: 1.3em !important;
535
+ font-weight: bold !important;
536
+ padding: 0 0.3em !important;
537
+ margin-left: 0.5em !important;
538
+ vertical-align: middle !important;
539
+ cursor: pointer !important;
540
+ min-width: 1.7em !important;
541
+ min-height: 1.7em !important;
542
+ border-radius: 50% !important;
543
+ transition: color 0.2s !important;
544
+ }
545
+ .cancel-audio-x-btn button:hover {
546
+ color: #b71c1c !important;
547
+ background: #fbe9e7 !important;
548
+ }
549
+ """) as demo:
550
+ fields_state = gr.State([])
551
+ extraction_in_progress = gr.State(False)
552
+ MAX_FIELDS = 15
553
+
554
+ # --- Tab Gating State ---
555
+ image_uploaded = gr.State(False)
556
+ fields_extracted = gr.State(False)
557
+
558
+ # --- Tab UI ---
559
+ with gr.Tabs() as tabs:
560
+ # --- About Tab ---
561
+ with gr.TabItem("1. About & Demo Info", id=0):
562
+ with gr.Column(elem_classes=["asha-section"]):
563
+ gr.Markdown(
564
+ """
565
+ <div class='asha-title'>ASHA Form Digitizer & Hindi Voice Transcriber</div>
566
+ <div class='asha-subtitle'>
567
+ <b>Digitizing rural health, empowering ASHA workers with AI.</b>
568
+ </div>
569
+ <p style='font-size:1.08rem; color:#263238; margin-bottom:1.2em;'>
570
+ This application is designed to help <b>ASHA (Accredited Social Health Activist) workers</b>—the backbone of India's rural healthcare system—quickly digitize handwritten forms and transcribe Hindi voice input. ASHA workers are often the first point of contact for healthcare in villages, but their work is slowed by manual paperwork and language barriers. This tool streamlines their workflow, making data entry faster, more accurate, and accessible even for those more comfortable with Hindi speech than typing.
571
+ </p>
572
+ <ul class='asha-list'>
573
+ <li><b>Image-based field extraction:</b> Upload a photo of an ASHA form and the app will automatically detect and extract all field labels, ready for digital entry.</li>
574
+ <li><b>Hindi voice transcription:</b> Fill any field by speaking in Hindi (Devanagari script) for instant, accurate transcription.</li>
575
+ <li><b>Data export:</b> All submitted data is saved in a CSV for further use or analysis.</li>
576
+ </ul>
577
+ <div class='asha-note'>
578
+ <b>Why this matters:</b> ASHA workers serve over 900 million people in rural India, often with limited digital literacy and resources. By making form digitization and voice transcription seamless, this app saves time, reduces errors, and helps bring rural health data into the digital age—empowering both workers and the communities they serve.
579
+ </div>
580
+ <div class='asha-note' style='color:#1a237e; font-size:1.05rem; margin-top:0.5em;'>
581
+ <b>Note</b> While you are reading this, the <b>Gemma 3n model</b> is being loaded in the background to ensure a smooth and fast demo experience. Please explore each step—the workflow is strictly gated for demo clarity. All features are designed for real-world usability and hackathon evaluation.
582
+ </div>
583
+ """,
584
+ elem_id="asha_about"
585
+ )
586
+ model_status = gr.Textbox(value="Loading model in background...", interactive=False, show_label=False, visible=True)
587
+
588
+ # --- Upload Tab ---
589
+ with gr.TabItem("2. Upload Image | छवि अपलोड करें", id=1):
590
+ with gr.Row():
591
+ with gr.Column(scale=2):
592
+ image_input = gr.Image(type="filepath", label="Upload Form Image | फॉर्म की छवि अपलोड करें", height=350, sources=["upload"]) # Only allow file upload
593
+ with gr.Row():
594
+ extract_btn = gr.Button("Extract Fields | फ़ील्ड निकालें", variant="secondary", elem_classes=["skyblue-btn"])
595
+ gr.Markdown("**Or try a sample image | या नमूना छवि आज़माएँ:**", elem_id="sample-image-label")
596
+ with gr.Row():
597
+ sample_gallery = gr.Gallery(
598
+ value=[
599
+
600
+ "samples/sample_form_2.png",
601
+
602
+ ],
603
+ label=None,
604
+ show_label=False,
605
+ elem_id="sample-gallery",
606
+ height=110,
607
+ columns=[3],
608
+ object_fit="contain",
609
+ allow_preview=True,
610
+ interactive=True,
611
+ elem_classes=["sample-img"]
612
+ )
613
+ # Removed status_box column
614
+
615
+ # --- Fill Form Tab ---
616
+ with gr.TabItem("3. Fill Form | फॉर्म भरें", id=2):
617
+ form_placeholder = gr.Markdown("""Please extract fields from Step 2 first |कृपया पहले चरण 2 से फ़ील्ड निकालें।""", visible=True)
618
+ with gr.Column(visible=False) as form_container:
619
+ text_inputs, audio_inputs, field_rows = [], [], []
620
+ for i in range(MAX_FIELDS):
621
+ with gr.Row(visible=False) as row:
622
+ text_input = gr.Textbox(interactive=True, label="Enter value | मान दर्ज करें")
623
+ audio_input = gr.Audio(sources=["microphone"], type="numpy", label="🎤 Speak to fill | बोलें और भरें", streaming=False)
624
+ text_inputs.append(text_input)
625
+ audio_inputs.append(audio_input)
626
+ field_rows.append(row)
627
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=text_input, show_progress="full")
628
+
629
+ with gr.Row(visible=False) as action_row:
630
+ submit_btn = gr.Button("Submit Form | फॉर्म सबमिट करें", variant="primary")
631
+ new_form_btn = gr.Button("Start New Form | नया फॉर्म शुरू करें")
632
+ # If you have a record_again_btn, add cancel_previous=True to its click event as well
633
+ # Example:
634
+ # record_again_btn.click(fn=on_record_again, inputs=[], outputs=[text_input, record_again_btn], cancel_previous=True)
635
+ # Removed cancel_x buttons and their logic
636
+
637
+ # --- Model Preload on App Start (Tab 1) ---
638
+ def preload_model():
639
+ ok = load_model_with_fallback()
640
+ return gr.update(value="Model loaded and ready!" if ok else "Model failed to load. Please check setup.")
641
+
642
+ # Schedule model loading as soon as the app starts (Tab 1 is shown)
643
+ demo.load(fn=preload_model, inputs=None, outputs=model_status, queue=False)
644
+
645
+ # --- UI Callback Functions ---
646
+ def clear_cache_and_reset():
647
+ global image_cache, audio_cache
648
+ image_cache.clear()
649
+ audio_cache.clear()
650
+ if os.path.exists(CACHE_FILE): os.remove(CACHE_FILE)
651
+ if os.path.exists(AUDIO_CACHE_FILE): os.remove(AUDIO_CACHE_FILE)
652
+ return "All caches cleared successfully!"
653
+
654
+ def on_sample_click(evt: gr.SelectData):
655
+ # evt.value can be a dict or a string path
656
+ value = evt.value
657
+ if isinstance(value, dict) and "image" in value and "path" in value["image"]:
658
+ value = value["image"]["path"]
659
+ return gr.update(value=value), True
660
+
661
+ # Dynamically determine the number of outputs for extract_btn
662
+ extract_outputs = [extract_btn, form_placeholder, form_container, fields_state, action_row, extraction_in_progress] + field_rows + text_inputs
663
+ N = len(extract_outputs)
664
+ def on_extract(img_path):
665
+ def fill_outputs(updates):
666
+ if len(updates) < N:
667
+ updates += [gr.update()] * (N - len(updates))
668
+ return updates[:N]
669
+
670
+ print(f"[on_extract] Called with img_path: {img_path}")
671
+ if not img_path:
672
+ print("[on_extract] No image path provided.")
673
+ yield fill_outputs([
674
+ gr.update(value="Please upload an image first. | कृपया पहले छवि अपल��ड करें।", interactive=True, variant="secondary"),
675
+ gr.update(visible=False),
676
+ gr.update(visible=True),
677
+ gr.update(),
678
+ gr.update(visible=True),
679
+ False # extraction_in_progress
680
+ ])
681
+ return
682
+ # Set extraction_in_progress True
683
+ yield fill_outputs([
684
+ gr.update(value="Extracting... | निकाल रहे हैं...", interactive=False, variant="secondary", elem_classes=["skyblue-btn"]),
685
+ gr.update(visible=False),
686
+ gr.update(visible=True),
687
+ gr.update(),
688
+ gr.update(visible=True),
689
+ True # extraction_in_progress
690
+ ])
691
+ try:
692
+ fields = extract_fields_from_image(img_path)
693
+ print(f"[on_extract] extract_fields_from_image returned: {fields}")
694
+ except gr.Error as e:
695
+ print(f"[on_extract] Exception during extraction: {e}")
696
+ yield fill_outputs([
697
+ gr.update(value=str(e), interactive=True, variant="stop"),
698
+ gr.update(visible=False),
699
+ gr.update(visible=True),
700
+ gr.update(),
701
+ gr.update(visible=True),
702
+ False # extraction_in_progress
703
+ ])
704
+ return
705
+
706
+ if not fields:
707
+ print("[on_extract] No fields found after extraction.")
708
+ yield fill_outputs([
709
+ gr.update(value="No fields found. | कोई फ़ील्ड नहीं मिली।", interactive=True, variant="stop"),
710
+ gr.update(visible=False),
711
+ gr.update(visible=True),
712
+ gr.update(),
713
+ gr.update(visible=True),
714
+ False # extraction_in_progress
715
+ ])
716
+ return
717
+
718
+ num_fields = min(len(fields), MAX_FIELDS)
719
+ print(f"[on_extract] num_fields to show: {num_fields}")
720
+ row_updates = [gr.update(visible=i < num_fields) for i in range(MAX_FIELDS)]
721
+ text_updates = [gr.update(label=fields[i] if i < num_fields else "") for i in range(MAX_FIELDS)]
722
+ result = [
723
+ gr.update(value=f"Extracted! | निकाला गया!", interactive=False, variant="secondary", elem_classes=["skyblue-btn"]),
724
+ gr.update(visible=False),
725
+ gr.update(visible=True),
726
+ gr.State(fields),
727
+ gr.update(visible=True),
728
+ False # extraction_in_progress
729
+ ] + row_updates + text_updates
730
+ print(f"[on_extract] Yielding result with {len(result)} outputs.")
731
+ yield fill_outputs(result)
732
+
733
+ def submit_form(*values):
734
+ fields = values[-1]
735
+ text_values = values[:MAX_FIELDS]
736
+ # If fields is a gr.State, get its value
737
+ if hasattr(fields, 'value'):
738
+ fields = fields.value
739
+ if not fields:
740
+ return gr.update(value="Error: No fields to submit.", variant="stop", interactive=False), gr.update(visible=True)
741
+ data = dict(zip(fields, text_values[:len(fields)]))
742
+ try:
743
+ save_to_csv(data)
744
+ return gr.update(value="Submitted! | सबमिट हो गया", variant="success", interactive=False), gr.update(visible=True)
745
+ except gr.Error as e:
746
+ return gr.update(value=str(e), variant="stop", interactive=False), gr.update(visible=True)
747
+
748
+ # --- Start New Form Logic ---
749
+ def start_new_form():
750
+ # Reset all form fields and UI state
751
+ return [
752
+ gr.update(value="", interactive=True, variant="secondary"), # status box
753
+ gr.update(visible=True), # form_placeholder
754
+ gr.update(visible=False), # form_container
755
+ gr.State([]), # fields_state
756
+ gr.update(visible=False), # action_row
757
+ False, # extraction_in_progress
758
+ ] + [gr.update(visible=False) for _ in range(MAX_FIELDS)] + [gr.update(value="", label="") for _ in range(MAX_FIELDS)]
759
+
760
+ # --- Button/Callback Wiring ---
761
+ sample_gallery.select(fn=on_sample_click, inputs=None, outputs=[image_input, image_uploaded])
762
+ extract_btn.click(
763
+ fn=on_extract,
764
+ inputs=image_input,
765
+ outputs=extract_outputs,
766
+ show_progress="full",
767
+ concurrency_limit=1
768
+ )
769
+ submit_btn.click(
770
+ fn=submit_form,
771
+ inputs=text_inputs + [fields_state],
772
+ outputs=[submit_btn, action_row],
773
+ show_progress="full",
774
+ concurrency_limit=1
775
+ )
776
+ new_form_btn.click(
777
+ fn=start_new_form,
778
+ inputs=None,
779
+ outputs=extract_outputs,
780
+ concurrency_limit=1
781
+ )
782
+ # Optionally, add a button to clear cache
783
+ # clear_cache_btn.click(fn=clear_cache_and_reset, inputs=None, outputs=status_box)
784
+
785
+ return demo
786
+
787
+ # --- App Launch Block ---
788
+ if __name__ == "__main__":
789
+ ui = main_ui()
790
+ ui.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For standalone audio recording
2
+ sounddevice
3
+ torch>=2.4.0
4
+ transformers>=4.53.0
5
+ gradio
6
+ pandas
7
+ pillow
8
+ opencv-python # Included as per your request
9
+ soundfile
10
+ librosa
11
+ python-dotenv
12
+ torchaudio