Spaces:
Running

yxqo41main commited on
Commit
bd010a5
·
verified ·
1 Parent(s): a9016b4

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +21 -0
  2. main.py +327 -0
  3. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.11-slim
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy the current directory contents into the container at /app
8
+ COPY . /app
9
+
10
+ # Install any needed packages specified in requirements.txt
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Make port 8000 available to the world outside this container
14
+ EXPOSE 8000
15
+
16
+ # Define environment variables
17
+ ENV NAME KalamalahQuranAPI
18
+ ENV USE_HF_CDN true
19
+
20
+ # Run uvicorn when the container launches
21
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
main.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
12
+ title="Kalamalah Quran API",
13
+ description="Official Kalamalah API for accessing Quran text and audio recitations",
14
+ version="1.0.0",
15
+ docs_url=None, # Disable default Swagger UI
16
+ redoc_url=None # Disable default ReDoc
17
+ )
18
+
19
+ # Add CORS middleware
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"], # Allow all origins
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ # Environment configuration
29
+ USE_HF_CDN = os.getenv("USE_HF_CDN", "false").lower() == "true"
30
+ HF_DATASET_URL = "https://huggingface.co/datasets/Kalamalah/cdn/raw/main"
31
+
32
+ # Base paths
33
+ BASE_DIR = Path(__file__).parent.parent
34
+ CDN_DIR = BASE_DIR / "cdn"
35
+ API_DATA_DIR = CDN_DIR / "api_data"
36
+ RECITERS_DIR = CDN_DIR / "reciters" / "audio"
37
+ MUSHAFS_DIR = CDN_DIR / "mushafs"
38
+
39
+ # Prevent hibernation - run a simple keep-alive task every 20 seconds
40
+ @app.on_event("startup")
41
+ @repeat_every(seconds=20) # Repeat every 20 seconds
42
+ def keep_alive():
43
+ # Just a simple log message to keep the app awake
44
+ print("Kalamalah API keep-alive tick")
45
+
46
+ # Reciter info (based on existing data)
47
+ RECITERS = {
48
+ "haitham-al-dukhin": {
49
+ "name": "Haitham Al Dokhin",
50
+ "arabic_name": "هيثم الدخين",
51
+ "types": ["murattal"]
52
+ },
53
+ "abdul-rashid-sofi": {
54
+ "name": "Abdul-Rashid Sofi",
55
+ "arabic_name": "عبد الرشيد الصوفي",
56
+ "types": ["murattal"]
57
+ },
58
+ "yasser-al-dossari": {
59
+ "name": "Yasser Al-Dossari",
60
+ "arabic_name": "ياسر الدوسري",
61
+ "types": ["murattal"]
62
+ },
63
+ "abdul-baset": {
64
+ "name": "Abdul Baset",
65
+ "arabic_name": "عبد الباسط عبد الصمد",
66
+ "types": ["mujawwad", "murattal"]
67
+ },
68
+ "khalil-al-husary": {
69
+ "name": "Khalil Al-Husary",
70
+ "arabic_name": "محمود خليل الحصري",
71
+ "types": ["murattal", "muallim"]
72
+ },
73
+ "siddiq-minshawi": {
74
+ "name": "Siddiq Minshawi",
75
+ "arabic_name": "محمد صديق المنشاوي",
76
+ "types": ["murattal", "kids-repeat"]
77
+ },
78
+ "hani-ar-rifai": {
79
+ "name": "Hani Ar-Rifai",
80
+ "arabic_name": "هاني الرفاعي",
81
+ "types": ["murattal"]
82
+ },
83
+ "abdurrahmaan-as-sudais": {
84
+ "name": "Abdurrahmaan As-Sudais",
85
+ "arabic_name": "عبد الرحمن السديس",
86
+ "types": ["murattal"]
87
+ },
88
+ "maher-al-muaiqly": {
89
+ "name": "Maher Al-Muaiqly",
90
+ "arabic_name": "ماهر المعيقلي",
91
+ "types": ["murattal"]
92
+ },
93
+ "ahmed-al-ajamy": {
94
+ "name": "Ahmed Al-Ajamy",
95
+ "arabic_name": "أحمد العجمي",
96
+ "types": ["murattal"]
97
+ },
98
+ "al-huzaifi": {
99
+ "name": "Al-Huzaifi",
100
+ "arabic_name": "الحوذيفي",
101
+ "types": ["ayah-by-ayah"]
102
+ }
103
+ }
104
+
105
+ # Load surahs data
106
+ SURAHS_DATA = None
107
+ try:
108
+ with open(API_DATA_DIR / "surahs.json", "r", encoding="utf-8") as f:
109
+ SURAHS_DATA = json.load(f)
110
+ except Exception:
111
+ pass
112
+
113
+ # Scalar documentation endpoint
114
+ @app.get("/docs", include_in_schema=False)
115
+ async def scalar_html():
116
+ return get_scalar_api_reference(
117
+ title=app.title,
118
+ openapi_url=app.openapi_url,
119
+ )
120
+
121
+ # Health check endpoint (for keep alive)
122
+ @app.get("/health")
123
+ async def health_check():
124
+ return {"status": "healthy"}
125
+
126
+ # Root endpoint
127
+ @app.get("/")
128
+ async def root():
129
+ return {
130
+ "message": "Welcome to Kalamalah Quran API!",
131
+ "docs": "/docs",
132
+ "endpoints": {
133
+ "quran": "/api/quran/{language}/{surah_number}[/{ayah_number}]",
134
+ "surahs_list": "/api/surahs",
135
+ "reciters": "/api/reciters",
136
+ "audio": "/api/{reciter_name}/{type}/{surah_number}",
137
+ "mushaf": "/api/mushaf/{mushaf_name}/{page_number}"
138
+ }
139
+ }
140
+
141
+ # Get list of all surahs
142
+ @app.get("/api/surahs")
143
+ async def get_surahs():
144
+ if USE_HF_CDN:
145
+ try:
146
+ hf_url = f"{HF_DATASET_URL}/api_data/surahs.json"
147
+ response = requests.get(hf_url, timeout=10)
148
+ response.raise_for_status()
149
+ data = response.json()
150
+ if data and data.get("code") == 200:
151
+ return JSONResponse(content=data["data"])
152
+ raise HTTPException(status_code=404, detail="Surahs data not found")
153
+ except Exception as e:
154
+ raise HTTPException(status_code=500, detail=str(e))
155
+ else:
156
+ if SURAHS_DATA and SURAHS_DATA.get("code") == 200:
157
+ return JSONResponse(content=SURAHS_DATA["data"])
158
+ raise HTTPException(status_code=404, detail="Surahs data not found")
159
+
160
+ # Get list of reciters
161
+ @app.get("/api/reciters")
162
+ async def get_reciters():
163
+ return JSONResponse(content=RECITERS)
164
+
165
+ # Get Quran text
166
+ @app.get("/api/quran/{language}/{surah_number}")
167
+ @app.get("/api/quran/{language}/{surah_number}/{ayah_number}")
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",
177
+ "tafsir": "ar.muyassar.json"
178
+ }
179
+ file_name = edition_map.get(language, f"{language}.json")
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):
193
+ return JSONResponse(content=ayahs[ayah_number - 1])
194
+ raise HTTPException(status_code=404, detail="Ayah not found")
195
+
196
+ return JSONResponse(content=data.get("data", data))
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",
209
+ "tafsir": "ar.muyassar.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
+ # 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 (put this first so it matches before the reciter audio endpoint!)
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-dussary/mp3",
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():
310
+ return FileResponse(audio_path, media_type="audio/mpeg")
311
+ audio_path = old_base_dir / recitation_type / f"{surah_str_normal}.mp3"
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__":
326
+ import uvicorn
327
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi>=0.104.0
2
+ uvicorn[standard]>=0.24.0
3
+ scalar-fastapi>=1.0.0
4
+ python-multipart>=0.0.6
5
+ fastapi-utils>=0.2.1
6
+ requests>=2.31.0