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