youssefreda9 commited on
Commit
0c80121
·
1 Parent(s): b987dcf

feat: Quran verification & translation endpoint + modal UI (13 languages)

Browse files
Files changed (9) hide show
  1. .gitignore +0 -4
  2. READMEquran.md +64 -0
  3. inference_hf.py +69 -0
  4. quran.py +355 -0
  5. quran_master.db +3 -0
  6. requirements.txt +1 -0
  7. src/app.py +49 -0
  8. src/css/components.css +94 -0
  9. src/index.html +141 -1
.gitignore CHANGED
@@ -38,7 +38,3 @@ node_modules/
38
  # Test artifacts
39
  .pytest_cache/
40
  test-results/
41
-
42
-
43
- quran_master.db
44
- quran.py
 
38
  # Test artifacts
39
  .pytest_cache/
40
  test-results/
 
 
 
 
READMEquran.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bayan Search API
2
+
3
+ ## Supported Languages
4
+
5
+ The `search_bayan()` function supports the following values for the `target_type` parameter:
6
+
7
+ ```python
8
+ languages = [
9
+ "تدقيق الايات",
10
+ "english",
11
+ "french",
12
+ "turkish",
13
+ "persian",
14
+ "urdu",
15
+ "russian",
16
+ "spanish",
17
+ "german",
18
+ "indonesian",
19
+ "malay",
20
+ "bengali",
21
+ "bosnian",
22
+ "portuguese",
23
+ "uzbek"
24
+ ]
25
+ ```
26
+
27
+ ## Language Descriptions
28
+
29
+ | Value | Output |
30
+ | ------------ | ------------------------------------- |
31
+ | تدقيق الايات | Quran text in Uthmani script (Arabic) |
32
+ | english | English translation |
33
+ | french | French translation |
34
+ | turkish | Turkish translation |
35
+ | persian | Persian (Farsi) translation |
36
+ | urdu | Urdu translation |
37
+ | russian | Russian translation |
38
+ | spanish | Spanish translation |
39
+ | german | German translation |
40
+ | indonesian | Indonesian translation |
41
+ | malay | Malay translation |
42
+ | bengali | Bengali translation |
43
+ | bosnian | Bosnian translation |
44
+ | portuguese | Portuguese translation |
45
+ | uzbek | Uzbek translation |
46
+
47
+ ## Example Usage
48
+
49
+ ```python
50
+ result = search_bayan(
51
+ "ولله المشرق والمغرب فأينما تولوا فثم وجه الله",
52
+ target_type="english"
53
+ )
54
+
55
+ print(result["matched_segment"])
56
+ print(result["full_verse"])
57
+ ```
58
+
59
+ ## Notes
60
+
61
+ * If `target_type` is omitted, the default value is `"تدقيق الايات"`.
62
+ * The search engine supports fuzzy matching and can handle minor spelling mistakes.
63
+ * Quranic Uthmani text is returned when using `"تدقيق الايات"`.
64
+ * Translations are returned when using any of the supported language names above.
inference_hf.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example usage:
3
+ from bayan_inference_hf import BayanConverter
4
+ converter = BayanConverter()
5
+ result = converter.convert("عايز اشتكي من موظف في فرعكم")
6
+ print(result)
7
+ """
8
+
9
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
10
+ import torch
11
+
12
+ class BayanConverter:
13
+ PREFIX = "حوّل إلى الفصحى: "
14
+ REPO_ID = "bayan10/dialect-to-msa-model" # ← الموديل على HuggingFace Hub
15
+
16
+ def __init__(self, model_path: str = None, device: str = None):
17
+ """
18
+ model_path: لو None، بيحمّل من HuggingFace Hub (bayan10/dialect-to-msa-model)
19
+ لو حددت مسار محلي، بيحمّل من هناك بدل كده
20
+ """
21
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
22
+ source = model_path or self.REPO_ID
23
+
24
+ print(f"Loading model from '{source}' on {self.device}...")
25
+ self.tokenizer = AutoTokenizer.from_pretrained(source)
26
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(source).to(self.device)
27
+ self.model.eval()
28
+ print("Ready.")
29
+
30
+ def convert(self, dialect_text: str, num_beams: int = 4) -> str:
31
+ """تحويل جملة عامية واحدة إلى الفصحى الحديثة."""
32
+ input_text = self.PREFIX + dialect_text
33
+ inputs = self.tokenizer(
34
+ input_text,
35
+ return_tensors="pt",
36
+ max_length=128,
37
+ truncation=True,
38
+ ).to(self.device)
39
+
40
+ with torch.no_grad():
41
+ outputs = self.model.generate(
42
+ **inputs,
43
+ max_length=128,
44
+ num_beams=num_beams,
45
+ early_stopping=True,
46
+ no_repeat_ngram_size=3,
47
+ )
48
+ return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
49
+
50
+ def convert_batch(self, texts: list[str], num_beams: int = 4) -> list[str]:
51
+ """تحويل مجموعة جمل دفعة واحدة (أسرع من واحدة واحدة)."""
52
+ inputs_list = [self.PREFIX + t for t in texts]
53
+ inputs = self.tokenizer(
54
+ inputs_list,
55
+ return_tensors="pt",
56
+ max_length=128,
57
+ truncation=True,
58
+ padding=True,
59
+ ).to(self.device)
60
+
61
+ with torch.no_grad():
62
+ outputs = self.model.generate(
63
+ **inputs,
64
+ max_length=128,
65
+ num_beams=num_beams,
66
+ early_stopping=True,
67
+ no_repeat_ngram_size=3,
68
+ )
69
+ return self.tokenizer.batch_decode(outputs, skip_special_tokens=True)
quran.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Quran.py
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1WwaR-xsFnY5iffCndJV5metzB0RS4_GP
8
+ """
9
+
10
+ import sqlite3
11
+ import re
12
+ from rapidfuzz.distance import Levenshtein
13
+
14
+ # ==========================================
15
+ # طبقة التطبيع الموسعة
16
+ # ==========================================
17
+
18
+ # مجموعات الحروف المتشابهة بصرياً أو صوتياً — كلها ترجع لشكل واحد
19
+ _SIMILAR_GROUPS = [
20
+ ('اأإآٱ', 'ا'),
21
+ ('ةه', 'ه'),
22
+ ('يىئ', 'ي'),
23
+ ('وؤ', 'و'),
24
+ ('ذد', 'د'), # متقاربة بصرياً للمبتدئين
25
+ ('زرذ', 'ر'), # أحياناً يخلط المستخدم بينها
26
+ ('طت', 'ت'),
27
+ ('ضظ', 'ض'),
28
+ ('سص', 'س'),
29
+ ('ثت', 'ت'),
30
+ ('خح', 'ح'),
31
+ ('غع', 'ع'),
32
+ ]
33
+
34
+ def _build_similarity_table():
35
+ table = {}
36
+ for group, canonical in _SIMILAR_GROUPS:
37
+ for ch in group:
38
+ table[ch] = canonical
39
+ return table
40
+
41
+ _SIM_TABLE = _build_similarity_table()
42
+
43
+ def normalize_arabic(text: str, *, deep: bool = False) -> str:
44
+ """
45
+ تطبيع النص العربي.
46
+ deep=False → تطبيع خفيف (للتخزين في DB أو المقارنة الدقيقة)
47
+ deep=True → تطبيع عميق يساوي بين الحروف المتشابهة (للبحث الضبابي)
48
+ """
49
+ if not text:
50
+ return ""
51
+ # إزالة التشكيل والعلامات القرآنية
52
+ text = re.sub(
53
+ r'[\u064B-\u065F\u0670\u0671\u0656'
54
+ r'\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]',
55
+ '', text
56
+ )
57
+ # همزات
58
+ text = re.sub(r'[أإآٱ]', 'ا', text)
59
+ # تاء مربوطة
60
+ text = re.sub(r'ة', 'ه', text)
61
+ # ألف مقصورة
62
+ text = re.sub(r'ى', 'ي', text)
63
+
64
+ if deep:
65
+ text = ''.join(_SIM_TABLE.get(ch, ch) for ch in text)
66
+
67
+ return ' '.join(text.strip().split())
68
+
69
+
70
+ # ==========================================
71
+ # مطابقة ضبابية على مستوى الكلمات
72
+ # ==========================================
73
+
74
+ def _word_similarity(a: str, b: str) -> float:
75
+ """نسبة التشابه بين كلمتين (0.0 → 1.0)."""
76
+ max_len = max(len(a), len(b), 1)
77
+ dist = Levenshtein.distance(a, b)
78
+ return 1.0 - dist / max_len
79
+
80
+
81
+ def _score_window(query_words: list[str], window_words: list[str],
82
+ query_deep: list[str], window_deep: list[str]) -> float:
83
+ """
84
+ احسب نسبة تطابق نافذة كلمات مع استعلام المستخدم.
85
+ نستخدم نسختين: خفيفة (أولوية) وعميقة (احتياط).
86
+ """
87
+ if len(window_words) != len(query_words):
88
+ return 0.0
89
+
90
+ total = 0.0
91
+ for qw, ww, qd, wd in zip(query_words, window_words, query_deep, window_deep):
92
+ # نأخذ أعلى نتيجة بين المقارنة الخفيفة والعميقة
93
+ s_light = _word_similarity(qw, ww)
94
+ s_deep = _word_similarity(qd, wd)
95
+ total += max(s_light, s_deep)
96
+
97
+ return total / len(query_words)
98
+
99
+
100
+ # ==========================================
101
+ # الدالة الرئيسية
102
+ # ==========================================
103
+
104
+ def search_bayan(query_text: str,
105
+ target_type: str = "تدقيق الايات",
106
+ fuzzy_threshold: float = 0.72,
107
+ db_path: str = None) -> dict:
108
+ """
109
+ البحث عن آية قرآنية مع دعم الأخطاء الإملائية.
110
+
111
+ المعاملات:
112
+ query_text : النص المُدخَل من المستخدم (قد يحتوي أخطاء)
113
+ target_type : لغة الإخراج (uthmani / english / french / ...)
114
+ fuzzy_threshold : الحد الأدنى لقبول التطابق (0→1)، افتراضياً 0.72
115
+ db_path : مسار ملف قاعدة البيانات (افتراضياً بجوار هذا الملف)
116
+
117
+ المُخرج:
118
+ dict يحتوي على:
119
+ matched_segment : النص المُصحَّح بالرسم العثماني أو الترجمة
120
+ full_verse : الآيات كاملة مع التوثيق
121
+ similarity_score : درجة التشابه
122
+ metadata : تفاصيل الآيات
123
+ أو:
124
+ error : رسالة الخطأ
125
+ """
126
+ import os
127
+ if db_path is None:
128
+ db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'quran_master.db')
129
+ conn = sqlite3.connect(db_path)
130
+ cursor = conn.cursor()
131
+
132
+ language_mapping = {
133
+ "تدقيق الايات": "uthmani",
134
+ "bengali": "bn", "bosnian": "bs", "english": "en", "french": "fr",
135
+ "german": "de", "indonesian": "id", "malay": "ms", "persian": "fa",
136
+ "portuguese": "pt", "russian": "ru", "spanish": "es",
137
+ "turkish": "tr", "uzbek": "uz"
138
+ }
139
+
140
+ clean_target = str(target_type).lower().strip()
141
+ lang_code = language_mapping.get(clean_target, "uthmani")
142
+
143
+ verse_column = "v.text_uthmani" if lang_code == "uthmani" else f"v.lang_{lang_code}"
144
+ sura_column = "s.ar" if lang_code == "uthmani" else f"s.lang_{lang_code}"
145
+
146
+ # ── تطبيع الاستعلام بنسختين ──
147
+ query_light = normalize_arabic(query_text, deep=False).split()
148
+ query_deep = normalize_arabic(query_text, deep=True).split()
149
+
150
+ if not query_light:
151
+ conn.close()
152
+ return {"error": "النص المُدخل فارغ"}
153
+
154
+ n = len(query_light)
155
+
156
+ # ==========================================
157
+ # البحث بالمرساة الديناميكية (من الأطول للأقصر)
158
+ # ==========================================
159
+ candidate_starts: list[tuple[int, int]] = []
160
+
161
+ for i in range(n, 0, -1):
162
+ anchor = ' '.join(query_light[:i])
163
+ # بحث LIKE عادي أولاً (سريع)
164
+ cursor.execute("""
165
+ SELECT v.sura_num, v.aya_num
166
+ FROM verses v
167
+ WHERE v.text_clean LIKE ?
168
+ ORDER BY v.sura_num, v.aya_num
169
+ """, ('%' + anchor + '%',))
170
+ candidate_starts = cursor.fetchall()
171
+ if candidate_starts:
172
+ break
173
+
174
+ # إذا لم تجد شيئاً بالمرساة الخفيفة → جرّب المرساة العميقة
175
+ # (يستخدم text_deep إذا كان موجوداً، وإلا يعود لـ text_clean)
176
+ if not candidate_starts:
177
+ # اكتشف أعمدة الجدول
178
+ cursor.execute("PRAGMA table_info(verses)")
179
+ cols = {row[1] for row in cursor.fetchall()}
180
+ deep_col = "v.text_deep" if "text_deep" in cols else "v.text_clean"
181
+
182
+ for i in range(n, 0, -1):
183
+ anchor_deep = ' '.join(query_deep[:i])
184
+ cursor.execute(f"""
185
+ SELECT v.sura_num, v.aya_num
186
+ FROM verses v
187
+ WHERE {deep_col} LIKE ?
188
+ ORDER BY v.sura_num, v.aya_num
189
+ """, ('%' + anchor_deep + '%',))
190
+ rows = cursor.fetchall()
191
+ if rows:
192
+ candidate_starts = rows
193
+ break
194
+
195
+ # الملاذ الأخير: ابحث بكل كلمة على حدة وخذ الآيات الأكثر تكراراً
196
+ if not candidate_starts:
197
+ counts: dict[tuple, int] = {}
198
+ for word in query_light:
199
+ if len(word) < 3:
200
+ continue
201
+ cursor.execute("""
202
+ SELECT v.sura_num, v.aya_num
203
+ FROM verses v
204
+ WHERE v.text_clean LIKE ?
205
+ """, ('%' + word + '%',))
206
+ for row in cursor.fetchall():
207
+ counts[row] = counts.get(row, 0) + 1
208
+ if counts:
209
+ candidate_starts = sorted(counts, key=counts.get, reverse=True)[:15]
210
+
211
+ if not candidate_starts:
212
+ conn.close()
213
+ return {
214
+ "matched_segment": "",
215
+ "full_verse": "لم يُعثر على تطابق — تحقق من النص المُدخل"
216
+ }
217
+
218
+ # ==========================================
219
+ # النافذة المنزلقة + التقييم الضبابي
220
+ # ==========================================
221
+ best_score = -1.0
222
+ best_match_idx = -1
223
+ best_rows = None
224
+
225
+ for start_sura, start_aya in candidate_starts:
226
+ cursor.execute(f"""
227
+ SELECT v.sura_num, v.aya_num, v.text_clean,
228
+ v.text_uthmani, {verse_column}, {sura_column}
229
+ FROM verses v
230
+ JOIN suras_translated s ON v.sura_num = s.sura_number
231
+ WHERE (v.sura_num = ? AND v.aya_num >= ?) OR (v.sura_num > ?)
232
+ ORDER BY v.sura_num, v.aya_num
233
+ LIMIT 12
234
+ """, (start_sura, start_aya, start_sura))
235
+ fetched = cursor.fetchall()
236
+
237
+ QURAN_MARKS = {
238
+ 'ۖ', 'ۗ', 'ۘ', 'ۙ', 'ۚ', 'ۛ', 'ۜ', '۝',
239
+ '۞', '۩'
240
+ }
241
+
242
+
243
+ # بناء خريطة الكلمات
244
+ combined_light, combined_deep, word_map = [], [], []
245
+ for row in fetched:
246
+ s_num, a_num, t_clean, t_uthmani, t_target, s_name = row
247
+ clean_w = t_clean.split()
248
+ uthmani_w = [
249
+ token
250
+ for token in t_uthmani.split()
251
+ if token not in QURAN_MARKS
252
+ ]
253
+ deep_w = normalize_arabic(t_clean, deep=True).split()
254
+
255
+ for j, cw in enumerate(clean_w):
256
+ combined_light.append(cw)
257
+ combined_deep.append(deep_w[j] if j < len(deep_w) else cw)
258
+ word_map.append({
259
+ "clean": cw,
260
+ "uthmani": uthmani_w[j] if j < len(uthmani_w) else cw,
261
+ "sura_num": s_num,
262
+ "aya_num": a_num,
263
+ "target_text": t_target,
264
+ "sura_name": s_name,
265
+ })
266
+
267
+ total_words = len(combined_light)
268
+ if total_words < n:
269
+ continue
270
+
271
+ # نافذة منزلقة — ابحث عن أعلى نتيجة
272
+ for j in range(total_words - n + 1):
273
+ score = _score_window(
274
+ query_light, combined_light[j:j+n],
275
+ query_deep, combined_deep[j:j+n]
276
+ )
277
+ if score > best_score:
278
+ best_score = score
279
+ best_match_idx = j
280
+ best_rows = word_map
281
+
282
+ # إذا وجدنا تطابقاً كاملاً، لا داعي للاستمرار
283
+ if best_score >= 0.999:
284
+ break
285
+
286
+ conn.close()
287
+
288
+ # if best_score < fuzzy_threshold or best_match_idx == -1:
289
+ # return {
290
+ # "error": (
291
+ # f"أقرب تطابق وجدناه بدرجة {best_score:.0%} وهي أقل من الحد المقبول "
292
+ # f"({fuzzy_threshold:.0%}). تحقق من النص المُدخل."
293
+ # )
294
+ # }
295
+
296
+ # ==========================================
297
+ # تشكيل المخرجات
298
+ # ==========================================
299
+ matched_words = best_rows[best_match_idx: best_match_idx + n]
300
+
301
+ # بناء matched_segment مع رقم كل آية
302
+ aya_words: dict[tuple, list] = {}
303
+ for w in matched_words:
304
+ key = (w["sura_num"], w["aya_num"])
305
+ if key not in aya_words:
306
+ aya_words[key] = []
307
+ aya_words[key].append(w["uthmani"] if lang_code == "uthmani" else w["target_text"])
308
+
309
+ if lang_code == "uthmani":
310
+ seg_parts = [
311
+ " ".join(words) + f" ({a_num})"
312
+ for (_, a_num), words in aya_words.items()
313
+ ]
314
+ matched_segment = " ".join(seg_parts)
315
+ else:
316
+ # للترجمات: نص الآية كامل + رقمها (بدون تكرار)
317
+ seen_texts, seg_parts = set(), []
318
+ for (_, a_num), words in aya_words.items():
319
+ txt = words[0] # target_text مكرر لكل كلمة، نأخذ الأول
320
+ if txt not in seen_texts:
321
+ seen_texts.add(txt)
322
+ seg_parts.append(f"{txt} ({a_num})")
323
+ matched_segment = " ".join(seg_parts)
324
+
325
+ # الآيات المشمولة — مرتبة بالترتيب
326
+ involved: dict[tuple, dict] = {}
327
+ for w in matched_words:
328
+ key = (w["sura_num"], w["aya_num"])
329
+ if key not in involved:
330
+ involved[key] = {"sura_name": w["sura_name"], "target_text": w["target_text"]}
331
+
332
+ ayah_nums = [a_num for (_, a_num) in involved]
333
+ sura_name = next(iter(involved.values()))["sura_name"]
334
+
335
+ verse_body_parts = []
336
+ for (s_num, a_num), data in involved.items():
337
+ verse_body_parts.append(f"{data['target_text']} ({a_num})")
338
+
339
+ combined_body = " ".join(verse_body_parts)
340
+
341
+ if len(ayah_nums) == 1:
342
+ ref = f"{sura_name}: {ayah_nums[0]}"
343
+ else:
344
+ nums_str = "،".join(str(x) for x in ayah_nums)
345
+ ref = f"{sura_name}: {nums_str}"
346
+
347
+ full_verse_formatted = f"({combined_body}) [{ref}]"
348
+ matched_segment = f"({matched_segment}) [{ref}]"
349
+
350
+ is_exact = best_score >= 0.999
351
+ return {
352
+ "matched_segment": matched_segment,
353
+ "full_verse": full_verse_formatted,
354
+
355
+ }
quran_master.db ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8249c308936ddc26e70e46580405f7751d2c96501d1185f617ae9b0436e987a9
3
+ size 23064576
requirements.txt CHANGED
@@ -14,3 +14,4 @@ python-Levenshtein
14
  gunicorn
