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

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from googlesearch import search
5
+ 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:
15
+ return detect(text)
16
+ except:
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(
79
+ messages=[
80
+ {"role": "system", "content": system_message},
81
+ {"role": "user", "content": question}
82
+ ],
83
+ max_tokens=1000,
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,
108
+ inputs=input_text,
109
+ outputs=[output_answer, output_source]
110
+ )
111
+
112
+ demo.queue().launch()