Spaces:
Runtime error
Runtime error
Fix Greek OCR and update Latin OCR model
Browse filesFiles changed (9)
290 unmodified lines291292293294295296297290 unmodified linesresponse_data["validation"] = {"quality_score": validation.get('quality_score', 0.0),"latin_ratio": validation.get('latin_ratio', 0.0),"trocr_used": validation.get('tridis_used', False) or (validation.get('ocr_method') in ['trocr-base-latin', 'tridis_HTR']),"char_analysis": processed_result.get('char_analysis', {}),"ocr_method": validation.get('ocr_method', 'standard_latin_ocr'),"writing_style": validation.get('writing_style', 'cursive')290 unmodified lines291292293294295296297290 unmodified linesresponse_data["validation"] = {"quality_score": validation.get('quality_score', 0.0),"latin_ratio": validation.get('latin_ratio', 0.0),"trocr_used": validation.get('tridis_used', False) or any(m in validation.get('ocr_method', '') for m in ['tridis', 'trocr-base-printed']),"char_analysis": processed_result.get('char_analysis', {}),"ocr_method": validation.get('ocr_method', 'standard_latin_ocr'),"writing_style": validation.get('writing_style', 'cursive')
9 unmodified lines101112131415169 unmodified linesTESSDATA_PREFIX = os.getenv("TESSDATA_PREFIX")REFERENCES_PATH = BASE_DIR / "references.json"ANCIENT_GREEK_TESSDATA = BASE_DIR / "tessdata" / "ancient-greek"GROQ_API_KEY = os.getenv("GROQ_API_KEY")9 unmodified lines1011121314159 unmodified linesTESSDATA_PREFIX = os.getenv("TESSDATA_PREFIX")REFERENCES_PATH = BASE_DIR / "references.json"GROQ_API_KEY = os.getenv("GROQ_API_KEY")
24 unmodified lines25262728293031323334359 unmodified lines454647484950515224 unmodified linestry:_t0 = time.time()print(f"[CLIP LAZY] Step 1/4 — Loading CLIPModel: {model_name}...", flush=True)self.model = CLIPModel.from_pretrained(model_name)print(f"[CLIP LAZY] Step 2/4 — CLIPModel loaded in {time.time()-_t0:.1f}s. Loading CLIPProcessor...", flush=True)_t1 = time.time()self.processor = CLIPProcessor.from_pretrained(model_name)print(f"[CLIP LAZY] Step 3/4 — CLIPProcessor loaded in {time.time()-_t1:.1f}s. Moving to {self.device}...", flush=True)_t2 = time.time()9 unmodified linestry:_t0 = time.time()print(f"[CLIP LAZY] Fallback 1/2 — Loading: {fallback_name}...", flush=True)self.model = CLIPModel.from_pretrained(fallback_name)self.processor = CLIPProcessor.from_pretrained(fallback_name)print(f"[CLIP LAZY] Fallback 2/2 — Moving to {self.device}...", flush=True)self.model.to(self.device)24 unmodified lines252627282930313233343536379 unmodified lines4748495051525354555624 unmodified linestry:_t0 = time.time()print(f"[CLIP LAZY] Step 1/4 — Loading CLIPModel: {model_name}...", flush=True)import osHF_TOKEN = os.getenv("HF_TOKEN")self.model = CLIPModel.from_pretrained(model_name, token=HF_TOKEN)print(f"[CLIP LAZY] Step 2/4 — CLIPModel loaded in {time.time()-_t0:.1f}s. Loading CLIPProcessor...", flush=True)_t1 = time.time()self.processor = CLIPProcessor.from_pretrained(model_name, token=HF_TOKEN)print(f"[CLIP LAZY] Step 3/4 — CLIPProcessor loaded in {time.time()-_t1:.1f}s. Moving to {self.device}...", flush=True)_t2 = time.time()9 unmodified linestry:_t0 = time.time()print(f"[CLIP LAZY] Fallback 1/2 — Loading: {fallback_name}...", flush=True)import osHF_TOKEN = os.getenv("HF_TOKEN")self.model = CLIPModel.from_pretrained(fallback_name, token=HF_TOKEN)self.processor = CLIPProcessor.from_pretrained(fallback_name, token=HF_TOKEN)print(f"[CLIP LAZY] Fallback 2/2 — Moving to {self.device}...", flush=True)self.model.to(self.device)
16 unmodified lines171819202122232416 unmodified linesmodel_name = getattr(self.config, 'HF_TRANSLATOR_MODEL', 'AnushS/Hieroglyph-Translator-Using-Gardiner-Codes')try:print(f"[INFO] Lazily loading Hugging Face translation model on CPU: {model_name}...")self._tokenizer = AutoTokenizer.from_pretrained(model_name)self._model = AutoModelForSeq2SeqLM.from_pretrained(model_name)self._model.to(self.device)self._model.eval()log_model_device("Egyptian T5 Translator", self.device)16 unmodified lines1718192021222324252616 unmodified linesmodel_name = getattr(self.config, 'HF_TRANSLATOR_MODEL', 'AnushS/Hieroglyph-Translator-Using-Gardiner-Codes')try:print(f"[INFO] Lazily loading Hugging Face translation model on CPU: {model_name}...")import osHF_TOKEN = os.getenv("HF_TOKEN")self._tokenizer = AutoTokenizer.from_pretrained(model_name, token=HF_TOKEN)self._model = AutoModelForSeq2SeqLM.from_pretrained(model_name, token=HF_TOKEN)self._model.to(self.device)self._model.eval()log_model_device("Egyptian T5 Translator", self.device)
47 unmodified lines484950515253545546 unmodified lines10210310410510610710810911011111211311447 unmodified lines# Use a powerful CLIP model for better ancient script understandingmodel_name = "openai/clip-vit-large-patch14"self.clip_processor = CLIPProcessor.from_pretrained(model_name)self.clip_model = CLIPModel.from_pretrained(model_name)self.clip_model.to(self.device)self.clip_model.eval() # Put in evaluation mode46 unmodified linesprint("[INFO] Lazily loading praeclarum cuneiform translation model...")self.cuneiform_tokenizer = AutoTokenizer.from_pretrained("praeclarum/cuneiform",cache_dir=CUNEIFORM_MODEL_DIR)self.cuneiform_model = AutoModelForSeq2SeqLM.from_pretrained("praeclarum/cuneiform",cache_dir=CUNEIFORM_MODEL_DIR)self.cuneiform_model.to(self.device)self.cuneiform_model.eval() # Put in evaluation mode47 unmodified lines4849505152535455565746 unmodified lines10410510610710810911011111211311411511611711811912047 unmodified lines# Use a powerful CLIP model for better ancient script understandingmodel_name = "openai/clip-vit-large-patch14"import osHF_TOKEN = os.getenv("HF_TOKEN")self.clip_processor = CLIPProcessor.from_pretrained(model_name, token=HF_TOKEN)self.clip_model = CLIPModel.from_pretrained(model_name, token=HF_TOKEN)self.clip_model.to(self.device)self.clip_model.eval() # Put in evaluation mode46 unmodified linesprint("[INFO] Lazily loading praeclarum cuneiform translation model...")import osHF_TOKEN = os.getenv("HF_TOKEN")self.cuneiform_tokenizer = AutoTokenizer.from_pretrained("praeclarum/cuneiform",cache_dir=CUNEIFORM_MODEL_DIR,token=HF_TOKEN)self.cuneiform_model = AutoModelForSeq2SeqLM.from_pretrained("praeclarum/cuneiform",cache_dir=CUNEIFORM_MODEL_DIR,token=HF_TOKEN)self.cuneiform_model.to(self.device)self.cuneiform_model.eval() # Put in evaluation mode
35 unmodified lines36373839404142434445464748495010 unmodified lines616263646566676869707172737475767778798081828384858651 unmodified lines13813914014114214314414586 unmodified lines2322332342352362372382392402412422432442452462472485 unmodified lines25425525625725825926026126226326426526626726826927027127227327427512 unmodified lines28828929029129229329429529629729829930030124 unmodified lines32632732832933033133233335 unmodified linesfrom transformers import TrOCRProcessor, VisionEncoderDecoderModelimport torchself.trocr_processor = TrOCRProcessor.from_pretrained('rithwikn/trocr_greek_combined',cache_dir=GREEK_TROCR_MODEL_DIR,local_files_only=False)self.trocr_model = VisionEncoderDecoderModel.from_pretrained('rithwikn/trocr_greek_combined',cache_dir=GREEK_TROCR_MODEL_DIR,local_files_only=False)self.trocr_model.to(self.device)10 unmodified linesself.trocr_available = Falsedef setup_ancient_greek_ocr(self):"""Setup Ancient Greek OCR with specialized tessdata"""# Path to Ancient Greek tessdata (download from ancientgreekocr.org)self.ancient_greek_tessdata = os.path.join(os.path.dirname(__file__),"..", "tessdata", "ancient-greek")# Verify tessdata existsif os.path.exists(self.ancient_greek_tessdata):print(f"[INFO] Ancient Greek tessdata found: {self.ancient_greek_tessdata}")else:print(f"[WARN] Ancient Greek tessdata not found at: {self.ancient_greek_tessdata}")print("[INFO] Download from: https://ancientgreekocr.org")def detect_script(self, image_path):"""Simplified detection - Groq Vision handles main classification"""try:if not getattr(self, 'trocr_available', False):# Check if Ancient Greek OCR is available as fallbackgrc_file = os.path.join(self.ancient_greek_tessdata, "grc.traineddata")if not os.path.exists(grc_file):print("[INFO] Greek processor not available (neither TrOCR nor Tesseract)")return False, 0.551 unmodified linesprint("[WARN] TrOCR extraction returned poor quality result, trying Tesseract fallback...")# Method 2: Ancient Greek OCR (if available and safe)grc_file = os.path.join(self.ancient_greek_tessdata, "grc.traineddata")if os.path.exists(grc_file):ancient_greek_text = self._extract_with_ancient_greek_ocr(image)if ancient_greek_text and self._validate_greek_text(ancient_greek_text):print("[INFO] Using Ancient Greek OCR result")86 unmodified linesdef _extract_with_ancient_greek_ocr(self, image):"""Extract using specialized Ancient Greek OCR"""try:# Save original tessdata pathoriginal_tessdata = os.environ.get("TESSDATA_PREFIX", "")# Set tessdata path properly (fix the path format)if os.path.exists(self.ancient_greek_tessdata):# Ensure proper path format without trailing quotesclean_path = str(self.ancient_greek_tessdata).replace('"', '')os.environ["TESSDATA_PREFIX"] = clean_pathprint(f"[INFO] Set TESSDATA_PREFIX to: {clean_path}")else:print(f"[WARN] Ancient Greek tessdata not found at: {self.ancient_greek_tessdata}")return ""# Use ancient Greek language code 'grc' with optimized settings5 unmodified lineslang="grc", # Ancient Greek language codeconfig=config)# Restore original tessdata pathif original_tessdata:os.environ["TESSDATA_PREFIX"] = original_tessdataelse:# Remove the environment variable if it wasn't set beforeif "TESSDATA_PREFIX" in os.environ:del os.environ["TESSDATA_PREFIX"]return text.strip()except Exception as e:print(f"[WARN] Ancient Greek OCR failed: {e}")# Make sure to restore tessdata path even on errorif 'original_tessdata' in locals() and original_tessdata:os.environ["TESSDATA_PREFIX"] = original_tessdatareturn ""def _extract_layout_aware_ocr(self, image_path):12 unmodified linesline_texts = []# Try to use Ancient Greek firstgrc_file = os.path.join(self.ancient_greek_tessdata, "grc.traineddata")use_grc = os.path.exists(grc_file)# Save original TESSDATA_PREFIXoriginal_tessdata = os.environ.get("TESSDATA_PREFIX", "")if use_grc:clean_path = str(self.ancient_greek_tessdata).replace('"', '')os.environ["TESSDATA_PREFIX"] = clean_pathtry:for idx, crop in enumerate(crops):24 unmodified linesif text:line_texts.append(text)finally:if use_grc and original_tessdata:os.environ["TESSDATA_PREFIX"] = original_tessdatareturn "\n".join(line_texts)except Exception as e:35 unmodified lines3637383940414243444546474849505152535410 unmodified lines656667686970717273747576777879808182838485868751 unmodified lines13914014114214314414586 unmodified lines2322332342352362372385 unmodified lines24424524624724824925025125225312 unmodified lines26626726826927027127224 unmodified lines29729829930030130230335 unmodified linesfrom transformers import TrOCRProcessor, VisionEncoderDecoderModelimport torchimport osHF_TOKEN = os.getenv("HF_TOKEN")self.trocr_processor = TrOCRProcessor.from_pretrained('rithwikn/trocr_greek_combined',cache_dir=GREEK_TROCR_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_model = VisionEncoderDecoderModel.from_pretrained('rithwikn/trocr_greek_combined',cache_dir=GREEK_TROCR_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_model.to(self.device)10 unmodified linesself.trocr_available = Falsedef setup_ancient_greek_ocr(self):"""Setup Ancient Greek OCR with Tesseract language check"""try:langs = pytesseract.get_languages(config='')self.grc_available = "grc" in langsif self.grc_available:print("[INFO] Ancient Greek Tesseract language pack 'grc' is available")else:print("[WARN] Ancient Greek Tesseract language pack 'grc' is NOT available")except Exception as e:print(f"[ERROR] Failed to check Tesseract languages: {e}")self.grc_available = Falsedef detect_script(self, image_path):"""Simplified detection - Groq Vision handles main classification"""try:if not getattr(self, 'trocr_available', False):# Check if Ancient Greek OCR is available as fallbackif not getattr(self, 'grc_available', False):print("[INFO] Greek processor not available (neither TrOCR nor Tesseract)")return False, 0.551 unmodified linesprint("[WARN] TrOCR extraction returned poor quality result, trying Tesseract fallback...")# Method 2: Ancient Greek OCR (if available and safe)if getattr(self, 'grc_available', False):ancient_greek_text = self._extract_with_ancient_greek_ocr(image)if ancient_greek_text and self._validate_greek_text(ancient_greek_text):print("[INFO] Using Ancient Greek OCR result")86 unmodified linesdef _extract_with_ancient_greek_ocr(self, image):"""Extract using specialized Ancient Greek OCR"""try:if not getattr(self, 'grc_available', False):return ""# Use ancient Greek language code 'grc' with optimized settings5 unmodified lineslang="grc", # Ancient Greek language codeconfig=config)return text.strip()except Exception as e:print(f"[WARN] Ancient Greek OCR failed: {e}")return ""def _extract_layout_aware_ocr(self, image_path):12 unmodified linesline_texts = []# Try to use Ancient Greek firstuse_grc = getattr(self, 'grc_available', False)try:for idx, crop in enumerate(crops):24 unmodified linesif text:line_texts.append(text)finally:passreturn "\n".join(line_texts)except Exception as e:
45 unmodified lines46474849505152535455565758596013 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171182 unmodified lines12112212312412512612783 unmodified lines21121221321421521621724 unmodified lines24224324424524624724845 unmodified linesprint("[INFO] This model specializes in 13th-16th century manuscripts with automatic abbreviation expansion")# TRIDIS model from Hugging Face - runs locally after downloadself.tridis_processor = TrOCRProcessor.from_pretrained('magistermilitum/tridis_HTR',cache_dir=TRIDIS_MODEL_DIR,local_files_only=False # Download first time, then cache locally)self.tridis_model = VisionEncoderDecoderModel.from_pretrained('magistermilitum/tridis_HTR',cache_dir=TRIDIS_MODEL_DIR,local_files_only=False)self.tridis_model.to(self.device)13 unmodified linesself.tridis_available = Falsedef setup_trocr_base_latin(self):"""Setup trocr-base-latin model - BEST for printed or carved classical Latin"""try:from utils.gpu_diagnostics import reclaim_vram_forreclaim_vram_for("latin")print("[INFO] Lazily loading trocr-base-latin model for printed/carved Latin...")self.trocr_latin_processor = TrOCRProcessor.from_pretrained('magistermilitum/trocr-base-latin',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False)self.trocr_latin_model = VisionEncoderDecoderModel.from_pretrained('magistermilitum/trocr-base-latin',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False)self.trocr_latin_model.to(self.device)self.trocr_latin_model.eval() # Put in evaluation modefrom utils.gpu_diagnostics import log_model_devicelog_model_device("Latin TrOCR (Printed)", self.device)self.trocr_latin_available = Trueprint(f"[INFO] trocr-base-latin loaded successfully on {self.device}")except Exception as e:print(f"[WARN] magistermilitum/trocr-base-latin model failed to load ({e}). Trying public fallback 'microsoft/trocr-base-printed'...")try:# Free VRAM again in case partial allocation left residuereclaim_vram_for("latin")self.trocr_latin_processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-printed',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False)self.trocr_latin_model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-printed',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False)self.trocr_latin_model.to(self.device)self.trocr_latin_model.eval() # Put in evaluation mode2 unmodified lineslog_model_device("Latin TrOCR (Printed Fallback)", self.device)self.trocr_latin_available = Trueprint(f"[INFO] Public fallback microsoft/trocr-base-printed loaded successfully on {self.device}")except Exception as ex:print(f"[ERROR] All printed Latin models failed to load: {ex}")self.trocr_latin_available = False83 unmodified linesprocessing_time = time.time() - start_timeprint(f"[SUCCESS] Routed to trocr-base-latin and completed in {processing_time:.2f}s")self.active_style = "printed"self.active_model = "trocr-base-latin"return primary_textelse:print("[WARN] trocr-base-latin returned poor quality result, trying TRIDIS HTR fallback...")24 unmodified linesprocessing_time = time.time() - start_timeprint(f"[SUCCESS] Fallback model transcription successful in {processing_time:.2f}s")self.active_style = "printed" if style == "cursive" else "cursive"self.active_model = "trocr-base-latin" if style == "cursive" else "tridis_HTR"return fallback_text# Step 3: Tesseract fallback45 unmodified lines4647484950515253545556575859606162636413 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines13613713813914014114214314414514614783 unmodified lines23123223323423523623724 unmodified lines26226326426526626726845 unmodified linesprint("[INFO] This model specializes in 13th-16th century manuscripts with automatic abbreviation expansion")# TRIDIS model from Hugging Face - runs locally after downloadimport osHF_TOKEN = os.getenv("HF_TOKEN")self.tridis_processor = TrOCRProcessor.from_pretrained('magistermilitum/tridis_HTR',cache_dir=TRIDIS_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.tridis_model = VisionEncoderDecoderModel.from_pretrained('magistermilitum/tridis_HTR',cache_dir=TRIDIS_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.tridis_model.to(self.device)13 unmodified linesself.tridis_available = Falsedef setup_trocr_base_latin(self):"""Setup TRIDIS v2 HTR model - Primary for printed or manuscript Latin, fallback to printed"""import osHF_TOKEN = os.getenv("HF_TOKEN")try:from utils.gpu_diagnostics import reclaim_vram_forreclaim_vram_for("latin")print("[LATIN] Loading TRIDIS v2 model...")self.trocr_latin_processor = TrOCRProcessor.from_pretrained('magistermilitum/tridis_v2_HTR_historical_manuscripts',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_latin_model = VisionEncoderDecoderModel.from_pretrained('magistermilitum/tridis_v2_HTR_historical_manuscripts',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_latin_model.to(self.device)self.trocr_latin_model.eval() # Put in evaluation modefrom utils.gpu_diagnostics import log_model_devicelog_model_device("Latin TRIDIS v2 HTR", self.device)self.trocr_latin_available = Trueself.loaded_printed_model_name = "tridis_v2_HTR_historical_manuscripts"print("[LATIN] TRIDIS v2 model loaded successfully")print(f"processor class: {type(self.trocr_latin_processor).__name__}")print(f"model class: {type(self.trocr_latin_model).__name__}")print(f"device: {self.device}")print(f"parameter count: {sum(p.numel() for p in self.trocr_latin_model.parameters())}")except Exception as e:print(f"[LATIN] TRIDIS unavailable, using microsoft/trocr-base-printed")try:# Free VRAM again in case partial allocation left residuereclaim_vram_for("latin")self.trocr_latin_processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-printed',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_latin_model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-printed',cache_dir=TROCR_LATIN_MODEL_DIR,local_files_only=False,token=HF_TOKEN)self.trocr_latin_model.to(self.device)self.trocr_latin_model.eval() # Put in evaluation mode2 unmodified lineslog_model_device("Latin TrOCR (Printed Fallback)", self.device)self.trocr_latin_available = Trueself.loaded_printed_model_name = "trocr-base-printed"print(f"[INFO] Public fallback microsoft/trocr-base-printed loaded successfully on {self.device}")print(f"processor class: {type(self.trocr_latin_processor).__name__}")print(f"model class: {type(self.trocr_latin_model).__name__}")print(f"device: {self.device}")print(f"parameter count: {sum(p.numel() for p in self.trocr_latin_model.parameters())}")except Exception as ex:print(f"[ERROR] All printed Latin models failed to load: {ex}")self.trocr_latin_available = False83 unmodified linesprocessing_time = time.time() - start_timeprint(f"[SUCCESS] Routed to trocr-base-latin and completed in {processing_time:.2f}s")self.active_style = "printed"self.active_model = getattr(self, "loaded_printed_model_name", "tridis_v2_HTR_historical_manuscripts")return primary_textelse:print("[WARN] trocr-base-latin returned poor quality result, trying TRIDIS HTR fallback...")24 unmodified linesprocessing_time = time.time() - start_timeprint(f"[SUCCESS] Fallback model transcription successful in {processing_time:.2f}s")self.active_style = "printed" if style == "cursive" else "cursive"self.active_model = getattr(self, "loaded_printed_model_name", "tridis_v2_HTR_historical_manuscripts") if style == "cursive" else "tridis_HTR"return fallback_text# Step 3: Tesseract fallback
__pycache__/app.cpython-312.pycDeleted
app.py+1-1
config.py-1
models/__pycache__/clip_classifier.cpython-312.pycDeleted
models/clip_classifier.py+8-4
models/huggingface_models.py+4-2
processors/cuneiform_processor.py+10-4
processors/greek_processor.py+22-52
processors/latin_processor.py+35-15