Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- README.md +55 -7
- app.py +211 -0
- requirements.txt +5 -0
README.md
CHANGED
|
@@ -1,14 +1,62 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
-
short_description: Translation and Transliteration of Arabic Language
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Munājāt Translation API
|
| 3 |
+
emoji: 🕌
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.20.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
|
app.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 30 |
+
# ── FastAPI ────────────────────────────────────────────────────────────────────
|
| 31 |
+
app = FastAPI(title="Munājāt Translation API", version="1.0.0")
|
| 32 |
+
|
| 33 |
+
app.add_middleware(
|
| 34 |
+
CORSMiddleware,
|
| 35 |
+
allow_origins=["*"],
|
| 36 |
+
allow_methods=["*"],
|
| 37 |
+
allow_headers=["*"],
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TranslationRequest(BaseModel):
|
| 42 |
+
arabic_text: str
|
| 43 |
+
target_language: str = "english" # "english" | "urdu" | "french" etc.
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TranslationResponse(BaseModel):
|
| 47 |
+
translation: str
|
| 48 |
+
transliteration: str
|
| 49 |
+
model: str
|
| 50 |
+
|
| 51 |
+
|
| 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}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@app.post("/translate", response_model=TranslationResponse)
|
| 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
|
| 210 |
+
import gradio as gr
|
| 211 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.109.0
|
| 2 |
+
uvicorn>=0.27.0
|
| 3 |
+
gradio>=4.20.0
|
| 4 |
+
huggingface_hub>=0.21.0
|
| 5 |
+
pydantic>=2.0.0
|