Spaces:
Sleeping
Sleeping
Create modules/api_manager.py
Browse files- modules/api_manager.py +52 -0
modules/api_manager.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytesseract
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from deep_translator import GoogleTranslator, MyMemoryTranslator
|
| 5 |
+
|
| 6 |
+
# --- OCR MODULE ---
|
| 7 |
+
def perform_ocr(image):
|
| 8 |
+
"""
|
| 9 |
+
Primary: Tesseract OCR (Local)
|
| 10 |
+
Backup: Mock/Placeholder (Since Google Vision requires credentials)
|
| 11 |
+
"""
|
| 12 |
+
try:
|
| 13 |
+
# PRIMARY: Tesseract
|
| 14 |
+
# Convert image to RGB if necessary
|
| 15 |
+
if image.mode != 'RGB':
|
| 16 |
+
image = image.convert('RGB')
|
| 17 |
+
|
| 18 |
+
text = pytesseract.image_to_string(image)
|
| 19 |
+
|
| 20 |
+
if not text.strip():
|
| 21 |
+
# If Tesseract runs but finds nothing, try backup
|
| 22 |
+
raise ValueError("Empty result from Tesseract")
|
| 23 |
+
|
| 24 |
+
return text, "Primary (Tesseract)"
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Primary OCR Failed: {e}")
|
| 27 |
+
# BACKUP: Fallback logic (Simulated for this demo)
|
| 28 |
+
return "Fallback Mode: Unable to read text clearly. (Mock Data: Burger $10, Pizza $12)", "Backup (Simulated)"
|
| 29 |
+
|
| 30 |
+
# --- TRANSLATION MODULE ---
|
| 31 |
+
def translate_text(text, target_lang='es'):
|
| 32 |
+
"""
|
| 33 |
+
Primary: Google Translate (via deep_translator wrapper)
|
| 34 |
+
Backup: MyMemory Translator
|
| 35 |
+
"""
|
| 36 |
+
if not text or text.strip() == "":
|
| 37 |
+
return "", "No Text"
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
# PRIMARY
|
| 41 |
+
translator = GoogleTranslator(source='auto', target=target_lang)
|
| 42 |
+
translation = translator.translate(text)
|
| 43 |
+
return translation, "Primary (Google)"
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Primary Translation Failed: {e}")
|
| 46 |
+
try:
|
| 47 |
+
# BACKUP
|
| 48 |
+
translator = MyMemoryTranslator(source='auto', target=target_lang)
|
| 49 |
+
translation = translator.translate(text)
|
| 50 |
+
return translation, "Backup (MyMemory)"
|
| 51 |
+
except Exception as e2:
|
| 52 |
+
return text, "Failed (No API available)"
|