15
  python-dotenv
16
  gradio_client
 
 
14
  gunicorn
15
  python-dotenv
16
  gradio_client
17
+ rapidfuzz
src/app.py CHANGED
@@ -13,6 +13,15 @@ import traceback
13
  import difflib
14
  import re
15
 
 
 
 
 
 
 
 
 
 
16
  # Pipeline hardening modules
17
  from nlp.pipeline_context import PipelineContext
18
  from nlp.punctuation.punctuation_rules import validate_punctuation_diff
@@ -1059,6 +1068,46 @@ def _is_orthographic_variant(word1: str, word2: str) -> bool:
1059
  return diff_count > 0 # At least one orthographic difference
1060
 
1061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1062
  @app.route('/api/analyze', methods=['POST'])
1063
  def analyze_text():
1064
  """
 
13
  import difflib
14
  import re
15
 
16
+ # Quran search
17
+ import sys
18
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
19
+ try:
20
+ from quran import search_bayan
21
+ logger_quran_ok = True
22
+ except ImportError:
23
+ logger_quran_ok = False
24
+
25
  # Pipeline hardening modules
26
  from nlp.pipeline_context import PipelineContext
27
  from nlp.punctuation.punctuation_rules import validate_punctuation_diff
 
1068
  return diff_count > 0 # At least one orthographic difference
1069
 
1070
 
1071
+ @app.route('/api/quran', methods=['POST'])
1072
+ def quran_verify():
1073
+ """
1074
+ Quran text verification and translation.
1075
+ Accepts: {text: str, language: str (optional, default='تدقيق الايات')}
1076
+ Returns: {matched_segment, full_verse} or {error}
1077
+ """
1078
+ try:
1079
+ if not logger_quran_ok:
1080
+ return jsonify({'error': 'Quran search module not available'}), 503
1081
+
1082
+ data = request.get_json(force=True)
1083
+ text = data.get('text', '').strip()
1084
+ language = data.get('language', 'تدقيق الايات').strip()
1085
+
1086
+ if not text:
1087
+ return jsonify({'error': 'النص المُدخل فارغ'}), 400
1088
+
1089
+ if len(text) > 2000:
1090
+ return jsonify({'error': 'النص طويل جداً (الحد الأقصى 2000 حرف)'}), 400
1091
+
1092
+ app.logger.info(f'[QURAN] Query: "{text[:60]}..." lang={language}')
1093
+ start_time = time.time()
1094
+
1095
+ result = search_bayan(text, target_type=language)
1096
+
1097
+ elapsed = int((time.time() - start_time) * 1000)
1098
+ app.logger.info(f'[QURAN] Done in {elapsed}ms')
1099
+
1100
+ if 'error' in result:
1101
+ return jsonify(result), 404
1102
+
1103
+ return jsonify(result)
1104
+
1105
+ except Exception as e:
1106
+ app.logger.error(f'[QURAN] Error: {e}')
1107
+ app.logger.error(traceback.format_exc())
1108
+ return jsonify({'error': 'حدث خطأ أثناء البحث في القرآن الكريم'}), 500
1109
+
1110
+
1111
  @app.route('/api/analyze', methods=['POST'])
1112
  def analyze_text():
1113
  """
