Consulawtech commited on
Commit
dfafb99
·
1 Parent(s): 13f1662

fix: better OCR with VL-72B, debug logging, cleaner error messages

Browse files
Files changed (1) hide show
  1. app.py +106 -203
app.py CHANGED
@@ -1,18 +1,12 @@
1
  """
2
- Munājāt — Arabic Dua API
3
- Endpoints:
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 = os.getenv("MODEL_ID", "Qwen/Qwen2.5-72B-Instruct")
25
- VISION_MODEL_ID = os.getenv("VISION_MODEL_ID", "Qwen/Qwen2.5-VL-7B-Instruct")
26
- HF_TOKEN = os.getenv("HF_TOKEN", "")
27
 
28
- client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None)
29
- vision_client = InferenceClient(model=VISION_MODEL_ID, token=HF_TOKEN or None)
30
 
31
  # ── App ────────────────────────────────────────────────────────────────────────
32
- app = FastAPI(title="Munājāt API", version="2.0.0")
33
-
34
- app.add_middleware(
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 (supplication) translation.
43
-
44
- Your task:
45
- 1. Translate the Arabic dua into the requested language with reverence and accuracy
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
- OCR_SYSTEM = """You are an expert Arabic text extractor. You will be given an image that may contain:
52
- - Arabic dua or supplication text
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
- Respond ONLY with valid JSON. No markdown, no backticks.
64
- Format: {
65
- "arabic": "extracted arabic text or empty string",
66
- "english": "extracted english translation or empty string",
67
- "transliteration": "extracted transliteration or empty string",
68
- "source": "extracted source reference or empty string",
69
- "raw_text": "all extracted text combined"
70
- }"""
71
 
72
- CAPTION_SYSTEM = """You are an expert at identifying Islamic duas (supplications) in social media captions and text.
 
 
 
73
 
74
- Given raw text (copied from Instagram, WhatsApp, YouTube etc), extract any dua content.
75
- Clean up hashtags, emojis, handles, promotional text. Keep only the actual dua content.
76
 
77
- Identify:
78
- 1. Arabic text (the actual dua)
79
- 2. English translation (if present)
80
- 3. Transliteration (if present)
81
- 4. Source/reference (if mentioned)
 
82
 
83
- Respond ONLY with valid JSON. No markdown, no backticks.
84
- Format: {
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 helpers ───────────────────────────────────────────────────────────────
93
  def extract_json(text: str) -> dict:
94
- """Robustly extract JSON from model response."""
95
- # Try direct parse
96
  try:
97
- return json.loads(text.strip())
98
  except Exception:
99
  pass
100
- # Strip markdown code blocks
101
- cleaned = re.sub(r'```json\s*|\s*```', '', text).strip()
102
  try:
103
  return json.loads(cleaned)
104
  except Exception:
105
  pass
106
- # Find JSON object in text
107
- match = re.search(r'\{.*\}', text, re.DOTALL)
108
- if match:
109
  try:
110
- return json.loads(match.group())
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
- m = re.search(rf'"{field}"\s*:\s*"((?:[^"\\]|\\.)*)"', text)
118
- if m:
119
- result[field] = m.group(1)
120
- bool_m = re.search(r'"has_dua"\s*:\s*(true|false)', text)
121
- if bool_m:
122
- result['has_dua'] = bool_m.group(1) == 'true'
123
  if result:
124
  return result
125
- raise ValueError(f"Could not parse JSON from: {text[:300]}")
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
- <html><head><title>Munājāt API</title>
162
- <style>
163
- body{font-family:Arial,sans-serif;max-width:760px;margin:60px auto;padding:0 24px;background:#F9F6F0}
164
- h1{color:#1A3D2B} h2{color:#2D6A4F;margin-top:32px}
165
- code{background:#F0E8D8;padding:2px 8px;border-radius:4px;font-size:13px}
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
- <table>
178
- <tr><th>Method</th><th>Endpoint</th><th>Description</th></tr>
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 or not req.arabic_text.strip():
214
- raise HTTPException(status_code=400, detail="arabic_text is required")
215
  if len(req.arabic_text) > 3000:
216
- raise HTTPException(status_code=400, detail="arabic_text too long (max 3000 chars)")
217
-
218
  try:
219
- response = client.chat_completion(
220
  messages=[
221
  {"role": "system", "content": TRANSLATE_SYSTEM},
222
  {"role": "user", "content": (
223
- f"Translate this Arabic dua into {req.target_language} "
224
- f"and provide its transliteration.\n\n"
225
- f"Arabic: {req.arabic_text.strip()}\n\n"
226
- f'Respond ONLY with JSON: {{"translation": "...", "transliteration": "..."}}'
227
  )},
228
  ],
229
- max_tokens=600,
230
- temperature=0.2,
231
  )
232
- raw = response.choices[0].message.content
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(status_code=422, detail=str(e))
241
  except Exception as e:
242
- raise HTTPException(status_code=500, detail=f"Model inference failed: {str(e)}")
243
-
244
 
245
  @app.post("/ocr", response_model=OcrResponse)
246
  async def ocr(file: UploadFile = File(...)):
247
- """Extract Arabic dua text from an image using vision model."""
248
- # Validate file type
249
  if not file.content_type or not file.content_type.startswith("image/"):
250
- raise HTTPException(status_code=400, detail="File must be an image")
251
 
252
- # Read and base64 encode the image
253
  contents = await file.read()
254
- if len(contents) > 10 * 1024 * 1024: # 10MB limit
255
- raise HTTPException(status_code=400, detail="Image too large (max 10MB)")
256
 
257
  b64 = base64.b64encode(contents).decode("utf-8")
258
  media_type = file.content_type or "image/jpeg"
259
 
260
  try:
261
- response = vision_client.chat_completion(
262
- messages=[
263
- {
264
- "role": "user",
265
- "content": [
266
- {
267
- "type": "image_url",
268
- "image_url": {
269
- "url": f"data:{media_type};base64,{b64}"
270
- },
271
- },
272
- {
273
- "type": "text",
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 = response.choices[0].message.content
 
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
- raise HTTPException(status_code=500, detail=f"OCR failed: {str(e)}")
303
-
304
 
305
  @app.post("/extract-caption", response_model=CaptionResponse)
306
  def extract_caption(req: CaptionRequest):
307
- """Extract dua content from raw caption/text (Instagram, WhatsApp, etc.)."""
308
- if not req.text or not req.text.strip():
309
- raise HTTPException(status_code=400, detail="text is required")
310
  if len(req.text) > 5000:
311
- raise HTTPException(status_code=400, detail="text too long (max 5000 chars)")
312
-
313
  try:
314
- response = client.chat_completion(
315
  messages=[
316
  {"role": "system", "content": CAPTION_SYSTEM},
317
  {"role": "user", "content": (
318
- f"Extract any dua content from this text:\n\n"
319
- f"{req.text.strip()}\n\n"
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
- raw = response.choices[0].message.content
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(status_code=422, detail=str(e))
340
  except Exception as e:
341
- raise HTTPException(status_code=500, detail=f"Caption extraction failed: {str(e)}")
 
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}")