Consulawtech commited on
Commit
c7f28a0
·
1 Parent(s): f3fc81f

fix: switch to Docker SDK, remove Gradio dependency

Browse files
Files changed (4) hide show
  1. Dockerfile +12 -0
  2. README.md +5 -40
  3. app.py +33 -112
  4. requirements.txt +0 -1
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY app.py .
9
+
10
+ EXPOSE 7860
11
+
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -3,60 +3,25 @@ title: Munājāt Translation API
3
  emoji: 🕌
4
  colorFrom: green
5
  colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 5.0.0
8
- app_file: app.py
9
  pinned: false
10
  license: mit
11
  ---
12
 
13
  # Munājāt — Arabic Dua Translation & Transliteration API
14
 
15
- A REST API + Gradio demo for translating Arabic duas (supplications) into English (and other languages) with academic transliteration.
16
 
17
  ## API Usage
18
 
19
  ### POST `/translate`
20
-
21
  ```bash
22
- curl -X POST "https://YOUR_USERNAME-munajat-api.hf.space/translate" \
23
  -H "Content-Type: application/json" \
24
- -d '{
25
- "arabic_text": "اللَّهُمَّ أَنْتَ رَبِّي لَا إِلَهَ إِلَّا أَنْتَ",
26
- "target_language": "english"
27
- }'
28
- ```
29
-
30
- **Response:**
31
- ```json
32
- {
33
- "translation": "O Allah, You are my Lord, there is no god but You.",
34
- "transliteration": "Allāhumma anta rabbī lā ilāha illā ant",
35
- "model": "mistralai/Mistral-7B-Instruct-v0.3"
36
- }
37
  ```
38
 
39
  ### GET `/health`
40
-
41
  ```bash
42
- curl "https://YOUR_USERNAME-munajat-api.hf.space/health"
43
  ```
44
-
45
- ## Setup (for developers)
46
-
47
- 1. Fork/duplicate this Space
48
- 2. Add your HF token in **Settings → Secrets** as `HF_TOKEN`
49
- 3. Optionally change `MODEL_ID` secret to use a different model
50
-
51
- ## Supported Languages
52
-
53
- - English (default)
54
- - Urdu
55
- - French
56
- - Turkish
57
- - Malay
58
- - Indonesian
59
-
60
- ---
61
-
62
- Built with ❤️ for the Muslim Ummah • مناجاة — Munājāt
 
3
  emoji: 🕌
4
  colorFrom: green
5
  colorTo: yellow
6
+ sdk: docker
 
 
7
  pinned: false
8
  license: mit
9
  ---
10
 
11
  # Munājāt — Arabic Dua Translation & Transliteration API
12
 
13
+ REST API for translating Arabic duas with transliteration. Powered by Mistral-7B via HuggingFace Inference API.
14
 
15
  ## API Usage
16
 
17
  ### POST `/translate`
 
18
  ```bash
19
+ curl -X POST "https://consulawtech-munajat-api.hf.space/translate" \
20
  -H "Content-Type: application/json" \
21
+ -d '{"arabic_text":"اللَّهُمَّ أَنْتَ رَبِّي","target_language":"english"}'
 
 
 
 
 
 
 
 
 
 
 
 
22
  ```
23
 
24
  ### GET `/health`
 
