Spaces:
Sleeping
Sleeping
Commit ·
dfafb99
1
Parent(s): 13f1662
fix: better OCR with VL-72B, debug logging, cleaner error messages
Browse files
app.py
CHANGED
|
@@ -1,18 +1,12 @@
|
|
| 1 |
"""
|
| 2 |
-
Munājāt — Arabic Dua API
|
| 3 |
-
|
| 4 |
-
POST /translate → arabic_text → translation + transliteration
|
| 5 |
-
POST /ocr → image file → extracted arabic + english text
|
| 6 |
-
POST /extract-caption → raw text → cleaned dua fields
|
| 7 |
-
GET /health → status
|
| 8 |
-
GET / → test page
|
| 9 |
"""
|
| 10 |
|
| 11 |
import os
|
| 12 |
import re
|
| 13 |
import json
|
| 14 |
import base64
|
| 15 |
-
from io import BytesIO
|
| 16 |
|
| 17 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 18 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -21,111 +15,84 @@ from pydantic import BaseModel
|
|
| 21 |
from huggingface_hub import InferenceClient
|
| 22 |
|
| 23 |
# ── Config ─────────────────────────────────────────────────────────────────────
|
| 24 |
-
MODEL_ID
|
| 25 |
-
|
| 26 |
-
HF_TOKEN
|
| 27 |
|
| 28 |
-
client
|
| 29 |
-
vision_client = InferenceClient(model=
|
| 30 |
|
| 31 |
# ── App ────────────────────────────────────────────────────────────────────────
|
| 32 |
-
app = FastAPI(title="Munājāt API", version="2.
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
CORSMiddleware,
|
| 36 |
-
allow_origins=["*"],
|
| 37 |
-
allow_methods=["*"],
|
| 38 |
-
allow_headers=["*"],
|
| 39 |
-
)
|
| 40 |
|
| 41 |
# ── Prompts ────────────────────────────────────────────────────────────────────
|
| 42 |
-
TRANSLATE_SYSTEM = """You are an expert Islamic scholar and Arabic linguist specialising in dua
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
2. Generate academic transliteration: ā (alif), ī (ya), ū (waw), dh for ذ, th for ث, gh for غ, kh for خ
|
| 47 |
-
|
| 48 |
-
Respond ONLY with valid JSON. No markdown, no explanation, no backticks.
|
| 49 |
Format: {"translation": "...", "transliteration": "..."}"""
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
- English translation
|
| 54 |
-
- Transliteration (Roman script pronunciation)
|
| 55 |
-
- Mixed Arabic/English content from social media posts
|
| 56 |
-
|
| 57 |
-
Extract ALL text you can see. Identify which parts are:
|
| 58 |
-
1. Arabic (عربي) text
|
| 59 |
-
2. English translation
|
| 60 |
-
3. Transliteration (Roman script)
|
| 61 |
-
4. Source/reference (e.g. Quran 2:186, Sahih Bukhari)
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
"source": "extracted source reference or empty string",
|
| 69 |
-
"raw_text": "all extracted text combined"
|
| 70 |
-
}"""
|
| 71 |
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
-
Respond ONLY with valid JSON
|
| 84 |
-
|
| 85 |
-
"arabic": "arabic dua text or empty string",
|
| 86 |
-
"english": "english translation or empty string",
|
| 87 |
-
"transliteration": "transliteration or empty string",
|
| 88 |
-
"source": "source reference or empty string",
|
| 89 |
-
"has_dua": true or false
|
| 90 |
-
}"""
|
| 91 |
|
| 92 |
-
# ── JSON
|
| 93 |
def extract_json(text: str) -> dict:
|
| 94 |
-
|
| 95 |
-
# Try direct parse
|
| 96 |
try:
|
| 97 |
-
return json.loads(text
|
| 98 |
except Exception:
|
| 99 |
pass
|
| 100 |
-
|
| 101 |
-
cleaned = re.sub(r'```json\s*|\s*```', '', text).strip()
|
| 102 |
try:
|
| 103 |
return json.loads(cleaned)
|
| 104 |
except Exception:
|
| 105 |
pass
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
if match:
|
| 109 |
try:
|
| 110 |
-
return json.loads(
|
| 111 |
except Exception:
|
| 112 |
pass
|
| 113 |
-
# Last resort: regex extract individual fields
|
| 114 |
result = {}
|
| 115 |
for field in ['arabic', 'english', 'transliteration', 'source',
|
| 116 |
'translation', 'raw_text']:
|
| 117 |
-
|
| 118 |
-
if
|
| 119 |
-
result[field] =
|
| 120 |
-
|
| 121 |
-
if
|
| 122 |
-
result['has_dua'] =
|
| 123 |
if result:
|
| 124 |
return result
|
| 125 |
-
raise ValueError(f"
|
| 126 |
|
| 127 |
-
|
| 128 |
-
# ── Models ─────────────────────────────────────────────────────────────────────
|
| 129 |
class TranslationRequest(BaseModel):
|
| 130 |
arabic_text: str
|
| 131 |
target_language: str = "english"
|
|
@@ -141,6 +108,7 @@ class OcrResponse(BaseModel):
|
|
| 141 |
transliteration: str
|
| 142 |
source: str
|
| 143 |
raw_text: str
|
|
|
|
| 144 |
|
| 145 |
class CaptionRequest(BaseModel):
|
| 146 |
text: str
|
|
@@ -152,182 +120,117 @@ class CaptionResponse(BaseModel):
|
|
| 152 |
source: str
|
| 153 |
has_dua: bool
|
| 154 |
|
| 155 |
-
|
| 156 |
# ── Routes ─────────────────────────────────────────────────────────────────────
|
| 157 |
|
| 158 |
@app.get("/", response_class=HTMLResponse)
|
| 159 |
def root():
|
| 160 |
-
return """
|
| 161 |
-
<
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
pre{background:#F0E8D8;padding:16px;border-radius:10px;overflow-x:auto;font-size:13px}
|
| 167 |
-
.badge{display:inline-block;background:#1A3D2B;color:#fff;padding:2px 10px;border-radius:12px;font-size:12px;margin-right:6px}
|
| 168 |
-
.gold{color:#C9A84C;font-style:italic}
|
| 169 |
-
table{width:100%;border-collapse:collapse;margin:12px 0}
|
| 170 |
-
td,th{padding:8px 12px;border:1px solid #E2E8F0;text-align:left;font-size:13px}
|
| 171 |
-
th{background:#F0E8D8;font-weight:600}
|
| 172 |
-
</style></head>
|
| 173 |
-
<body>
|
| 174 |
-
<h1>🕌 مناجاة — Munājāt API <span style="font-size:14px;color:#64748B">v2.0</span></h1>
|
| 175 |
<p class="gold">"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ" — Quran 2:186</p>
|
| 176 |
-
|
| 177 |
-
<
|
| 178 |
-
|
| 179 |
-
<tr><td><span class="badge">POST</span></td><td><code>/translate</code></td><td>Arabic → translation + transliteration</td></tr>
|
| 180 |
-
<tr><td><span class="badge">POST</span></td><td><code>/ocr</code></td><td>Image → extract dua text</td></tr>
|
| 181 |
-
<tr><td><span class="badge">POST</span></td><td><code>/extract-caption</code></td><td>Caption/text → clean dua fields</td></tr>
|
| 182 |
-
<tr><td><span class="badge" style="background:#2D6A4F">GET</span></td><td><code>/health</code></td><td>Status check</td></tr>
|
| 183 |
-
</table>
|
| 184 |
-
|
| 185 |
-
<h2>POST /translate</h2>
|
| 186 |
-
<pre>curl -X POST /translate \\
|
| 187 |
-
-H "Content-Type: application/json" \\
|
| 188 |
-
-d '{"arabic_text": "اللَّهُمَّ أَنْتَ رَبِّي", "target_language": "english"}'</pre>
|
| 189 |
-
|
| 190 |
-
<h2>POST /ocr</h2>
|
| 191 |
-
<pre>curl -X POST /ocr \\
|
| 192 |
-
-F "file=@screenshot.jpg"</pre>
|
| 193 |
-
|
| 194 |
-
<h2>POST /extract-caption</h2>
|
| 195 |
-
<pre>curl -X POST /extract-caption \\
|
| 196 |
-
-H "Content-Type: application/json" \\
|
| 197 |
-
-d '{"text": "Bismillah 🤲 اللهم بارك لنا\\n#dua #islam #quran"}'</pre>
|
| 198 |
-
</body></html>
|
| 199 |
-
"""
|
| 200 |
-
|
| 201 |
|
| 202 |
@app.get("/health")
|
| 203 |
def health():
|
| 204 |
-
return {
|
| 205 |
-
"status": "ok",
|
| 206 |
-
"model": MODEL_ID,
|
| 207 |
-
"vision_model": VISION_MODEL_ID,
|
| 208 |
-
}
|
| 209 |
-
|
| 210 |
|
| 211 |
@app.post("/translate", response_model=TranslationResponse)
|
| 212 |
def translate(req: TranslationRequest):
|
| 213 |
-
if not req.arabic_text
|
| 214 |
-
raise HTTPException(
|
| 215 |
if len(req.arabic_text) > 3000:
|
| 216 |
-
raise HTTPException(
|
| 217 |
-
|
| 218 |
try:
|
| 219 |
-
|
| 220 |
messages=[
|
| 221 |
{"role": "system", "content": TRANSLATE_SYSTEM},
|
| 222 |
{"role": "user", "content": (
|
| 223 |
-
f"Translate
|
| 224 |
-
f"
|
| 225 |
-
f
|
| 226 |
-
f'Respond ONLY with JSON: {{"translation": "...", "transliteration": "..."}}'
|
| 227 |
)},
|
| 228 |
],
|
| 229 |
-
max_tokens=600,
|
| 230 |
-
temperature=0.2,
|
| 231 |
)
|
| 232 |
-
|
| 233 |
-
result = extract_json(raw)
|
| 234 |
return TranslationResponse(
|
| 235 |
translation=result.get("translation", ""),
|
| 236 |
transliteration=result.get("transliteration", ""),
|
| 237 |
model=MODEL_ID,
|
| 238 |
)
|
| 239 |
except ValueError as e:
|
| 240 |
-
raise HTTPException(
|
| 241 |
except Exception as e:
|
| 242 |
-
raise HTTPException(
|
| 243 |
-
|
| 244 |
|
| 245 |
@app.post("/ocr", response_model=OcrResponse)
|
| 246 |
async def ocr(file: UploadFile = File(...)):
|
| 247 |
-
"""Extract Arabic dua text from
|
| 248 |
-
# Validate file type
|
| 249 |
if not file.content_type or not file.content_type.startswith("image/"):
|
| 250 |
-
raise HTTPException(
|
| 251 |
|
| 252 |
-
# Read and base64 encode the image
|
| 253 |
contents = await file.read()
|
| 254 |
-
if len(contents) > 10 * 1024 * 1024:
|
| 255 |
-
raise HTTPException(
|
| 256 |
|
| 257 |
b64 = base64.b64encode(contents).decode("utf-8")
|
| 258 |
media_type = file.content_type or "image/jpeg"
|
| 259 |
|
| 260 |
try:
|
| 261 |
-
|
| 262 |
-
messages=[
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
"text": (
|
| 275 |
-
"Extract all text from this image. "
|
| 276 |
-
"Identify Arabic dua text, English translation, "
|
| 277 |
-
"transliteration, and source references.\n\n"
|
| 278 |
-
"Respond ONLY with JSON:\n"
|
| 279 |
-
'{"arabic": "...", "english": "...", '
|
| 280 |
-
'"transliteration": "...", "source": "...", '
|
| 281 |
-
'"raw_text": "..."}'
|
| 282 |
-
),
|
| 283 |
-
},
|
| 284 |
-
],
|
| 285 |
-
}
|
| 286 |
-
],
|
| 287 |
-
max_tokens=800,
|
| 288 |
-
temperature=0.1,
|
| 289 |
)
|
| 290 |
-
raw =
|
|
|
|
| 291 |
result = extract_json(raw)
|
|
|
|
| 292 |
return OcrResponse(
|
| 293 |
arabic=result.get("arabic", ""),
|
| 294 |
english=result.get("english", ""),
|
| 295 |
transliteration=result.get("transliteration", ""),
|
| 296 |
source=result.get("source", ""),
|
| 297 |
raw_text=result.get("raw_text", ""),
|
|
|
|
| 298 |
)
|
| 299 |
-
except ValueError as e:
|
| 300 |
-
raise HTTPException(status_code=422, detail=str(e))
|
| 301 |
except Exception as e:
|
| 302 |
-
|
| 303 |
-
|
| 304 |
|
| 305 |
@app.post("/extract-caption", response_model=CaptionResponse)
|
| 306 |
def extract_caption(req: CaptionRequest):
|
| 307 |
-
"""Extract dua
|
| 308 |
-
if not req.text
|
| 309 |
-
raise HTTPException(
|
| 310 |
if len(req.text) > 5000:
|
| 311 |
-
raise HTTPException(
|
| 312 |
-
|
| 313 |
try:
|
| 314 |
-
|
| 315 |
messages=[
|
| 316 |
{"role": "system", "content": CAPTION_SYSTEM},
|
| 317 |
{"role": "user", "content": (
|
| 318 |
-
f"Extract
|
| 319 |
-
f
|
| 320 |
-
f"Respond ONLY with JSON: "
|
| 321 |
-
f'{{"arabic": "...", "english": "...", '
|
| 322 |
-
f'"transliteration": "...", "source": "...", '
|
| 323 |
-
f'"has_dua": true/false}}'
|
| 324 |
)},
|
| 325 |
],
|
| 326 |
-
max_tokens=600,
|
| 327 |
-
temperature=0.1,
|
| 328 |
)
|
| 329 |
-
|
| 330 |
-
result = extract_json(raw)
|
| 331 |
return CaptionResponse(
|
| 332 |
arabic=result.get("arabic", ""),
|
| 333 |
english=result.get("english", ""),
|
|
@@ -336,6 +239,6 @@ def extract_caption(req: CaptionRequest):
|
|
| 336 |
has_dua=result.get("has_dua", False),
|
| 337 |
)
|
| 338 |
except ValueError as e:
|
| 339 |
-
raise HTTPException(
|
| 340 |
except Exception as e:
|
| 341 |
-
raise HTTPException(
|
|
|
|
| 1 |
"""
|
| 2 |
+
Munājāt — Arabic Dua API v2.1
|
| 3 |
+
Fixed OCR: uses Qwen2.5-VL-72B-Instruct (more reliable on free tier)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
| 7 |
import re
|
| 8 |
import json
|
| 9 |
import base64
|
|
|
|
| 10 |
|
| 11 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 12 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 15 |
from huggingface_hub import InferenceClient
|
| 16 |
|
| 17 |
# ── Config ─────────────────────────────────────────────────────────────────────
|
| 18 |
+
MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-72B-Instruct")
|
| 19 |
+
VISION_MODEL = os.getenv("VISION_MODEL_ID", "Qwen/Qwen2.5-VL-72B-Instruct")
|
| 20 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 21 |
|
| 22 |
+
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None)
|
| 23 |
+
vision_client = InferenceClient(model=VISION_MODEL, token=HF_TOKEN or None)
|
| 24 |
|
| 25 |
# ── App ────────────────────────────────────────────────────────────────────────
|
| 26 |
+
app = FastAPI(title="Munājāt API", version="2.1.0")
|
| 27 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
| 28 |
+
allow_methods=["*"], allow_headers=["*"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
# ── Prompts ────────────────────────────────────────────────────────────────────
|
| 31 |
+
TRANSLATE_SYSTEM = """You are an expert Islamic scholar and Arabic linguist specialising in dua translation.
|
| 32 |
+
1. Translate the Arabic dua into the requested language with reverence and accuracy.
|
| 33 |
+
2. Provide academic transliteration: ā=alif, ī=ya, ū=waw, dh=ذ, th=ث, gh=غ, kh=خ
|
| 34 |
+
Respond ONLY with valid JSON — no markdown, no backticks.
|
|
|
|
|
|
|
|
|
|
| 35 |
Format: {"translation": "...", "transliteration": "..."}"""
|
| 36 |
|
| 37 |
+
OCR_PROMPT = """You are an expert at reading Arabic Islamic text from images.
|
| 38 |
+
Carefully examine this image and extract ALL visible text.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
The image likely contains some combination of:
|
| 41 |
+
- Arabic dua text (Arabic script, right-to-left)
|
| 42 |
+
- English translation
|
| 43 |
+
- Transliteration (Roman alphabet pronunciation)
|
| 44 |
+
- Source reference (Quran verse, hadith reference)
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
Rules:
|
| 47 |
+
- Extract Arabic text EXACTLY as written, preserving all diacritics
|
| 48 |
+
- Extract partial text if fully visible text is not available
|
| 49 |
+
- Do NOT translate — only extract what is literally visible
|
| 50 |
|
| 51 |
+
Respond ONLY with this exact JSON structure:
|
| 52 |
+
{"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"}"""
|
| 53 |
|
| 54 |
+
CAPTION_SYSTEM = """You are an expert at extracting Islamic duas from social media captions.
|
| 55 |
+
Given raw text from Instagram, WhatsApp, Telegram or any app:
|
| 56 |
+
1. Find the actual dua/supplication content
|
| 57 |
+
2. Separate: Arabic text, English translation, transliteration, source
|
| 58 |
+
3. Strip: hashtags, handles, emojis (unless part of dua), promotional text
|
| 59 |
+
4. Set has_dua=false if no actual dua is present
|
| 60 |
|
| 61 |
+
Respond ONLY with valid JSON:
|
| 62 |
+
{"arabic": "...", "english": "...", "transliteration": "...", "source": "...", "has_dua": true or false}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
# ── JSON parser ────────────────────────────────────────────────────────────────
|
| 65 |
def extract_json(text: str) -> dict:
|
| 66 |
+
text = text.strip()
|
|
|
|
| 67 |
try:
|
| 68 |
+
return json.loads(text)
|
| 69 |
except Exception:
|
| 70 |
pass
|
| 71 |
+
cleaned = re.sub(r'```(?:json)?\s*|\s*```', '', text).strip()
|
|
|
|
| 72 |
try:
|
| 73 |
return json.loads(cleaned)
|
| 74 |
except Exception:
|
| 75 |
pass
|
| 76 |
+
m = re.search(r'\{.*\}', cleaned, re.DOTALL)
|
| 77 |
+
if m:
|
|
|
|
| 78 |
try:
|
| 79 |
+
return json.loads(m.group())
|
| 80 |
except Exception:
|
| 81 |
pass
|
|
|
|
| 82 |
result = {}
|
| 83 |
for field in ['arabic', 'english', 'transliteration', 'source',
|
| 84 |
'translation', 'raw_text']:
|
| 85 |
+
fm = re.search(rf'"{field}"\s*:\s*"((?:[^"\\]|\\.)*)"', text)
|
| 86 |
+
if fm:
|
| 87 |
+
result[field] = fm.group(1)
|
| 88 |
+
bm = re.search(r'"has_dua"\s*:\s*(true|false)', text)
|
| 89 |
+
if bm:
|
| 90 |
+
result['has_dua'] = bm.group(1) == 'true'
|
| 91 |
if result:
|
| 92 |
return result
|
| 93 |
+
raise ValueError(f"No JSON found in: {text[:300]}")
|
| 94 |
|
| 95 |
+
# ── Pydantic models ────────────────────────────────────────────────────────────
|
|
|
|
| 96 |
class TranslationRequest(BaseModel):
|
| 97 |
arabic_text: str
|
| 98 |
target_language: str = "english"
|
|
|
|
| 108 |
transliteration: str
|
| 109 |
source: str
|
| 110 |
raw_text: str
|
| 111 |
+
method: str
|
| 112 |
|
| 113 |
class CaptionRequest(BaseModel):
|
| 114 |
text: str
|
|
|
|
| 120 |
source: str
|
| 121 |
has_dua: bool
|
| 122 |
|
|
|
|
| 123 |
# ── Routes ─────────────────────────────────────────────────────────────────────
|
| 124 |
|
| 125 |
@app.get("/", response_class=HTMLResponse)
|
| 126 |
def root():
|
| 127 |
+
return """<html><head><title>Munājāt API</title>
|
| 128 |
+
<style>body{font-family:Arial;max-width:700px;margin:60px auto;padding:0 24px;background:#F9F6F0}
|
| 129 |
+
h1{color:#1A3D2B}code{background:#F0E8D8;padding:2px 8px;border-radius:4px}
|
| 130 |
+
pre{background:#F0E8D8;padding:16px;border-radius:10px;overflow-x:auto}
|
| 131 |
+
.gold{color:#C9A84C;font-style:italic}</style></head>
|
| 132 |
+
<body><h1>🕌 مناجاة — Munājāt API v2.1</h1>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
<p class="gold">"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ" — Quran 2:186</p>
|
| 134 |
+
<p>Endpoints: <code>POST /translate</code> · <code>POST /ocr</code> ·
|
| 135 |
+
<code>POST /extract-caption</code> · <code>GET /health</code></p>
|
| 136 |
+
</body></html>"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
@app.get("/health")
|
| 139 |
def health():
|
| 140 |
+
return {"status": "ok", "model": MODEL_ID, "vision_model": VISION_MODEL}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
@app.post("/translate", response_model=TranslationResponse)
|
| 143 |
def translate(req: TranslationRequest):
|
| 144 |
+
if not req.arabic_text.strip():
|
| 145 |
+
raise HTTPException(400, "arabic_text is required")
|
| 146 |
if len(req.arabic_text) > 3000:
|
| 147 |
+
raise HTTPException(400, "Too long (max 3000 chars)")
|
|
|
|
| 148 |
try:
|
| 149 |
+
resp = client.chat_completion(
|
| 150 |
messages=[
|
| 151 |
{"role": "system", "content": TRANSLATE_SYSTEM},
|
| 152 |
{"role": "user", "content": (
|
| 153 |
+
f"Translate into {req.target_language} with transliteration.\n"
|
| 154 |
+
f"Arabic: {req.arabic_text.strip()}\n"
|
| 155 |
+
f'JSON only: {{"translation":"...","transliteration":"..."}}'
|
|
|
|
| 156 |
)},
|
| 157 |
],
|
| 158 |
+
max_tokens=600, temperature=0.2,
|
|
|
|
| 159 |
)
|
| 160 |
+
result = extract_json(resp.choices[0].message.content)
|
|
|
|
| 161 |
return TranslationResponse(
|
| 162 |
translation=result.get("translation", ""),
|
| 163 |
transliteration=result.get("transliteration", ""),
|
| 164 |
model=MODEL_ID,
|
| 165 |
)
|
| 166 |
except ValueError as e:
|
| 167 |
+
raise HTTPException(422, str(e))
|
| 168 |
except Exception as e:
|
| 169 |
+
raise HTTPException(500, f"Translation failed: {e}")
|
|
|
|
| 170 |
|
| 171 |
@app.post("/ocr", response_model=OcrResponse)
|
| 172 |
async def ocr(file: UploadFile = File(...)):
|
| 173 |
+
"""Extract Arabic dua text from screenshot/image using vision model."""
|
|
|
|
| 174 |
if not file.content_type or not file.content_type.startswith("image/"):
|
| 175 |
+
raise HTTPException(400, "File must be an image (jpg, png, etc.)")
|
| 176 |
|
|
|
|
| 177 |
contents = await file.read()
|
| 178 |
+
if len(contents) > 10 * 1024 * 1024:
|
| 179 |
+
raise HTTPException(400, "Image too large (max 10MB)")
|
| 180 |
|
| 181 |
b64 = base64.b64encode(contents).decode("utf-8")
|
| 182 |
media_type = file.content_type or "image/jpeg"
|
| 183 |
|
| 184 |
try:
|
| 185 |
+
resp = vision_client.chat_completion(
|
| 186 |
+
messages=[{
|
| 187 |
+
"role": "user",
|
| 188 |
+
"content": [
|
| 189 |
+
{
|
| 190 |
+
"type": "image_url",
|
| 191 |
+
"image_url": {"url": f"data:{media_type};base64,{b64}"},
|
| 192 |
+
},
|
| 193 |
+
{"type": "text", "text": OCR_PROMPT},
|
| 194 |
+
],
|
| 195 |
+
}],
|
| 196 |
+
max_tokens=1000,
|
| 197 |
+
temperature=0.05,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
)
|
| 199 |
+
raw = resp.choices[0].message.content
|
| 200 |
+
print(f"[OCR] Raw model response: {raw[:500]}")
|
| 201 |
result = extract_json(raw)
|
| 202 |
+
|
| 203 |
return OcrResponse(
|
| 204 |
arabic=result.get("arabic", ""),
|
| 205 |
english=result.get("english", ""),
|
| 206 |
transliteration=result.get("transliteration", ""),
|
| 207 |
source=result.get("source", ""),
|
| 208 |
raw_text=result.get("raw_text", ""),
|
| 209 |
+
method="vision",
|
| 210 |
)
|
|
|
|
|
|
|
| 211 |
except Exception as e:
|
| 212 |
+
print(f"[OCR] Failed: {e}")
|
| 213 |
+
raise HTTPException(500, f"OCR failed: {str(e)[:200]}")
|
| 214 |
|
| 215 |
@app.post("/extract-caption", response_model=CaptionResponse)
|
| 216 |
def extract_caption(req: CaptionRequest):
|
| 217 |
+
"""Extract structured dua fields from raw caption/social media text."""
|
| 218 |
+
if not req.text.strip():
|
| 219 |
+
raise HTTPException(400, "text is required")
|
| 220 |
if len(req.text) > 5000:
|
| 221 |
+
raise HTTPException(400, "Too long (max 5000 chars)")
|
|
|
|
| 222 |
try:
|
| 223 |
+
resp = client.chat_completion(
|
| 224 |
messages=[
|
| 225 |
{"role": "system", "content": CAPTION_SYSTEM},
|
| 226 |
{"role": "user", "content": (
|
| 227 |
+
f"Extract dua from:\n\n{req.text.strip()}\n\n"
|
| 228 |
+
f'JSON only: {{"arabic":"...","english":"...","transliteration":"...","source":"...","has_dua":true/false}}'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
)},
|
| 230 |
],
|
| 231 |
+
max_tokens=600, temperature=0.1,
|
|
|
|
| 232 |
)
|
| 233 |
+
result = extract_json(resp.choices[0].message.content)
|
|
|
|
| 234 |
return CaptionResponse(
|
| 235 |
arabic=result.get("arabic", ""),
|
| 236 |
english=result.get("english", ""),
|
|
|
|
| 239 |
has_dua=result.get("has_dua", False),
|
| 240 |
)
|
| 241 |
except ValueError as e:
|
| 242 |
+
raise HTTPException(422, str(e))
|
| 243 |
except Exception as e:
|
| 244 |
+
raise HTTPException(500, f"Caption extraction failed: {e}")
|