File size: 10,488 Bytes
e6737c8
dfafb99
 
e6737c8
 
 
 
13f1662
 
 
 
e6737c8
c7f28a0
e6737c8
 
 
13f1662
dfafb99
 
 
e6737c8
dfafb99
 
e6737c8
13f1662
dfafb99
 
 
e6737c8
13f1662
dfafb99
 
 
 
13f1662
e6737c8
dfafb99
 
e6737c8
dfafb99
 
 
 
 
e6737c8
dfafb99
 
 
 
e6737c8
dfafb99
 
13f1662
dfafb99
 
 
 
 
 
e6737c8
dfafb99
 
e6737c8
dfafb99
e6737c8
dfafb99
e6737c8
dfafb99
e6737c8
 
dfafb99
13f1662
 
 
 
dfafb99
 
e6737c8
dfafb99
e6737c8
 
13f1662
 
 
dfafb99
 
 
 
 
 
13f1662
 
dfafb99
e6737c8
dfafb99
13f1662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfafb99
13f1662
 
 
 
 
 
 
 
 
 
 
 
 
c7f28a0
 
dfafb99
 
 
 
 
 
13f1662
dfafb99
 
 
c7f28a0
e6737c8
 
dfafb99
e6737c8
 
 
dfafb99
 
e6737c8
dfafb99
e6737c8
dfafb99
e68c044
13f1662
 
dfafb99
 
 
13f1662
e68c044
dfafb99
e6737c8
dfafb99
e6737c8
 
 
 
 
 
dfafb99
e6737c8
dfafb99
13f1662
 
 
dfafb99
13f1662
dfafb99
13f1662
 
dfafb99
 
13f1662
 
 
 
 
dfafb99
 
 
 
 
 
 
 
 
 
 
 
 
13f1662
dfafb99
 
13f1662
dfafb99
13f1662
 
 
 
 
 
dfafb99
13f1662
 
dfafb99
 
13f1662
 
 
dfafb99
 
 
13f1662
dfafb99
13f1662
dfafb99
13f1662
 
 
dfafb99
 
13f1662
 
dfafb99
13f1662
dfafb99
13f1662
 
 
 
 
 
 
 
dfafb99
13f1662
dfafb99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
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}")