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