Upload 3 files
Browse files- main.py +30 -45
- requirements.txt +1 -1
main.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
from fastapi_utils.tasks import repeat_every
|
| 5 |
from scalar_fastapi import get_scalar_api_reference
|
| 6 |
import json
|
| 7 |
import os
|
| 8 |
import requests
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
app = FastAPI(
|
|
@@ -36,12 +36,17 @@ API_DATA_DIR = CDN_DIR / "api_data"
|
|
| 36 |
RECITERS_DIR = CDN_DIR / "reciters" / "audio"
|
| 37 |
MUSHAFS_DIR = CDN_DIR / "mushafs"
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
@app.on_event("startup")
|
| 41 |
-
@repeat_every(seconds=20) # Repeat every 20 seconds
|
| 42 |
def keep_alive():
|
| 43 |
-
# Just a simple log
|
| 44 |
print("Kalamalah API keep-alive tick")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# Reciter info (based on existing data)
|
| 47 |
RECITERS = {
|
|
@@ -51,7 +56,7 @@ RECITERS = {
|
|
| 51 |
"types": ["murattal"]
|
| 52 |
},
|
| 53 |
"abdul-rashid-sofi": {
|
| 54 |
-
"name": "Abdul-
|
| 55 |
"arabic_name": "عبد الرشيد الصوفي",
|
| 56 |
"types": ["murattal"]
|
| 57 |
},
|
|
@@ -118,7 +123,7 @@ async def scalar_html():
|
|
| 118 |
openapi_url=app.openapi_url,
|
| 119 |
)
|
| 120 |
|
| 121 |
-
# Health check endpoint
|
| 122 |
@app.get("/health")
|
| 123 |
async def health_check():
|
| 124 |
return {"status": "healthy"}
|
|
@@ -168,9 +173,8 @@ async def get_reciters():
|
|
| 168 |
async def get_quran_text(language: str, surah_number: int, ayah_number: int = None):
|
| 169 |
if surah_number < 1 or surah_number > 114:
|
| 170 |
raise HTTPException(status_code=404, detail="Surah not found")
|
| 171 |
-
|
| 172 |
if USE_HF_CDN:
|
| 173 |
-
# Determine edition file
|
| 174 |
edition_map = {
|
| 175 |
"ar": "uthmani.json",
|
| 176 |
"en": "en.sahih.json",
|
|
@@ -180,13 +184,11 @@ async def get_quran_text(language: str, surah_number: int, ayah_number: int = No
|
|
| 180 |
hf_url = f"{HF_DATASET_URL}/api_data/surah/{surah_number}/{file_name}"
|
| 181 |
|
| 182 |
try:
|
| 183 |
-
# Fetch from HF CDN
|
| 184 |
response = requests.get(hf_url, timeout=10)
|
| 185 |
response.raise_for_status()
|
| 186 |
data = response.json()
|
| 187 |
|
| 188 |
if ayah_number:
|
| 189 |
-
# Filter to specific ayah
|
| 190 |
if data.get("code") == 200:
|
| 191 |
ayahs = data["data"]["ayahs"]
|
| 192 |
if 1 <= ayah_number <= len(ayahs):
|
|
@@ -197,12 +199,10 @@ async def get_quran_text(language: str, surah_number: int, ayah_number: int = No
|
|
| 197 |
except Exception as e:
|
| 198 |
raise HTTPException(status_code=500, detail=str(e))
|
| 199 |
else:
|
| 200 |
-
# Local development mode
|
| 201 |
surah_dir = API_DATA_DIR / "surah" / str(surah_number)
|
| 202 |
if not surah_dir.exists():
|
| 203 |
raise HTTPException(status_code=404, detail="Surah not found")
|
| 204 |
-
|
| 205 |
-
# Determine edition file
|
| 206 |
edition_map = {
|
| 207 |
"ar": "uthmani.json",
|
| 208 |
"en": "en.sahih.json",
|
|
@@ -210,100 +210,86 @@ async def get_quran_text(language: str, surah_number: int, ayah_number: int = No
|
|
| 210 |
}
|
| 211 |
file_name = edition_map.get(language, f"{language}.json")
|
| 212 |
file_path = surah_dir / file_name
|
| 213 |
-
|
| 214 |
if not file_path.exists():
|
| 215 |
-
# Try other possible files in the directory
|
| 216 |
json_files = list(surah_dir.glob("*.json"))
|
| 217 |
if json_files:
|
| 218 |
file_path = json_files[0]
|
| 219 |
else:
|
| 220 |
raise HTTPException(status_code=404, detail=f"Edition {language} not found for this surah")
|
| 221 |
-
|
| 222 |
try:
|
| 223 |
with open(file_path, "r", encoding="utf-8") as f:
|
| 224 |
data = json.load(f)
|
| 225 |
-
|
| 226 |
if ayah_number:
|
| 227 |
-
# Filter to specific ayah
|
| 228 |
if data.get("code") == 200:
|
| 229 |
ayahs = data["data"]["ayahs"]
|
| 230 |
if 1 <= ayah_number <= len(ayahs):
|
| 231 |
return JSONResponse(content=ayahs[ayah_number - 1])
|
| 232 |
raise HTTPException(status_code=404, detail="Ayah not found")
|
| 233 |
-
|
| 234 |
return JSONResponse(content=data.get("data", data))
|
| 235 |
except Exception as e:
|
| 236 |
raise HTTPException(status_code=500, detail=str(e))
|
| 237 |
|
| 238 |
-
# Get mushaf page
|
| 239 |
@app.api_route("/api/mushaf/{mushaf_name}/{page_number}", methods=["GET", "HEAD"], operation_id="getMushafPage")
|
| 240 |
async def get_mushaf_page(mushaf_name: str, page_number: int):
|
| 241 |
if USE_HF_CDN:
|
| 242 |
-
# Redirect to Hugging Face CDN
|
| 243 |
for ext in [".jpg", ".jpeg", ".png"]:
|
| 244 |
-
# Just try redirecting with first extension
|
| 245 |
hf_url = f"{HF_DATASET_URL}/mushafs/{mushaf_name}/{page_number}{ext}"
|
| 246 |
return RedirectResponse(url=hf_url)
|
| 247 |
raise HTTPException(status_code=404, detail="Page not found")
|
| 248 |
else:
|
| 249 |
-
# Local development mode
|
| 250 |
mushaf_dir = MUSHAFS_DIR / mushaf_name
|
| 251 |
if not mushaf_dir.exists():
|
| 252 |
raise HTTPException(status_code=404, detail="Mushaf not found")
|
| 253 |
-
|
| 254 |
-
# Try different extensions
|
| 255 |
for ext in [".jpg", ".jpeg", ".png"]:
|
| 256 |
page_path = mushaf_dir / f"{page_number}{ext}"
|
| 257 |
if page_path.exists():
|
| 258 |
return FileResponse(page_path, media_type=f"image/{ext[1:]}")
|
| 259 |
-
|
| 260 |
raise HTTPException(status_code=404, detail="Page not found")
|
| 261 |
|
| 262 |
# Get reciter audio
|
| 263 |
@app.api_route("/api/{reciter_name}/{recitation_type}/{surah_number}", methods=["GET", "HEAD"], operation_id="getReciterAudio")
|
| 264 |
async def get_reciter_audio(reciter_name: str, recitation_type: str, surah_number: int):
|
| 265 |
-
# Validate reciter and type
|
| 266 |
if reciter_name not in RECITERS:
|
| 267 |
raise HTTPException(status_code=404, detail="Reciter not found")
|
| 268 |
-
|
| 269 |
if recitation_type not in RECITERS[reciter_name]["types"]:
|
| 270 |
raise HTTPException(status_code=404, detail="Recitation type not available for this reciter")
|
| 271 |
-
|
| 272 |
-
# Special case for ayah-by-ayah (only Al-Huzaifi)
|
| 273 |
if recitation_type == "ayah-by-ayah" and reciter_name != "al-huzaifi":
|
| 274 |
raise HTTPException(status_code=400, detail="Ayah-by-ayah only available for Al-Huzaifi")
|
| 275 |
-
|
| 276 |
if USE_HF_CDN:
|
| 277 |
-
# Redirect to Hugging Face CDN
|
| 278 |
surah_str_padded = str(surah_number).zfill(3)
|
| 279 |
hf_url = f"{HF_DATASET_URL}/reciters/audio/{reciter_name}/{recitation_type}/{surah_str_padded}.mp3"
|
| 280 |
return RedirectResponse(url=hf_url)
|
| 281 |
else:
|
| 282 |
-
# Find audio file path
|
| 283 |
surah_str_padded = str(surah_number).zfill(3)
|
| 284 |
surah_str_normal = str(surah_number)
|
| 285 |
-
|
| 286 |
-
# First try the new structure: reciter/type/001.mp3
|
| 287 |
audio_path = RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_padded}.mp3"
|
| 288 |
if audio_path.exists():
|
| 289 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 290 |
-
|
| 291 |
-
# Try without padding: reciter/type/1.mp3
|
| 292 |
audio_path = RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_normal}.mp3"
|
| 293 |
if audio_path.exists():
|
| 294 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 295 |
-
|
| 296 |
-
# Now check the old directory names (for backward compatibility)
|
| 297 |
old_dir_names = {
|
| 298 |
-
"yasser-al-dossari": "yasser_ad-
|
| 299 |
"abdul-baset": "abdul_baset",
|
| 300 |
"khalil-al-husary": "khalil_al_husary",
|
| 301 |
"siddiq-minshawi": "siddiq_minshawi"
|
| 302 |
}
|
| 303 |
-
|
| 304 |
if reciter_name in old_dir_names:
|
| 305 |
old_base_dir = RECITERS_DIR / old_dir_names[reciter_name]
|
| 306 |
-
# Check if it's a nested type directory or flat
|
| 307 |
if (old_base_dir / recitation_type).exists():
|
| 308 |
audio_path = old_base_dir / recitation_type / f"{surah_str_padded}.mp3"
|
| 309 |
if audio_path.exists():
|
|
@@ -312,14 +298,13 @@ async def get_reciter_audio(reciter_name: str, recitation_type: str, surah_numbe
|
|
| 312 |
if audio_path.exists():
|
| 313 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 314 |
else:
|
| 315 |
-
# Flat structure
|
| 316 |
audio_path = old_base_dir / f"{surah_str_padded}.mp3"
|
| 317 |
if audio_path.exists():
|
| 318 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 319 |
audio_path = old_base_dir / f"{surah_str_normal}.mp3"
|
| 320 |
if audio_path.exists():
|
| 321 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 322 |
-
|
| 323 |
raise HTTPException(status_code=404, detail="Audio file not found")
|
| 324 |
|
| 325 |
if __name__ == "__main__":
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 4 |
from scalar_fastapi import get_scalar_api_reference
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
import requests
|
| 8 |
+
import threading
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
app = FastAPI(
|
|
|
|
| 36 |
RECITERS_DIR = CDN_DIR / "reciters" / "audio"
|
| 37 |
MUSHAFS_DIR = CDN_DIR / "mushafs"
|
| 38 |
|
| 39 |
+
# Simple keep-alive function using threading.Timer
|
|
|
|
|
|
|
| 40 |
def keep_alive():
|
| 41 |
+
# Just a simple log to keep the app awake
|
| 42 |
print("Kalamalah API keep-alive tick")
|
| 43 |
+
# Schedule next tick in 20 seconds
|
| 44 |
+
threading.Timer(20.0, keep_alive).start()
|
| 45 |
+
|
| 46 |
+
# Start keep-alive on app startup
|
| 47 |
+
@app.on_event("startup")
|
| 48 |
+
async def startup_event():
|
| 49 |
+
keep_alive()
|
| 50 |
|
| 51 |
# Reciter info (based on existing data)
|
| 52 |
RECITERS = {
|
|
|
|
| 56 |
"types": ["murattal"]
|
| 57 |
},
|
| 58 |
"abdul-rashid-sofi": {
|
| 59 |
+
"name": "Abdul-Rasheed Sofi",
|
| 60 |
"arabic_name": "عبد الرشيد الصوفي",
|
| 61 |
"types": ["murattal"]
|
| 62 |
},
|
|
|
|
| 123 |
openapi_url=app.openapi_url,
|
| 124 |
)
|
| 125 |
|
| 126 |
+
# Health check endpoint
|
| 127 |
@app.get("/health")
|
| 128 |
async def health_check():
|
| 129 |
return {"status": "healthy"}
|
|
|
|
| 173 |
async def get_quran_text(language: str, surah_number: int, ayah_number: int = None):
|
| 174 |
if surah_number < 1 or surah_number > 114:
|
| 175 |
raise HTTPException(status_code=404, detail="Surah not found")
|
| 176 |
+
|
| 177 |
if USE_HF_CDN:
|
|
|
|
| 178 |
edition_map = {
|
| 179 |
"ar": "uthmani.json",
|
| 180 |
"en": "en.sahih.json",
|
|
|
|
| 184 |
hf_url = f"{HF_DATASET_URL}/api_data/surah/{surah_number}/{file_name}"
|
| 185 |
|
| 186 |
try:
|
|
|
|
| 187 |
response = requests.get(hf_url, timeout=10)
|
| 188 |
response.raise_for_status()
|
| 189 |
data = response.json()
|
| 190 |
|
| 191 |
if ayah_number:
|
|
|
|
| 192 |
if data.get("code") == 200:
|
| 193 |
ayahs = data["data"]["ayahs"]
|
| 194 |
if 1 <= ayah_number <= len(ayahs):
|
|
|
|
| 199 |
except Exception as e:
|
| 200 |
raise HTTPException(status_code=500, detail=str(e))
|
| 201 |
else:
|
|
|
|
| 202 |
surah_dir = API_DATA_DIR / "surah" / str(surah_number)
|
| 203 |
if not surah_dir.exists():
|
| 204 |
raise HTTPException(status_code=404, detail="Surah not found")
|
| 205 |
+
|
|
|
|
| 206 |
edition_map = {
|
| 207 |
"ar": "uthmani.json",
|
| 208 |
"en": "en.sahih.json",
|
|
|
|
| 210 |
}
|
| 211 |
file_name = edition_map.get(language, f"{language}.json")
|
| 212 |
file_path = surah_dir / file_name
|
| 213 |
+
|
| 214 |
if not file_path.exists():
|
|
|
|
| 215 |
json_files = list(surah_dir.glob("*.json"))
|
| 216 |
if json_files:
|
| 217 |
file_path = json_files[0]
|
| 218 |
else:
|
| 219 |
raise HTTPException(status_code=404, detail=f"Edition {language} not found for this surah")
|
| 220 |
+
|
| 221 |
try:
|
| 222 |
with open(file_path, "r", encoding="utf-8") as f:
|
| 223 |
data = json.load(f)
|
| 224 |
+
|
| 225 |
if ayah_number:
|
|
|
|
| 226 |
if data.get("code") == 200:
|
| 227 |
ayahs = data["data"]["ayahs"]
|
| 228 |
if 1 <= ayah_number <= len(ayahs):
|
| 229 |
return JSONResponse(content=ayahs[ayah_number - 1])
|
| 230 |
raise HTTPException(status_code=404, detail="Ayah not found")
|
| 231 |
+
|
| 232 |
return JSONResponse(content=data.get("data", data))
|
| 233 |
except Exception as e:
|
| 234 |
raise HTTPException(status_code=500, detail=str(e))
|
| 235 |
|
| 236 |
+
# Get mushaf page
|
| 237 |
@app.api_route("/api/mushaf/{mushaf_name}/{page_number}", methods=["GET", "HEAD"], operation_id="getMushafPage")
|
| 238 |
async def get_mushaf_page(mushaf_name: str, page_number: int):
|
| 239 |
if USE_HF_CDN:
|
|
|
|
| 240 |
for ext in [".jpg", ".jpeg", ".png"]:
|
|
|
|
| 241 |
hf_url = f"{HF_DATASET_URL}/mushafs/{mushaf_name}/{page_number}{ext}"
|
| 242 |
return RedirectResponse(url=hf_url)
|
| 243 |
raise HTTPException(status_code=404, detail="Page not found")
|
| 244 |
else:
|
|
|
|
| 245 |
mushaf_dir = MUSHAFS_DIR / mushaf_name
|
| 246 |
if not mushaf_dir.exists():
|
| 247 |
raise HTTPException(status_code=404, detail="Mushaf not found")
|
| 248 |
+
|
|
|
|
| 249 |
for ext in [".jpg", ".jpeg", ".png"]:
|
| 250 |
page_path = mushaf_dir / f"{page_number}{ext}"
|
| 251 |
if page_path.exists():
|
| 252 |
return FileResponse(page_path, media_type=f"image/{ext[1:]}")
|
| 253 |
+
|
| 254 |
raise HTTPException(status_code=404, detail="Page not found")
|
| 255 |
|
| 256 |
# Get reciter audio
|
| 257 |
@app.api_route("/api/{reciter_name}/{recitation_type}/{surah_number}", methods=["GET", "HEAD"], operation_id="getReciterAudio")
|
| 258 |
async def get_reciter_audio(reciter_name: str, recitation_type: str, surah_number: int):
|
|
|
|
| 259 |
if reciter_name not in RECITERS:
|
| 260 |
raise HTTPException(status_code=404, detail="Reciter not found")
|
| 261 |
+
|
| 262 |
if recitation_type not in RECITERS[reciter_name]["types"]:
|
| 263 |
raise HTTPException(status_code=404, detail="Recitation type not available for this reciter")
|
| 264 |
+
|
|
|
|
| 265 |
if recitation_type == "ayah-by-ayah" and reciter_name != "al-huzaifi":
|
| 266 |
raise HTTPException(status_code=400, detail="Ayah-by-ayah only available for Al-Huzaifi")
|
| 267 |
+
|
| 268 |
if USE_HF_CDN:
|
|
|
|
| 269 |
surah_str_padded = str(surah_number).zfill(3)
|
| 270 |
hf_url = f"{HF_DATASET_URL}/reciters/audio/{reciter_name}/{recitation_type}/{surah_str_padded}.mp3"
|
| 271 |
return RedirectResponse(url=hf_url)
|
| 272 |
else:
|
|
|
|
| 273 |
surah_str_padded = str(surah_number).zfill(3)
|
| 274 |
surah_str_normal = str(surah_number)
|
| 275 |
+
|
|
|
|
| 276 |
audio_path = RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_padded}.mp3"
|
| 277 |
if audio_path.exists():
|
| 278 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 279 |
+
|
|
|
|
| 280 |
audio_path = RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_normal}.mp3"
|
| 281 |
if audio_path.exists():
|
| 282 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 283 |
+
|
|
|
|
| 284 |
old_dir_names = {
|
| 285 |
+
"yasser-al-dossari": "yasser_ad-dossary/mp3",
|
| 286 |
"abdul-baset": "abdul_baset",
|
| 287 |
"khalil-al-husary": "khalil_al_husary",
|
| 288 |
"siddiq-minshawi": "siddiq_minshawi"
|
| 289 |
}
|
| 290 |
+
|
| 291 |
if reciter_name in old_dir_names:
|
| 292 |
old_base_dir = RECITERS_DIR / old_dir_names[reciter_name]
|
|
|
|
| 293 |
if (old_base_dir / recitation_type).exists():
|
| 294 |
audio_path = old_base_dir / recitation_type / f"{surah_str_padded}.mp3"
|
| 295 |
if audio_path.exists():
|
|
|
|
| 298 |
if audio_path.exists():
|
| 299 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 300 |
else:
|
|
|
|
| 301 |
audio_path = old_base_dir / f"{surah_str_padded}.mp3"
|
| 302 |
if audio_path.exists():
|
| 303 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 304 |
audio_path = old_base_dir / f"{surah_str_normal}.mp3"
|
| 305 |
if audio_path.exists():
|
| 306 |
return FileResponse(audio_path, media_type="audio/mpeg")
|
| 307 |
+
|
| 308 |
raise HTTPException(status_code=404, detail="Audio file not found")
|
| 309 |
|
| 310 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
|
@@ -2,5 +2,5 @@ fastapi>=0.104.0
|
|
| 2 |
uvicorn[standard]>=0.24.0
|
| 3 |
scalar-fastapi>=1.0.0
|
| 4 |
python-multipart>=0.0.6
|
| 5 |
-
|
| 6 |
requests>=2.31.0
|
|
|
|
| 2 |
uvicorn[standard]>=0.24.0
|
| 3 |
scalar-fastapi>=1.0.0
|
| 4 |
python-multipart>=0.0.6
|
| 5 |
+
typing-inspect>=0.9.0
|
| 6 |
requests>=2.31.0
|