src/css/components.css CHANGED
@@ -3052,3 +3052,97 @@ input[type="range"]::-moz-range-thumb {
3052
  display: none !important;
3053
  }
3054
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3052
  display: none !important;
3053
  }
3054
  }
3055
+
3056
+ /* ── Quran Verification Modal ── */
3057
+ .quran-modal {
3058
+ position: fixed;
3059
+ inset: 0;
3060
+ z-index: 1000;
3061
+ display: flex;
3062
+ align-items: center;
3063
+ justify-content: center;
3064
+ padding: 1rem;
3065
+ }
3066
+ .quran-modal.is-hidden { display: none; }
3067
+
3068
+ .quran-modal-backdrop {
3069
+ position: absolute;
3070
+ inset: 0;
3071
+ background: rgba(0, 0, 0, 0.6);
3072
+ backdrop-filter: blur(6px);
3073
+ -webkit-backdrop-filter: blur(6px);
3074
+ }
3075
+
3076
+ .quran-modal-panel {
3077
+ position: relative;
3078
+ width: 100%;
3079
+ max-width: 580px;
3080
+ max-height: 85vh;
3081
+ overflow-y: auto;
3082
+ background: var(--color-surface);
3083
+ border-radius: 1.5rem;
3084
+ border: 1px solid var(--color-border);
3085
+ padding: 1.5rem;
3086
+ box-shadow: 0 25px 60px rgba(0, 0, 0, 0.35);
3087
+ animation: quranModalIn 0.25s ease-out;
3088
+ }
3089
+
3090
+ @keyframes quranModalIn {
3091
+ from { opacity: 0; transform: scale(0.95) translateY(10px); }
3092
+ to { opacity: 1; transform: scale(1) translateY(0); }
3093
+ }
3094
+
3095
+ .quran-result-card {
3096
+ background: rgba(6, 182, 212, 0.08);
3097
+ border-right: 4px solid #06b6d4;
3098
+ border-radius: 0.75rem;
3099
+ padding: 1.25rem;
3100
+ }
3101
+
3102
+ .quran-uthmani {
3103
+ font-family: 'Traditional Arabic', 'Amiri', 'Scheherazade New', serif;
3104
+ font-size: 24px;
3105
+ line-height: 2.2;
3106
+ color: var(--color-text-primary);
3107
+ text-align: center;
3108
+ direction: rtl;
3109
+ }
3110
+
3111
+ .quran-reference {
3112
+ color: var(--text-secondary);
3113
+ font-size: 14px;
3114
+ text-align: center;
3115
+ margin-top: 8px;
3116
+ font-weight: 600;
3117
+ }
3118
+
3119
+ .quran-lang-select {
3120
+ padding: 6px 12px;
3121
+ border-radius: 8px;
3122
+ border: 1px solid var(--color-border);
3123
+ background: var(--color-surface);
3124
+ color: var(--color-text-primary);
3125
+ font-size: 14px;
3126
+ font-family: inherit;
3127
+ cursor: pointer;
3128
+ transition: border-color 0.2s;
3129
+ }
3130
+ .quran-lang-select:hover {
3131
+ border-color: #06b6d4;
3132
+ }
3133
+ .quran-lang-select:focus {
3134
+ outline: none;
3135
+ border-color: #06b6d4;
3136
+ box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15);
3137
+ }
3138
+
3139
+ @media (max-width: 640px) {
3140
+ .quran-modal-panel {
3141
+ max-width: 100%;
3142
+ border-radius: 1.25rem;
3143
+ padding: 1.25rem;
3144
+ }
3145
+ .quran-uthmani {
3146
+ font-size: 20px;
3147
+ }
3148
+ }
src/index.html CHANGED
@@ -1194,7 +1194,96 @@
1194
  }
