munajat-api / app.py
Consulawtech's picture
fix: better OCR with VL-72B, debug logging, cleaner error messages
dfafb99
Raw History Blame Contribute Delete
10.5 kB
"""
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 """<html><head><title>Munājāt API</title>
<style>body{font-family:Arial;max-width:700px;margin:60px auto;padding:0 24px;background:#F9F6F0}
h1{color:#1A3D2B}code{background:#F0E8D8;padding:2px 8px;border-radius:4px}
pre{background:#F0E8D8;padding:16px;border-radius:10px;overflow-x:auto}
.gold{color:#C9A84C;font-style:italic}</style></head>
<body><h1>🕌 مناجاة — Munājāt API v2.1</h1>
<p class="gold">"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ" — Quran 2:186</p>
<p>Endpoints: <code>POST /translate</code> · <code>POST /ocr</code> ·
<code>POST /extract-caption</code> · <code>GET /health</code></p>
</body></html>"""
@app.get("/health")
def health():
return {"status": "ok", "model": MODEL_ID, "vision_model": VISION_MODEL}
@app.post("/translate", response_model=TranslationResponse)
def translate(req: TranslationRequest):
if not req.arabic_text.strip():
raise HTTPException(400, "arabic_text is required")
if len(req.arabic_text) > 3000:
raise HTTPException(400, "Too long (max 3000 chars)")
try:
resp = client.chat_completion(
messages=[
{"role": "system", "content": TRANSLATE_SYSTEM},
{"role": "user", "content": (
f"Translate into {req.target_language} with transliteration.\n"
f"Arabic: {req.arabic_text.strip()}\n"
f'JSON only: {{"translation":"...","transliteration":"..."}}'
)},
],
max_tokens=600, temperature=0.2,
)
result = extract_json(resp.choices[0].message.content)
return TranslationResponse(
translation=result.get("translation", ""),
transliteration=result.get("transliteration", ""),
model=MODEL_ID,
)
except ValueError as e:
raise HTTPException(422, str(e))
except Exception as e:
raise HTTPException(500, f"Translation failed: {e}")
@app.post("/ocr", response_model=OcrResponse)
async def ocr(file: UploadFile = File(...)):
"""Extract Arabic dua text from screenshot/image using vision model."""
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(400, "File must be an image (jpg, png, etc.)")
contents = await file.read()
if len(contents) > 10 * 1024 * 1024:
raise HTTPException(400, "Image too large (max 10MB)")
b64 = base64.b64encode(contents).decode("utf-8")
media_type = file.content_type or "image/jpeg"
try:
resp = vision_client.chat_completion(
messages=[{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:{media_type};base64,{b64}"},
},
{"type": "text", "text": OCR_PROMPT},
],
}],
max_tokens=1000,
temperature=0.05,
)
raw = resp.choices[0].message.content
print(f"[OCR] Raw model response: {raw[:500]}")
result = extract_json(raw)
return OcrResponse(
arabic=result.get("arabic", ""),
english=result.get("english", ""),
transliteration=result.get("transliteration", ""),
source=result.get("source", ""),
raw_text=result.get("raw_text", ""),
method="vision",
)
except Exception as e:
print(f"[OCR] Failed: {e}")
raise HTTPException(500, f"OCR failed: {str(e)[:200]}")
@app.post("/extract-caption", response_model=CaptionResponse)
def extract_caption(req: CaptionRequest):
"""Extract structured dua fields from raw caption/social media text."""
if not req.text.strip():
raise HTTPException(400, "text is required")
if len(req.text) > 5000:
raise HTTPException(400, "Too long (max 5000 chars)")
try:
resp = client.chat_completion(
messages=[
{"role": "system", "content": CAPTION_SYSTEM},
{"role": "user", "content": (
f"Extract dua from:\n\n{req.text.strip()}\n\n"
f'JSON only: {{"arabic":"...","english":"...","transliteration":"...","source":"...","has_dua":true/false}}'
)},
],
max_tokens=600, temperature=0.1,
)
result = extract_json(resp.choices[0].message.content)
return CaptionResponse(
arabic=result.get("arabic", ""),
english=result.get("english", ""),
transliteration=result.get("transliteration", ""),
source=result.get("source", ""),
has_dua=result.get("has_dua", False),
)
except ValueError as e:
raise HTTPException(422, str(e))
except Exception as e:
raise HTTPException(500, f"Caption extraction failed: {e}")