Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files123456731 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485283 unmodified lines369370371372373374375376377378379380381382383384385386387388389390391392393394395396397141 unmodified lines539540541542543544545101 unmodified lines64764864965065165265390 unmodified lines744745746747748749750751752753754755756"""BubbleScribe - AI Manga & Comic TranslatorTranslate manga/comics using GLM-4.6V-Flash for OCR + Translation and LaMa for inpainting.Auto-detects hardware (works on free tier and upgraded spaces)"""import gradio as gr31 unmodified lines# MODEL PRELOADING (Load once at startup, not per-request)# ============================================================# Force CPU mode (no GPU available)os.environ["CUDA_VISIBLE_DEVICES"] = ""import torchtorch.set_default_device('cpu')print("🚀 BubbleScribe starting up...")print(f" CPU Threads: {NUM_CPUS}")print(f" Device: CPU (forced)")# Global LaMa model (loaded once)_lama_model = None_lama_lock = threading.Lock()def get_lama_model():"""Get or initialize LaMa model (singleton pattern) - CPU only."""global _lama_modelif _lama_model is None:with _lama_lock:if _lama_model is None:print("📦 Loading LaMa inpainting model (CPU mode)...")try:from simple_lama_inpainting import SimpleLama_lama_model = SimpleLama(device=torch.device('cpu'))print("✅ LaMa model loaded on CPU!")except TypeError:# Older version without device parametertry:from simple_lama_inpainting import SimpleLama_lama_model = SimpleLama()print("✅ LaMa model loaded!")except Exception as e:print(f"⚠️ LaMa failed to load: {e}")_lama_model = "fallback"except Exception as e:print(f"⚠️ LaMa failed to load: {e}")_lama_model = "fallback"return _lama_model# Preload LaMa at startupprint("📦 Preloading models...")get_lama_model()# ============================================================# FONT CACHING283 unmodified linesreturn maskdef opencv_inpaint(image: Image.Image, mask: Image.Image) -> Image.Image:"""Fast inpainting using OpenCV (multi-threaded)."""img_array = np.array(image.convert('RGB'))mask_array = np.array(mask)# Use TELEA algorithm - faster and good qualityresult = cv2.inpaint(img_array, mask_array, inpaintRadius=5, flags=cv2.INPAINT_TELEA)return Image.fromarray(result)def lama_inpaint(image: Image.Image, mask: Image.Image) -> Image.Image:"""High-quality inpainting using LaMa model."""lama = get_lama_model()if lama == "fallback" or lama is None:return opencv_inpaint(image, mask)try:result = lama(image, mask)return resultexcept Exception as e:print(f"LaMa inpaint failed: {e}, using OpenCV fallback")return opencv_inpaint(image, mask)# ============================================================# TEXT RENDERING (Optimized with word wrapping)# ============================================================141 unmodified linesmask = create_text_mask(image, detections)progress(0.7, desc="✨ Inpainting (removing original text)...")inpainted = lama_inpaint(image, mask)progress(0.9, desc="✍️ Adding translated text...")result = add_translated_text(inpainted, detections)101 unmodified linesgr.HTML("""<div class="stats">⚡ <strong>Models:</strong> GLM-4.6V-Flash (OCR & Translation) + LaMa (Inpainting)</div>""")90 unmodified lines### 🔧 Powered By- **GLM-4.6V-Flash** - Text detection & translation (Z.ai API - Free tier)- **LaMa** - Text removal inpainting""")gr.HTML("""<div style="text-align: center; margin-top: 20px; padding: 10px; background: rgba(0,0,0,0.05); border-radius: 8px;"><strong>Models:</strong> <a href="https://huggingface.co/zai-org/GLM-4.6V" target="_blank">zai-org/GLM-4.6V-Flash</a> (OCR & Translation) •<a href="https://github.com/advimman/lama" target="_blank">LaMa</a> (Inpainting) •<strong>Created by:</strong> <a href="https://huggingface.co/lulavc" target="_blank">@lulavc</a></div>""")123456731 unmodified lines3940414243444546474849283 unmodified lines333334335336337338339340341342343344345346347141 unmodified lines489490491492493494495101 unmodified lines59759859960060160260390 unmodified lines694695696697698699700701702703704705706"""BubbleScribe - AI Manga & Comic TranslatorTranslate manga/comics using GLM-4.6V-Flash for OCR + Translation and OpenCV for inpainting.CPU-optimized (works on free tier and upgraded spaces)"""import gradio as gr31 unmodified lines# MODEL PRELOADING (Load once at startup, not per-request)# ============================================================print("🚀 BubbleScribe starting up...")print(f" CPU Threads: {NUM_CPUS}")print(f" Inpainting: OpenCV (CPU-optimized)")# No LaMa - use OpenCV inpainting (works great on CPU for text removal)# ============================================================# FONT CACHING283 unmodified linesreturn maskdef inpaint_image(image: Image.Image, mask: Image.Image) -> Image.Image:"""Fast inpainting using OpenCV (CPU-optimized, multi-threaded)."""img_array = np.array(image.convert('RGB'))mask_array = np.array(mask)# Use TELEA algorithm - fast and good quality for text removalresult = cv2.inpaint(img_array, mask_array, inpaintRadius=7, flags=cv2.INPAINT_TELEA)return Image.fromarray(result)# ============================================================# TEXT RENDERING (Optimized with word wrapping)# ============================================================141 unmodified linesmask = create_text_mask(image, detections)progress(0.7, desc="✨ Inpainting (removing original text)...")inpainted = inpaint_image(image, mask)progress(0.9, desc="✍️ Adding translated text...")result = add_translated_text(inpainted, detections)101 unmodified linesgr.HTML("""<div class="stats">⚡ <strong>Models:</strong> GLM-4.6V-Flash (OCR & Translation) + OpenCV (Inpainting)</div>""")90 unmodified lines### 🔧 Powered By- **GLM-4.6V-Flash** - Text detection & translation (Z.ai API - Free tier)- **OpenCV** - Text removal inpainting (CPU-optimized)""")gr.HTML("""<div style="text-align: center; margin-top: 20px; padding: 10px; background: rgba(0,0,0,0.05); border-radius: 8px;"><strong>Models:</strong> <a href="https://huggingface.co/zai-org/GLM-4.6V" target="_blank">zai-org/GLM-4.6V-Flash</a> (OCR & Translation) •<a href="https://opencv.org/" target="_blank">OpenCV</a> (Inpainting) •<strong>Created by:</strong> <a href="https://huggingface.co/lulavc" target="_blank">@lulavc</a></div>""")
app.py+13-63