Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -5,46 +5,42 @@ from sentence_transformers import SentenceTransformer
|
|
5 |
import json
|
6 |
from dspy import Example, MIPROv2, Evaluate, evaluate
|
7 |
|
8 |
-
# إعداد نموذج
|
9 |
dspy.settings.configure(lm=dspy.LM("mistralai/Mistral-7B-Instruct-v0.2"))
|
10 |
|
11 |
-
# إعداد
|
12 |
client = chromadb.PersistentClient(path="./chroma_db")
|
13 |
col = client.get_or_create_collection(name="arabic_docs")
|
14 |
|
15 |
-
# نموذج توليد embeddings
|
16 |
embedder = SentenceTransformer("sentence-transformers/LaBSE")
|
17 |
|
18 |
-
# تقطيع النصوص من
|
19 |
def process_pdf(pdf_file):
|
20 |
-
doc = fitz.open(pdf_file.
|
21 |
texts = []
|
22 |
-
for
|
23 |
-
text =
|
24 |
for chunk in text.split("\n\n"):
|
25 |
if len(chunk.strip()) > 50:
|
26 |
texts.append(chunk.strip())
|
27 |
return texts
|
28 |
|
29 |
-
# إدخال النصوص
|
30 |
def ingest(pdf_file):
|
31 |
texts = process_pdf(pdf_file)
|
32 |
embeddings = embedder.encode(texts, show_progress_bar=True)
|
33 |
for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
|
34 |
-
col.add(
|
35 |
-
ids=[f"chunk_{i}"],
|
36 |
-
embeddings=[emb.tolist()],
|
37 |
-
metadatas=[{"text": chunk}]
|
38 |
-
)
|
39 |
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
40 |
|
41 |
-
#
|
42 |
class RagSig(dspy.Signature):
|
43 |
question: str = dspy.InputField()
|
44 |
context: str = dspy.InputField()
|
45 |
answer: str = dspy.OutputField()
|
46 |
|
47 |
-
# وحدة
|
48 |
class RagMod(dspy.Module):
|
49 |
def __init__(self):
|
50 |
super().__init__()
|
@@ -53,18 +49,18 @@ class RagMod(dspy.Module):
|
|
53 |
def forward(self, question):
|
54 |
query_embedding = embedder.encode([question])[0]
|
55 |
results = col.query(query_embeddings=[query_embedding], n_results=1)
|
56 |
-
context_list = [m["text"] for m in results["metadatas"]]
|
57 |
context = context_list[0] if context_list else ""
|
58 |
return self.predictor(question=question, context=context)
|
59 |
|
60 |
model = RagMod()
|
61 |
|
62 |
-
#
|
63 |
def answer(question):
|
64 |
out = model(question)
|
65 |
return out.answer
|
66 |
|
67 |
-
# تحميل بيانات
|
68 |
def load_dataset(path):
|
69 |
with open(path, "r", encoding="utf-8") as f:
|
70 |
return [Example(**json.loads(l)).with_inputs("question") for l in f]
|
@@ -84,10 +80,10 @@ with gr.Blocks() as demo:
|
|
84 |
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
|
85 |
|
86 |
with gr.Tab("📥 تحميل وتخزين"):
|
87 |
-
pdf_input = gr.File(label="ارفع ملف PDF",
|
88 |
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
89 |
-
|
90 |
-
ingest_btn.click(ingest, inputs=pdf_input, outputs=
|
91 |
|
92 |
with gr.Tab("❓ سؤال"):
|
93 |
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
@@ -103,4 +99,3 @@ with gr.Blocks() as demo:
|
|
103 |
opt_btn.click(optimize, inputs=[train_file, val_file], outputs=result)
|
104 |
|
105 |
demo.launch()
|
106 |
-
|
|
|
5 |
import json
|
6 |
from dspy import Example, MIPROv2, Evaluate, evaluate
|
7 |
|
8 |
+
# إعداد نموذج مفتوح المصدر
|
9 |
dspy.settings.configure(lm=dspy.LM("mistralai/Mistral-7B-Instruct-v0.2"))
|
10 |
|
11 |
+
# إعداد Chroma
|
12 |
client = chromadb.PersistentClient(path="./chroma_db")
|
13 |
col = client.get_or_create_collection(name="arabic_docs")
|
14 |
|
15 |
+
# نموذج توليد embeddings
|
16 |
embedder = SentenceTransformer("sentence-transformers/LaBSE")
|
17 |
|
18 |
+
# تقطيع النصوص من PDF
|
19 |
def process_pdf(pdf_file):
|
20 |
+
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
21 |
texts = []
|
22 |
+
for p in doc:
|
23 |
+
text = p.get_text()
|
24 |
for chunk in text.split("\n\n"):
|
25 |
if len(chunk.strip()) > 50:
|
26 |
texts.append(chunk.strip())
|
27 |
return texts
|
28 |
|
29 |
+
# إدخال النصوص في قاعدة Chroma
|
30 |
def ingest(pdf_file):
|
31 |
texts = process_pdf(pdf_file)
|
32 |
embeddings = embedder.encode(texts, show_progress_bar=True)
|
33 |
for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
|
34 |
+
col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
|
|
|
|
|
|
|
|
|
35 |
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
36 |
|
37 |
+
# تعريف التوقيع
|
38 |
class RagSig(dspy.Signature):
|
39 |
question: str = dspy.InputField()
|
40 |
context: str = dspy.InputField()
|
41 |
answer: str = dspy.OutputField()
|
42 |
|
43 |
+
# وحدة DSPy
|
44 |
class RagMod(dspy.Module):
|
45 |
def __init__(self):
|
46 |
super().__init__()
|
|
|
49 |
def forward(self, question):
|
50 |
query_embedding = embedder.encode([question])[0]
|
51 |
results = col.query(query_embeddings=[query_embedding], n_results=1)
|
52 |
+
context_list = [m["text"] for m in results["metadatas"][0]] # ✅ تصحيح هنا
|
53 |
context = context_list[0] if context_list else ""
|
54 |
return self.predictor(question=question, context=context)
|
55 |
|
56 |
model = RagMod()
|
57 |
|
58 |
+
# توليد إجابة
|
59 |
def answer(question):
|
60 |
out = model(question)
|
61 |
return out.answer
|
62 |
|
63 |
+
# تحميل بيانات التدريب والتقييم
|
64 |
def load_dataset(path):
|
65 |
with open(path, "r", encoding="utf-8") as f:
|
66 |
return [Example(**json.loads(l)).with_inputs("question") for l in f]
|
|
|
80 |
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
|
81 |
|
82 |
with gr.Tab("📥 تحميل وتخزين"):
|
83 |
+
pdf_input = gr.File(label="ارفع ملف PDF", type="binary")
|
84 |
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
85 |
+
ingest_output = gr.Textbox()
|
86 |
+
ingest_btn.click(ingest, inputs=pdf_input, outputs=ingest_output)
|
87 |
|
88 |
with gr.Tab("❓ سؤال"):
|
89 |
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
|
|
99 |
opt_btn.click(optimize, inputs=[train_file, val_file], outputs=result)
|
100 |
|
101 |
demo.launch()
|
|