1195
  function convertDialect(){var i=document.getElementById('dialect-input').value.trim();if(!i){if(typeof showToast==='function')showToast('الرجاء كتابة نص أولاً');return;}var r=document.getElementById('dialect-result-card');var d=document.getElementById('dialect-result');d.innerHTML='<p class="text-secondary text-center">⏳ جاري التحويل...</p>';r.classList.remove('is-hidden');setTimeout(function(){d.innerHTML='<p class="text-secondary text-center">🚧 هذه الميزة قيد التطوير — ستتوفر قريبًا</p>';},1000);}
1196
  function copyDialectResult(){var t=document.getElementById('dialect-result');if(t){navigator.clipboard.writeText(t.innerText);if(typeof showToast==='function')showToast('✓ تم النسخ');}}
1197
- function verifyQuranText(){var s=window.getSelection();var t=s?s.toString().trim():'';if(!t){if(typeof showToast==='function')showToast('علّم على النص القرآني أولاً');return;}if(typeof showToast==='function')showToast('🚧 تدقيق النص القرآني — قيد التطوير');}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1198
 
1199
 
1200
 
@@ -1555,5 +1644,56 @@
1555
  }
1556
  });
1557
  </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1558
  </body>
1559
  </html>
 
1194
  }
1195
  function convertDialect(){var i=document.getElementById('dialect-input').value.trim();if(!i){if(typeof showToast==='function')showToast('الرجاء كتابة نص أولاً');return;}var r=document.getElementById('dialect-result-card');var d=document.getElementById('dialect-result');d.innerHTML='<p class="text-secondary text-center">⏳ جاري التحويل...</p>';r.classList.remove('is-hidden');setTimeout(function(){d.innerHTML='<p class="text-secondary text-center">🚧 هذه الميزة قيد التطوير — ستتوفر قريبًا</p>';},1000);}
