xTHExBEASTx commited on
Commit
c1ed215
·
verified ·
1 Parent(s): c4057d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -33
app.py CHANGED
@@ -6,9 +6,9 @@ from huggingface_hub import InferenceClient
6
  from langdetect import detect
7
  import os
8
 
9
- # إعداد العميل (استبدل TOKEN بـ Secret في إعدادات HF إذا لزم الأمر، أو سيتم استخدامه تلقائياً إذا كان الموديل عاماً)
10
- # سنستخدم Gemma 3 4B لسرعته وجودته العالية
11
- client = InferenceClient("google/gemma-3-4b-it")
12
 
13
  def get_language(text):
14
  try:
@@ -17,62 +17,76 @@ def get_language(text):
17
  return "ar"
18
 
19
  def search_islamweb(query):
20
- # حصر البحث في إسلام ويب فقط
21
  full_query = f"site:islamweb.net {query}"
22
  try:
23
- links = [j for j in search(full_query, num=3, stop=3, pause=2)]
 
 
 
 
24
  return links
25
- except:
 
26
  return []
27
 
28
  def scrape_content(url):
29
  try:
30
- headers = {'User-Agent': 'Mozilla/5.0'}
 
31
  response = requests.get(url, headers=headers, timeout=10)
32
  response.encoding = 'utf-8'
33
  soup = BeautifulSoup(response.text, 'html.parser')
34
 
35
- # استخراج متن الفتوى (هذا الـ Selector مناسب لبنية إسلام ويب الحالية)
36
- main_content = soup.find('div', {'class': 'item'})
37
- if not main_content:
38
- main_content = soup.find('div', {'id': 'fullitem'})
39
-
40
- return main_content.get_text(strip=True)[:4000] # نأخذ أول 4000 حرف للسياق
41
- except:
 
 
 
42
  return ""
43
 
44
  def islamic_ai_search(question):
 
 
 
 
45
  lang = get_language(question)
46
 
47
  # 1. البحث عن الروابط
48
  links = search_islamweb(question)
49
  if not links:
50
- return "عذراً، لم أجد نتائج في إسلام ويب لهذا السؤال. / Üzgünüm, bu soru için IslamWeb'de sonuç bulamadım.", ""
 
51
 
52
- # 2. استخراج السياق من أول رابط ناجح
53
  context = ""
54
  source_link = ""
55
  for link in links:
56
  content = scrape_content(link)
57
- if len(content) > 100:
58
  context = content
59
  source_link = link
60
  break
61
 
62
  if not context:
63
- return "تعذر استخراج محتوى مناسب من المصدر.", ""
 
64
 
65
- # 3. صياغة البرومبت المحكم (System Prompt) لعدم الهلوسة
66
  system_message = (
67
  "You are an expert Islamic researcher. Answer the user's question ONLY using the provided context from IslamWeb. "
68
  "Strict rules: \n"
69
  "1. If the answer is not in the context, say you don't know.\n"
70
- "2. You MUST answer in the same language as the user's question.\n"
71
- "3. Do not add outside information.\n"
72
  f"Context: {context}"
73
  )
74
 
75
- # 4. طلب الإجابة من النموذج
76
  response = ""
77
  try:
78
  for message in client.chat_completion(
@@ -84,24 +98,24 @@ def islamic_ai_search(question):
84
  stream=True,
85
  ):
86
  token = message.choices[0].delta.content
87
- response += token
88
- yield response, source_link
 
89
  except Exception as e:
90
- yield f"خطأ في الاتصال بالنموذج: {str(e)}", source_link
 
91
 
92
- # إعداد واجهة Gradio
93
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="green")) as demo:
94
- gr.Markdown("# 🕋 الباحث الإسلامي الذكي (مرجع إسلام ويب)")
95
- gr.Markdown("اسأل أي سؤال ديني، وسيقوم الذكاء الاصطناعي بالبحث في إسلام ويب وتلخيص الإجابة لك.")
96
 
97
  with gr.Row():
98
- input_text = gr.Textbox(label="سؤالك / Sorunuz", placeholder="مثلاً: ما حكم صلاة الوتر؟")
99
 
100
  submit_btn = gr.Button("بحث وتحليل", variant="primary")
101
 
102
- with gr.Column():
103
- output_answer = gr.Markdown(label="الإجابة")
104
- output_source = gr.Textbox(label="المصدر الأصلي (إسلام ويب)")
105
 
