""" Munājāt — Arabic Dua API v2.1 Fixed OCR: uses Qwen2.5-VL-72B-Instruct (more reliable on free tier) """ import os import re import json import base64 from fastapi import FastAPI, HTTPException, UploadFile, File from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse from pydantic import BaseModel from huggingface_hub import InferenceClient # ── Config ───────────────────────────────────────────────────────────────────── MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-72B-Instruct") VISION_MODEL = os.getenv("VISION_MODEL_ID", "Qwen/Qwen2.5-VL-72B-Instruct") HF_TOKEN = os.getenv("HF_TOKEN", "") client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None) vision_client = InferenceClient(model=VISION_MODEL, token=HF_TOKEN or None) # ── App ──────────────────────────────────────────────────────────────────────── app = FastAPI(title="Munājāt API", version="2.1.0") app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) # ── Prompts ──────────────────────────────────────────────────────────────────── TRANSLATE_SYSTEM = """You are an expert Islamic scholar and Arabic linguist specialising in dua translation. 1. Translate the Arabic dua into the requested language with reverence and accuracy. 2. Provide academic transliteration: ā=alif, ī=ya, ū=waw, dh=ذ, th=ث, gh=غ, kh=خ Respond ONLY with valid JSON — no markdown, no backticks. Format: {"translation": "...", "transliteration": "..."}""" OCR_PROMPT = """You are an expert at reading Arabic Islamic text from images. Carefully examine this image and extract ALL visible text. The image likely contains some combination of: - Arabic dua text (Arabic script, right-to-left) - English translation - Transliteration (Roman alphabet pronunciation) - Source reference (Quran verse, hadith reference) Rules: - Extract Arabic text EXACTLY as written, preserving all diacritics - Extract partial text if fully visible text is not available - Do NOT translate — only extract what is literally visible Respond ONLY with this exact JSON structure: {"arabic": "arabic text here or empty string", "english": "english text here or empty string", "transliteration": "roman text here or empty string", "source": "source reference or empty string", "raw_text": "all extracted text combined"}""" CAPTION_SYSTEM = """You are an expert at extracting Islamic duas from social media captions. Given raw text from Instagram, WhatsApp, Telegram or any app: 1. Find the actual dua/supplication content 2. Separate: Arabic text, English translation, transliteration, source 3. Strip: hashtags, handles, emojis (unless part of dua), promotional text 4. Set has_dua=false if no actual dua is present Respond ONLY with valid JSON: {"arabic": "...", "english": "...", "transliteration": "...", "source": "...", "has_dua": true or false}""" # ── JSON parser ──────────────────────────────────────────────────────────────── def extract_json(text: str) -> dict: text = text.strip() try: return json.loads(text) except Exception: pass cleaned = re.sub(r'```(?:json)?\s*|\s*```', '', text).strip() try: return json.loads(cleaned) except Exception: pass m = re.search(r'\{.*\}', cleaned, re.DOTALL) if m: try: return json.loads(m.group()) except Exception: pass result = {} for field in ['arabic', 'english', 'transliteration', 'source', 'translation', 'raw_text']: fm = re.search(rf'"{field}"\s*:\s*"((?:[^"\\]|\\.)*)"', text) if fm: result[field] = fm.group(1) bm = re.search(r'"has_dua"\s*:\s*(true|false)', text) if bm: result['has_dua'] = bm.group(1) == 'true' if result: return result raise ValueError(f"No JSON found in: {text[:300]}") # ── Pydantic models ──────────────────────────────────────────────────────────── class TranslationRequest(BaseModel): arabic_text: str target_language: str = "english" class TranslationResponse(BaseModel): translation: str transliteration: str model: str class OcrResponse(BaseModel): arabic: str english: str transliteration: str source: str raw_text: str method: str class CaptionRequest(BaseModel): text: str class CaptionResponse(BaseModel): arabic: str english: str transliteration: str source: str has_dua: bool # ── Routes ───────────────────────────────────────────────────────────────────── @app.get("/", response_class=HTMLResponse) def root(): return """
"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ" — Quran 2:186
Endpoints: POST /translate · POST /ocr ·
POST /extract-caption · GET /health