1196
  function copyDialectResult(){var t=document.getElementById('dialect-result');if(t){navigator.clipboard.writeText(t.innerText);if(typeof showToast==='function')showToast('✓ تم النسخ');}}
1197
+
1198
+ /* ═══════════════════════════════════════════
1199
+ Quran Verification & Translation
1200
+ ═══════════════════════════════════════════ */
1201
+ let _quranCurrentQuery = '';
1202
+
1203
+ async function verifyQuranText() {
1204
+ const sel = window.getSelection();
1205
+ const text = sel ? sel.toString().trim() : '';
1206
+ if (!text) {
1207
+ if (typeof showToast === 'function') showToast('علّم على النص القرآني أولاً');
1208
+ return;
1209
+ }
1210
+ _quranCurrentQuery = text;
1211
+
1212
+ // Show modal with loading
1213
+ const modal = document.getElementById('quran-modal');
1214
+ document.getElementById('quran-input-display').textContent = text;
1215
+ document.getElementById('quran-uthmani-text').innerHTML = '<span class="text-secondary">⏳ جاري البحث...</span>';
1216
+ document.getElementById('quran-reference').textContent = '';
1217
+ document.getElementById('quran-translation-result').classList.add('is-hidden');
1218
+ document.getElementById('quran-lang-select').value = '';
1219
+ modal.classList.remove('is-hidden');
1220
+ document.body.style.overflow = 'hidden';
1221
+
1222
+ try {
1223
+ const res = await fetch('/api/quran', {
1224
+ method: 'POST',
1225
+ headers: { 'Content-Type': 'application/json' },
1226
+ body: JSON.stringify({ text: text, language: 'تدقيق الايات' })
1227
+ });
1228
+ const data = await res.json();
1229
+
1230
+ if (data.error) {
1231
+ document.getElementById('quran-uthmani-text').innerHTML =
1232
+ '<span class="text-secondary">' + data.error + '</span>';
1233
+ return;
1234
+ }
1235
+
1236
+ // Parse matched_segment: "(verse text) [surah: ayah]"
1237
+ const seg = data.matched_segment || '';
1238
+ const refMatch = seg.match(/\[([^\]]+)\]/);
1239
+ const verseText = seg.replace(/\s*\[[^\]]+\]\s*$/, '').replace(/^\(/, '').replace(/\)$/, '');
1240
+ const reference = refMatch ? refMatch[1] : '';
1241
+
1242
+ document.getElementById('quran-uthmani-text').textContent = verseText;
1243
+ document.getElementById('quran-reference').textContent = reference ? '[' + reference + ']' : '';
1244
+
1245
+ } catch (err) {
1246
+ document.getElementById('quran-uthmani-text').innerHTML =
1247
+ '<span class="text-secondary">حدث خطأ أثناء البحث — تأكد من الاتصال</span>';
1248
+ }
1249
+ }
1250
+
1251
+ async function translateQuranVerse() {
1252
+ const lang = document.getElementById('quran-lang-select').value;
1253
+ if (!lang || !_quranCurrentQuery) return;
1254
+
1255
+ const resultDiv = document.getElementById('quran-translation-result');
1256
+ const textEl = document.getElementById('quran-translation-text');
1257
+ textEl.innerHTML = '<span class="text-secondary">⏳ جاري الترجمة...</span>';
1258
+ resultDiv.classList.remove('is-hidden');
1259
+
1260
+ try {
1261
+ const res = await fetch('/api/quran', {
1262
+ method: 'POST',
1263
+ headers: { 'Content-Type': 'application/json' },
1264
+ body: JSON.stringify({ text: _quranCurrentQuery, language: lang })
1265
+ });
1266
+ const data = await res.json();
1267
+
1268
+ if (data.error) {
1269
+ textEl.innerHTML = '<span class="text-secondary">' + data.error + '</span>';
1270
+ return;
1271
+ }
1272
+
1273
+ // Parse translation text (remove brackets)
1274
+ const seg = data.matched_segment || '';
1275
+ const transText = seg.replace(/\s*\[[^\]]+\]\s*$/, '').replace(/^\(/, '').replace(/\)$/, '');
1276
+ textEl.textContent = transText;
1277
+
1278
+ } catch (err) {
1279
+ textEl.innerHTML = '<span class="text-secondary">حدث خطأ في الترجمة</span>';
1280
+ }
1281
+ }
1282
+
1283
+ function closeQuranModal() {
1284
+ document.getElementById('quran-modal').classList.add('is-hidden');
1285
+ document.body.style.overflow = '';
1286
+ }
1287
 
