Spaces:
Running
on
L4
Running
on
L4
File size: 16,018 Bytes
41ae0ed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
import gradio as gr
import easyocr
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from transformers import pipeline
import logging
import os
import time
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Check for GPU availability
device = "cuda" if torch.cuda.is_available() else "cpu"
using_gpu = device == "cuda"
logger.info(f"Using device: {device}")
class SmartGlassesSystem:
"""Main class for Police Smart Glasses AI system"""
def __init__(self):
self.initialize_models()
self.supported_languages = {
"Arabic": ["ar", "en"],
"Hindi": ["hi", "en"],
"Chinese": ["ch_sim", "en"],
"Japanese": ["ja", "en"],
"Korean": ["ko", "en"],
"Russian": ["ru", "en"],
"French": ["fr", "en"]
}
# Cache for OCR readers to avoid reloading
self.ocr_readers = {}
def initialize_models(self):
"""Initialize all AI models with proper error handling"""
try:
# Load OCR for most common languages eagerly
logger.info("Loading initial OCR readers...")
self.ocr_readers = {
"Arabic": easyocr.Reader(['ar', 'en'], gpu=using_gpu, verbose=False),
"Hindi": easyocr.Reader(['hi', 'en'], gpu=using_gpu, verbose=False)
}
# Load translation model
logger.info("Loading translation model...")
self.translator = pipeline(
"translation",
model="Helsinki-NLP/opus-mt-mul-en",
device=0 if using_gpu else -1
)
# Check if timm is installed for object detection
try:
import timm
logger.info("Loading object detection model...")
self.detector = pipeline(
"object-detection",
model="facebook/detr-resnet-50",
device=0 if using_gpu else -1
)
except ImportError:
logger.warning("timm library not found, using YOLOv5 as fallback for object detection")
try:
import torch
# Use YOLOv5 as a fallback (it has fewer dependencies)
self.detector = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# Make detector interface compatible with transformers pipeline
self._original_detect = self.detector
self.detector = self._yolo_detector_wrapper
except Exception as e2:
logger.error(f"Fallback object detection also failed: {str(e2)}")
logger.warning("Object detection will be disabled")
self.detector = self._dummy_detector
logger.info("All models loaded successfully!")
except Exception as e:
logger.error(f"Error initializing models: {str(e)}")
raise RuntimeError(f"Failed to initialize AI models: {str(e)}")
def _yolo_detector_wrapper(self, image):
"""Wrapper to make YOLOv5 output compatible with transformers pipeline format"""
results = self._original_detect(image)
detections = []
# Convert YOLOv5 results to transformers pipeline format
for i, (x1, y1, x2, y2, conf, cls) in enumerate(results.xyxy[0]):
detections.append({
'score': float(conf),
'label': results.names[int(cls)],
'box': {
'xmin': int(x1),
'ymin': int(y1),
'xmax': int(x2),
'ymax': int(y2)
}
})
return detections
def _dummy_detector(self, image):
"""Dummy detector when no object detection is available"""
logger.warning("Object detection is disabled due to missing dependencies")
return []
def get_ocr_reader(self, language_choice):
"""Get or create appropriate OCR reader based on language choice"""
if language_choice in self.ocr_readers:
return self.ocr_readers[language_choice]
# Create new reader if not already loaded
if language_choice in self.supported_languages:
logger.info(f"Loading new OCR reader for {language_choice}...")
reader = easyocr.Reader(
self.supported_languages[language_choice],
gpu=using_gpu,
verbose=False
)
# Cache for future use
self.ocr_readers[language_choice] = reader
return reader
else:
# Fallback to general reader
logger.warning(f"Unsupported language: {language_choice}, using default")
if "Other" not in self.ocr_readers:
self.ocr_readers["Other"] = easyocr.Reader(['en', 'fr', 'ru'], gpu=using_gpu, verbose=False)
return self.ocr_readers["Other"]
def extract_text(self, image, language_choice):
"""Extract text from image using OCR"""
start_time = time.time()
reader = self.get_ocr_reader(language_choice)
try:
text_results = reader.readtext(image)
extracted_texts = [res[1] for res in text_results]
extracted_text = " ".join(extracted_texts)
# Get bounding boxes for visualization
text_boxes = [(res[0], res[1]) for res in text_results]
logger.info(f"OCR completed in {time.time() - start_time:.2f} seconds")
return extracted_text, text_boxes
except Exception as e:
logger.error(f"OCR error: {str(e)}")
return "Error during text extraction.", []
def translate_text(self, text):
"""Translate extracted text to English"""
if not text or text == "No text detected." or text.strip() == "":
return "No text to translate."
try:
# Handle long text by breaking it into chunks
max_length = 450 # Safe maximum length to avoid hitting the 512 token limit
if len(text) > max_length:
logger.info(f"Breaking long text ({len(text)} chars) into chunks for translation")
# Split by sentences to maintain context when possible
import re
sentences = re.split(r'(?<=[.!?])\s+', text)
chunks = []
current_chunk = ""
for sentence in sentences:
if len(current_chunk) + len(sentence) < max_length:
current_chunk += " " + sentence if current_chunk else sentence
else:
if current_chunk:
chunks.append(current_chunk)
current_chunk = sentence
if current_chunk:
chunks.append(current_chunk)
# Translate each chunk
translations = []
for chunk in chunks:
try:
chunk_translation = self.translator(chunk, max_length=512)[0]['translation_text']
translations.append(chunk_translation)
except Exception as e:
logger.error(f"Chunk translation error: {str(e)}")
translations.append(f"[Translation error: {str(e)}]")
return " ".join(translations)
else:
# For shorter text, translate directly
return self.translator(text, max_length=512)[0]['translation_text']
except Exception as e:
logger.error(f"Translation error: {str(e)}")
return f"Translation error: {str(e)}"
def detect_objects(self, image_pil):
"""Detect objects in the image"""
try:
# Use a try-except block to handle potential CUDA errors
try:
detections = self.detector(image_pil)
return detections
except RuntimeError as e:
if "CUDA" in str(e):
logger.warning("CUDA error in object detection, trying CPU fallback")
# Try CPU fallback
old_device = None
if hasattr(self.detector, 'device'):
old_device = self.detector.device
self.detector.device = torch.device('cpu')
try:
detections = self.detector(image_pil)
logger.info("CPU fallback for object detection successful")
# Restore original device
if old_device:
self.detector.device = old_device
return detections
except Exception as cpu_error:
logger.error(f"CPU fallback also failed: {str(cpu_error)}")
return []
else:
raise e
except Exception as e:
logger.error(f"Object detection error: {str(e)}")
return []
def visualize_results(self, image, text_boxes, detections):
"""Create visualization with detected objects and text"""
image_draw = image.copy().convert("RGB")
draw = ImageDraw.Draw(image_draw)
# Try to load a better font, fall back to default if necessary
try:
font = ImageFont.truetype("Arial", 12)
except IOError:
font = ImageFont.load_default()
# Draw text bounding boxes
for box, text in text_boxes:
# Convert box points to rectangle coordinates
points = np.array(box).astype(np.int32)
draw.polygon([tuple(p) for p in points], outline="blue", width=2)
# Add small text label
draw.text((points[0][0], points[0][1] - 10), "Text", fill="blue", font=font)
# Draw object detection boxes
for det in detections:
box = det['box']
label = det['label']
score = det['score']
if score > 0.6: # Higher confidence threshold
draw.rectangle(
[box['xmin'], box['ymin'], box['xmax'], box['ymax']],
outline="red",
width=3
)
label_text = f"{label} ({score:.2f})"
draw.text((box['xmin'], box['ymin'] - 15), label_text, fill="red", font=font)
return image_draw
def process_image(self, image, language_choice):
"""Main processing pipeline"""
if image is None:
return (
None,
"No image provided. Please upload an image.",
"No image to process."
)
# Convert to numpy array if needed
if not isinstance(image, np.ndarray):
image = np.array(image)
# Create PIL image for visualization
image_pil = Image.fromarray(image)
# Extract text
try:
extracted_text, text_boxes = self.extract_text(image, language_choice)
except Exception as e:
logger.error(f"Text extraction error: {str(e)}")
extracted_text = f"Error during text extraction: {str(e)}"
text_boxes = []
# Translate text
try:
translation = self.translate_text(extracted_text)
except Exception as e:
logger.error(f"Translation error: {str(e)}")
translation = f"Error during translation: {str(e)}"
# Detect objects - with error recovery
try:
detections = self.detect_objects(image_pil)
except Exception as e:
logger.error(f"Final object detection error: {str(e)}")
detections = []
# Create visualization
try:
result_image = self.visualize_results(image_pil, text_boxes, detections)
except Exception as e:
logger.error(f"Visualization error: {str(e)}")
result_image = image_pil # Return original image if visualization fails
return result_image, extracted_text, translation
# Create system instance
smart_glasses = SmartGlassesSystem()
def create_interface():
"""Create and configure the Gradio interface"""
# Custom CSS for better appearance
custom_css = """
.gradio-container {
background-color: #f0f4f8;
}
.output-image {
border: 2px solid #2c3e50;
border-radius: 5px;
}
"""
# Create interface
with gr.Blocks(css=custom_css, title="π¨ Police Smart Glasses - AI Demo") as iface:
gr.Markdown("""
# π¨ Police Smart Glasses - Advanced AI Demo
This system demonstrates real-time text recognition, translation, and object detection capabilities
for law enforcement smart glasses technology.
### Instructions:
1. Upload an image containing text in the selected language
2. Choose the primary language in the image
3. View the detection results, extracted text, and English translation
""")
with gr.Row():
with gr.Column(scale=1):
# Input components
input_image = gr.Image(
type="pil",
label="Upload an Image (e.g., Signs, Documents, License Plates)"
)
language_choice = gr.Dropdown(
choices=list(smart_glasses.supported_languages.keys()) + ["Other"],
value="Arabic",
label="Select Primary Language in Image"
)
process_btn = gr.Button("Process Image", variant="primary")
with gr.Column(scale=1):
# Output components
output_image = gr.Image(label="Analysis Results")
extracted_text = gr.Textbox(label="Extracted Text")
translated_text = gr.Textbox(label="Translated Text (English)")
# Set up processing function
process_btn.click(
fn=smart_glasses.process_image,
inputs=[input_image, language_choice],
outputs=[output_image, extracted_text, translated_text]
)
# Examples for testing
gr.Examples(
examples=[
["examples/arabic_sign.jpg", "Arabic"],
["examples/hindi_text.jpg", "Hindi"],
["examples/russian_document.jpg", "Russian"]
],
inputs=[input_image, language_choice]
)
# System information
with gr.Accordion("System Information", open=False):
gr.Markdown(f"""
- **Device**: {'GPU' if using_gpu else 'CPU'}
- **Supported Languages**: {', '.join(smart_glasses.supported_languages.keys())}
- **AI Models**:
- OCR: EasyOCR
- Translation: Helsinki-NLP/opus-mt-mul-en
- Object Detection: facebook/detr-resnet-50
""")
return iface
if __name__ == "__main__":
# Create and launch interface
iface = create_interface()
iface.launch(
share=True, # Enable sharing
debug=True # Show debugging information
) |