106
  submit_btn.click(
107
  fn=islamic_ai_search,
 
6
  from langdetect import detect
7
  import os
8
 
9
+ # محاولة جلب التوكن من الإعدادات
10
+ hf_token = os.getenv("HF_TOKEN")
11
+ client = InferenceClient("google/gemma-3-4b-it", token=hf_token)
12
 
13
  def get_language(text):
14
  try:
 
17
  return "ar"
18
 
19
  def search_islamweb(query):
20
+ print(f"جاري البحث عن: {query}") # تظهر في سجلات الـ Logs
21
  full_query = f"site:islamweb.net {query}"
22
  try:
23
+ # تقليل عدد النتائج لسرعة الاستجابة وتجنب الحظر
24
+ links = []
25
+ for j in search(full_query, num=3, stop=3, pause=2):
26
+ links.append(j)
27
+ print(f"الروابط المستخرجة: {links}")
28
  return links
29
+ except Exception as e:
30
+ print(f"فشل البحث في جوجل: {e}")
31
  return []
32
 
33
  def scrape_content(url):
34
  try:
35
+ print(f"جاري استخراج محتوى: {url}")
36
+ headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
37
  response = requests.get(url, headers=headers, timeout=10)
38
  response.encoding = 'utf-8'
39
  soup = BeautifulSoup(response.text, 'html.parser')
40
 
41
+ # بنية إسلام ويب قد تختلف، نحاول أكثر من مكان
42
+ main_content = soup.find('div', {'class': 'item'}) or soup.find('div', {'id': 'fullitem'}) or soup.find('article')
43
+
44
+ if main_content:
45
+ text = main_content.get_text(strip=True)[:4000]
46
+ print("تم استخراج النص بنجاح.")
47
+ return text
48
+ return ""
49
+ except Exception as e:
50
+ print(f"فشل الاستخراج: {e}")
51
  return ""
52
 
53
  def islamic_ai_search(question):
54
+ if not question.strip():
55
+ yield "الرجاء كتابة سؤال أولاً.", ""
56
+ return
57
+
58
  lang = get_language(question)
59
 
60
  # 1. البحث عن الروابط
61
  links = search_islamweb(question)
62
  if not links:
63
+ yield "عذراً، جوجل حظر طلب البحث حالياً. جرب مرة أخرى بعد قليل أو تأكد من إعدادات البحث.", ""
64
+ return
65
 
66
+ # 2. استخراج السياق
67
  context = ""
68
  source_link = ""
69
  for link in links:
70
  content = scrape_content(link)
71
+ if len(content) > 150:
72
  context = content
73
  source_link = link
74
  break
75
 
76
  if not context:
77
+ yield "لم أتمكن من قراءة محتوى الفتوى من الروابط الموجودة.", ""
78
+ return
79
 
80
+ # 3. نظام الرسائل للنموذج
81
  system_message = (
82
  "You are an expert Islamic researcher. Answer the user's question ONLY using the provided context from IslamWeb. "
83
  "Strict rules: \n"
84
  "1. If the answer is not in the context, say you don't know.\n"
85
+ "2. Response language MUST be the same as input question language.\n"
 
86
  f"Context: {context}"
87
  )
88
 
89
+ # 4. طلب الإجابة (Streaming)
90
  response = ""
91
  try:
92
  for message in client.chat_completion(
 
98
  stream=True,
99
  ):
100
  token = message.choices[0].delta.content
101
+ if token:
102
+ response += token
103
+ yield response, source_link
104
  except Exception as e:
105
+ print(f"خطأ الـ AI: {e}")
106
+ yield f"حدث خطأ أثناء توليد الإجابة. تأكد من إضافة HF_TOKEN في الـ Secrets. الخطأ: {e}", source_link
107
 
108
+ # واجهة Gradio
109
+ with gr.Blocks() as demo:
110
+ gr.Markdown("# 🕋 الباحث الإسلامي الذكي")
 
111
 
112
  with gr.Row():
113
+ input_text = gr.Textbox(label="سؤالك / Sorunuz")
114
 
115
  submit_btn = gr.Button("بحث وتحليل", variant="primary")
116
 
117
+ output_answer = gr.Markdown(label="الإجابة")
118
+ output_source = gr.Textbox(label="المصدر الأصلي")
 
119
 
120
  submit_btn.click(
121
  fn=islamic_ai_search,