1288
 
1289
 
 
1644
  }
1645
  });
1646
  </script>
1647
+ <!-- Quran Verification Modal -->
1648
+ <div id="quran-modal" class="quran-modal is-hidden" role="dialog" aria-label="نتيجة التدقيق القرآني" aria-modal="true">
1649
+ <div class="quran-modal-backdrop" onclick="closeQuranModal()"></div>
1650
+ <div class="quran-modal-panel" dir="rtl">
1651
+ <!-- Header -->
1652
+ <div class="flex items-center justify-between mb-4">
1653
+ <div class="flex items-center gap-2">
1654
+ <svg width="20" height="20" fill="none" stroke="#06b6d4" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg>
1655
+ <span class="text-lg font-bold">تدقيق النص القرآني</span>
1656
+ </div>
1657
+ <button onclick="closeQuranModal()" class="btn-ghost" style="font-size:18px;padding:4px 8px;" aria-label="إغلاق">✕</button>
1658
+ </div>
1659
+ <!-- Input text -->
1660
+ <div class="p-3 rounded-xl mb-4" style="background: rgba(255,255,255,0.04); border: 1px solid var(--color-border);">
1661
+ <span class="text-xs" style="color:var(--text-secondary);">📝 النص المحدد:</span>
1662
+ <p id="quran-input-display" class="text-base mt-1" style="color:var(--color-text-primary);"></p>
1663
+ </div>
1664
+ <!-- Uthmani Result -->
1665
+ <div class="quran-result-card">
1666
+ <div class="text-sm font-bold mb-3" style="color:#06b6d4;">✓ النص القرآني المدقق</div>
1667
+ <p id="quran-uthmani-text" class="quran-uthmani"></p>
1668
+ <p id="quran-reference" class="quran-reference"></p>
1669
+ </div>
1670
+ <!-- Translation -->
1671
+ <div class="mt-4 pt-4" style="border-top:1px solid var(--color-border);">
1672
+ <div class="flex items-center gap-3 mb-3 flex-wrap">
1673
+ <svg width="16" height="16" fill="none" stroke="#06b6d4" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"/></svg>
1674
+ <span class="text-sm font-bold">ترجمة الآية</span>
1675
+ <select id="quran-lang-select" onchange="translateQuranVerse()" class="quran-lang-select">
1676
+ <option value="">— اختر لغة —</option>
1677
+ <option value="english">🇬🇧 English</option>
1678
+ <option value="french">🇫🇷 Français</option>
1679
+ <option value="turkish">🇹🇷 Türkçe</option>
1680
+ <option value="persian">🇮🇷 فارسی</option>
1681
+ <option value="russian">🇷🇺 Русский</option>
1682
+ <option value="spanish">🇪🇸 Español</option>
1683
+ <option value="german">🇩🇪 Deutsch</option>
1684
+ <option value="indonesian">🇮🇩 Indonesia</option>
1685
+ <option value="malay">🇲🇾 Melayu</option>
1686
+ <option value="bengali">🇧🇩 বাংলা</option>
1687
+ <option value="bosnian">🇧🇦 Bosanski</option>
1688
+ <option value="portuguese">🇵🇹 Português</option>
1689
+ <option value="uzbek">🇺🇿 O'zbek</option>
1690
+ </select>
1691
+ </div>
1692
+ <div id="quran-translation-result" class="is-hidden p-4 rounded-xl" style="background:rgba(6,182,212,0.06); border:1px solid rgba(6,182,212,0.15);">
1693
+ <p id="quran-translation-text" class="text-base" style="line-height:1.9; color:var(--color-text-primary);"></p>
1694
+ </div>
1695
+ </div>
1696
+ </div>
1697
+ </div>
1698
  </body>
1699
  </html>