25
  ```bash
26
+ curl "https://consulawtech-munajat-api.hf.space/health"
27
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,29 +1,25 @@
1
  """
2
  Munājāt — Arabic Dua Translation & Transliteration API
3
- HuggingFace Space (FastAPI + Gradio)
4
 
5
  Endpoints:
6
  POST /translate → { arabic_text, target_language? } → { translation, transliteration }
7
  GET /health → { status }
 
8
  """
9
 
10
  import os
11
  import json
12
  import re
13
- import gradio as gr
14
  from fastapi import FastAPI, HTTPException
15
  from fastapi.middleware.cors import CORSMiddleware
 
16
  from pydantic import BaseModel
17
  from huggingface_hub import InferenceClient
18
 
19
  # ── Model ──────────────────────────────────────────────────────────────────────
20
- # Use a strong instruction model available on HF Inference API (free tier)
21
- # Options in order of preference:
22
- # mistralai/Mixtral-8x7B-Instruct-v0.1 (best quality, may be slow)
23
- # mistralai/Mistral-7B-Instruct-v0.3 (good quality, faster)
24
- # HuggingFaceH4/zephyr-7b-beta (good fallback)
25
  MODEL_ID = os.getenv("MODEL_ID", "mistralai/Mistral-7B-Instruct-v0.3")
26
- HF_TOKEN = os.getenv("HF_TOKEN", "") # Set in Space Secrets
27
 
28
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None)
29
 
@@ -40,7 +36,7 @@ app.add_middleware(
40
 
41
  class TranslationRequest(BaseModel):
42
  arabic_text: str
43
- target_language: str = "english" # "english" | "urdu" | "french" etc.
44
 
45
 
46
  class TranslationResponse(BaseModel):
@@ -52,54 +48,56 @@ class TranslationResponse(BaseModel):
52
  SYSTEM_PROMPT = """You are an expert Islamic scholar and Arabic linguist specializing in dua (supplication) translation.
53
 
54
  Your task is to:
55
- 1. Translate Arabic dua text into the requested target language with deep reverence, accuracy, and preservation of spiritual nuance
56
- 2. Generate academic transliteration of the Arabic text using these rules:
57
- - Mark long vowels with macrons: ā (alif), ī (ya), ū (waw)
58
- - Use dh for ذ, th for ث, gh for غ, kh for خ
59
- - Separate words clearly for recitation
60
 
61
  IMPORTANT: Respond ONLY with a valid JSON object. No markdown, no explanation, no backticks.
62
- Format:
63
- {"translation": "...", "transliteration": "..."}"""
64
-
65
-
66
- def build_prompt(arabic_text: str, target_language: str) -> str:
67
- return f"""Translate this Arabic dua into {target_language} and provide its transliteration.
68
-
69
- Arabic text: {arabic_text}
70
-
71
- Respond ONLY with JSON: {{"translation": "...", "transliteration": "..."}}"""
72
 
73
 
74
  def extract_json(text: str) -> dict:
75
- """Try to extract JSON from model output even if it has surrounding text."""
76
- # Direct parse
77
  try:
78
  return json.loads(text.strip())
79
  except Exception:
80
  pass
81
-
82
- # Find JSON object in response
83
  match = re.search(r'\{[^{}]*"translation"[^{}]*"transliteration"[^{}]*\}', text, re.DOTALL)
84
  if match:
85
  try:
86
  return json.loads(match.group())
87
  except Exception:
88
  pass
89
-
90
- # Last resort: extract values manually
91
  trans_match = re.search(r'"translation"\s*:\s*"([^"]+)"', text)
92
  translit_match = re.search(r'"transliteration"\s*:\s*"([^"]+)"', text)
93
-
94
  if trans_match and translit_match:
95
  return {
96
  "translation": trans_match.group(1),
97
  "transliteration": translit_match.group(1),
98
  }
99
-
100
  raise ValueError(f"Could not parse JSON from model response: {text[:200]}")
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  @app.get("/health")
104
  def health():
105
  return {"status": "ok", "model": MODEL_ID}
@@ -109,103 +107,26 @@ def health():
109
  def translate(req: TranslationRequest):
110
  if not req.arabic_text or not req.arabic_text.strip():
111
  raise HTTPException(status_code=400, detail="arabic_text is required")
112
-
113
  if len(req.arabic_text) > 3000:
114
  raise HTTPException(status_code=400, detail="arabic_text too long (max 3000 chars)")
115
 
116
- prompt = build_prompt(req.arabic_text.strip(), req.target_language)
117
 
118
  try:
119
  response = client.text_generation(
120
- prompt=f"<s>[INST] {SYSTEM_PROMPT}\n\n{prompt} [/INST]",
121
  max_new_tokens=600,
122
- temperature=0.2, # Low temp for accurate translations
123
  repetition_penalty=1.1,
124
  do_sample=True,
125
  )
126
-
127
  result = extract_json(response)
128
-
129
  return TranslationResponse(
130
  translation=result.get("translation", ""),
131
  transliteration=result.get("transliteration", ""),
132
  model=MODEL_ID,
133
  )
134
-
135
  except ValueError as e:
136
  raise HTTPException(status_code=422, detail=str(e))
137
  except Exception as e:
138
  raise HTTPException(status_code=500, detail=f"Model inference failed: {str(e)}")
139
-
140
-
141
- # ── Gradio UI (for the Space homepage) ────────────────────────────────────────
142
- def gradio_translate(arabic_text: str, target_language: str) -> tuple[str, str]:
143
- """Called by the Gradio demo interface."""
144
- if not arabic_text.strip():
145
- return "Please enter Arabic text.", ""
146
- try:
147
- result = translate(TranslationRequest(
148
- arabic_text=arabic_text,
149
- target_language=target_language,
150
- ))
151
- return result.translation, result.transliteration
152
- except HTTPException as e:
153
- return f"Error: {e.detail}", ""
154
- except Exception as e:
155
- return f"Error: {str(e)}", ""
156
-
157
-
158
- with gr.Blocks(
159
- title="Munājāt — Dua Translation API",
160
- theme=gr.themes.Soft(primary_hue="green"),
161
- css=".gradio-container { max-width: 800px; margin: auto; }",
162
- ) as demo:
163
- gr.Markdown("""
164
- # 🕌 Munājāt — Arabic Dua Translation API
165
- ### مناجاة — Intimate Whispers to God
166
-
167
- Translate Arabic duas (supplications) into English (or other languages) with transliteration.
168
-
169
- **API Endpoint:** `POST /translate`
170
- ```json
171
- {
172
- "arabic_text": "اللَّهُمَّ أَنْتَ رَبِّي",
173
- "target_language": "english"
174
- }
175
- ```
176
- """)
177
-
178
- with gr.Row():
179
- with gr.Column():
180
- arabic_input = gr.Textbox(
181
- label="Arabic Text (النص العربي)",
182
- placeholder="اللَّهُمَّ أَنْتَ رَبِّي لَا إِلَهَ إِلَّا أَنْتَ",
183
- lines=4,
184
- rtl=True,
185
- )
186
- language_input = gr.Dropdown(
187
- label="Target Language",
188
- choices=["english", "urdu", "french", "turkish", "malay", "indonesian"],
189
- value="english",
190
- )
191
- btn = gr.Button("Translate 🌿", variant="primary")
192
-
193
- with gr.Column():
194
- translation_out = gr.Textbox(label="Translation", lines=4)
195
- transliteration_out = gr.Textbox(label="Transliteration", lines=3)
196
-
197
- btn.click(
198
- fn=gradio_translate,
199
- inputs=[arabic_input, language_input],
200
- outputs=[translation_out, transliteration_out],
201
- )
202
-
203
- gr.Markdown("""
204
- ---
205
- *\"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ\"*
206
- *"And when My servants ask you concerning Me — indeed I am near."* — Quran 2:186
207
- """)
208
-
209
- # Mount Gradio on FastAPI (Gradio 5+ compatible)
210
- from gradio import mount_gradio_app
211
- app = mount_gradio_app(app, demo, path="/")
 
1
  """
2
  Munājāt — Arabic Dua Translation & Transliteration API
3
+ Pure FastAPI (no Gradio) — Python 3.13 compatible
4
 
5
  Endpoints:
6
  POST /translate → { arabic_text, target_language? } → { translation, transliteration }
7
  GET /health → { status }
8
+ GET / → simple HTML test page
9
  """
10
 
11
  import os
12
  import json
13
  import re
 
14
  from fastapi import FastAPI, HTTPException
15
  from fastapi.middleware.cors import CORSMiddleware
16
+ from fastapi.responses import HTMLResponse
17
  from pydantic import BaseModel
18
  from huggingface_hub import InferenceClient
19
 
20
  # ── Model ──────────────────────────────────────────────────────────────────────
 
 
 
 
 
21
  MODEL_ID = os.getenv("MODEL_ID", "mistralai/Mistral-7B-Instruct-v0.3")
22
+ HF_TOKEN = os.getenv("HF_TOKEN", "")
23
 
24
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None)
25
 
 
36
 
37
  class TranslationRequest(BaseModel):
38
  arabic_text: str
39
+ target_language: str = "english"
40
 
41
 
42
  class TranslationResponse(BaseModel):
 
48
  SYSTEM_PROMPT = """You are an expert Islamic scholar and Arabic linguist specializing in dua (supplication) translation.
49
 
50
  Your task is to:
51
+ 1. Translate Arabic dua text into the requested target language with deep reverence and accuracy
52
+ 2. Generate academic transliteration using: ā (alif), ī (ya), ū (waw), dh for ذ, th for ث, gh for غ, kh for خ
 
 
 
53
 
54
  IMPORTANT: Respond ONLY with a valid JSON object. No markdown, no explanation, no backticks.
55
+ Format: {"translation": "...", "transliteration": "..."}"""
 
 
 
 
 
 
 
 
 
56
 
57
 
58
  def extract_json(text: str) -> dict:
 
 
59
  try:
60
  return json.loads(text.strip())
61
  except Exception:
62
  pass
 
 
63
  match = re.search(r'\{[^{}]*"translation"[^{}]*"transliteration"[^{}]*\}', text, re.DOTALL)
64
  if match:
65
  try:
66
  return json.loads(match.group())
67
  except Exception:
68
  pass
 
 
69
  trans_match = re.search(r'"translation"\s*:\s*"([^"]+)"', text)
70
  translit_match = re.search(r'"transliteration"\s*:\s*"([^"]+)"', text)
 
71
  if trans_match and translit_match:
72
  return {
73
  "translation": trans_match.group(1),
74
  "transliteration": translit_match.group(1),
75
  }
 
76
  raise ValueError(f"Could not parse JSON from model response: {text[:200]}")
77
 
78
 
79
+ @app.get("/", response_class=HTMLResponse)
80
+ def root():
81
+ return """
82
+ <html><head><title>Munājāt API</title>
83
+ <style>body{font-family:Arial,sans-serif;max-width:700px;margin:60px auto;padding:0 20px;background:#F9F6F0}
84
+ h1{color:#1A3D2B}code{background:#F0E8D8;padding:2px 6px;border-radius:4px}
85
+ pre{background:#F0E8D8;padding:16px;border-radius:8px;overflow-x:auto}
86
+ .gold{color:#C9A84C}</style></head>
87
+ <body>
88
+ <h1>🕌 مناجاة &mdash; Munājāt Translation API</h1>
89
+ <p><em>Intimate Whispers to God</em></p>
90
+ <h2>POST <code>/translate</code></h2>
91
+ <pre>curl -X POST /translate \\
92
+ -H "Content-Type: application/json" \\
93
+ -d '{"arabic_text":"اللَّهُمَّ أَنْتَ رَبِّي","target_language":"english"}'</pre>
94
+ <h2>GET <code>/health</code></h2>
95
+ <pre>{"status":"ok","model":"mistralai/Mistral-7B-Instruct-v0.3"}</pre>
96
+ <p class="gold"><em>"وَإِذَا سَأَلَكَ عِبَادِي عَنِّي فَإِنِّي قَرِيبٌ" — Quran 2:186</em></p>
97
+ </body></html>
98
+ """
99
+
100
+
101
  @app.get("/health")
102
  def health():
103
  return {"status": "ok", "model": MODEL_ID}
 
107
  def translate(req: TranslationRequest):
108
  if not req.arabic_text or not req.arabic_text.strip():
109
  raise HTTPException(status_code=400, detail="arabic_text is required")
 
110
  if len(req.arabic_text) > 3000:
111
  raise HTTPException(status_code=400, detail="arabic_text too long (max 3000 chars)")
112
 
113
+ prompt = f"<s>[INST] {SYSTEM_PROMPT}\n\nTranslate this Arabic dua into {req.target_language} and provide its transliteration.\n\nArabic text: {req.arabic_text.strip()}\n\nRespond ONLY with JSON: {{\"translation\": \"...\", \"transliteration\": \"...\"}} [/INST]"
114
 
115
  try:
116
  response = client.text_generation(
117
+ prompt=prompt,
118
  max_new_tokens=600,
119
+ temperature=0.2,
120
  repetition_penalty=1.1,
121
  do_sample=True,
122
  )
 
123
  result = extract_json(response)
 
124
  return TranslationResponse(
125
  translation=result.get("translation", ""),
126
  transliteration=result.get("transliteration", ""),
127
  model=MODEL_ID,
128
  )
 
129
  except ValueError as e:
130
  raise HTTPException(status_code=422, detail=str(e))
131
  except Exception as e:
132
  raise HTTPException(status_code=500, detail=f"Model inference failed: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
  fastapi>=0.109.0
2
  uvicorn>=0.27.0
3
- gradio>=5.0.0
4
  huggingface_hub>=0.21.0
5
  pydantic>=2.0.0
 
1
  fastapi>=0.109.0
2
  uvicorn>=0.27.0
 
3
  huggingface_hub>=0.21.0
4
  pydantic>=2.0.0