Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,21 @@
|
|
1 |
-
import dspy
|
2 |
-
import gradio as gr
|
3 |
import chromadb
|
4 |
import fitz # PyMuPDF
|
5 |
-
import json
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
-
|
|
|
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 |
-
#
|
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 = []
|
@@ -27,12 +26,13 @@ def process_pdf(pdf_bytes):
|
|
27 |
texts.append(chunk.strip())
|
28 |
return texts
|
29 |
|
30 |
-
# إدخال
|
31 |
def ingest(pdf_file):
|
32 |
if hasattr(pdf_file, "read"):
|
33 |
pdf_bytes = pdf_file.read()
|
34 |
else:
|
35 |
-
|
|
|
36 |
texts = process_pdf(pdf_bytes)
|
37 |
embeddings = embedder.encode(texts, show_progress_bar=True)
|
38 |
for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
|
@@ -40,13 +40,13 @@ def ingest(pdf_file):
|
|
40 |
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
41 |
|
42 |
# استرجاع السياق من Chroma
|
43 |
-
def retrieve_context(
|
44 |
-
|
45 |
-
results = col.query(query_embeddings=[
|
46 |
-
context_list = [m["text"] for
|
47 |
-
return
|
48 |
|
49 |
-
#
|
50 |
class RagSig(dspy.Signature):
|
51 |
question: str = dspy.InputField()
|
52 |
context: str = dspy.InputField()
|
@@ -69,12 +69,12 @@ def answer(question):
|
|
69 |
out = model(question)
|
70 |
return out.answer
|
71 |
|
72 |
-
# تحميل بيانات
|
73 |
def load_dataset(path):
|
74 |
with open(path, "r", encoding="utf-8") as f:
|
75 |
return [Example(**json.loads(l)).with_inputs("question") for l in f]
|
76 |
|
77 |
-
# تحسين النموذج
|
78 |
def optimize(train_file, val_file):
|
79 |
global model
|
80 |
trainset = load_dataset(train_file.name)
|
@@ -89,20 +89,20 @@ with gr.Blocks() as demo:
|
|
89 |
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
|
90 |
|
91 |
with gr.Tab("📥 تحميل وتخزين"):
|
92 |
-
pdf_input = gr.File(label="ارفع ملف PDF",
|
93 |
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
94 |
-
|
95 |
-
ingest_btn.click(
|
96 |
|
97 |
with gr.Tab("❓ سؤال"):
|
98 |
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
99 |
answer_btn = gr.Button("احصل على الإجابة")
|
100 |
out = gr.Textbox(label="الإجابة")
|
101 |
-
answer_btn.click(
|
102 |
|
103 |
with gr.Tab("⚙️ تحسين النموذج"):
|
104 |
-
train_file = gr.File(label="trainset.jsonl"
|
105 |
-
val_file = gr.File(label="valset.jsonl"
|
106 |
opt_btn = gr.Button("ابدأ التحسين")
|
107 |
result = gr.Textbox(label="نتيجة التحسين")
|
108 |
opt_btn.click(optimize, inputs=[train_file, val_file], outputs=result)
|
|
|
1 |
+
import dspy, gradio as gr
|
|
|
2 |
import chromadb
|
3 |
import fitz # PyMuPDF
|
|
|
4 |
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 |
+
# إعداد 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_bytes):
|
20 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
21 |
texts = []
|
|
|
26 |
texts.append(chunk.strip())
|
27 |
return texts
|
28 |
|
29 |
+
# إدخال النصوص في قاعدة Chroma
|
30 |
def ingest(pdf_file):
|
31 |
if hasattr(pdf_file, "read"):
|
32 |
pdf_bytes = pdf_file.read()
|
33 |
else:
|
34 |
+
with open(pdf_file.name, "rb") as f:
|
35 |
+
pdf_bytes = f.read()
|
36 |
texts = process_pdf(pdf_bytes)
|
37 |
embeddings = embedder.encode(texts, show_progress_bar=True)
|
38 |
for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
|
|
|
40 |
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
41 |
|
42 |
# استرجاع السياق من Chroma
|
43 |
+
def retrieve_context(question):
|
44 |
+
query_embedding = embedder.encode([question])[0] # تحويل السؤال إلى embedding
|
45 |
+
results = col.query(query_embeddings=[query_embedding], n_results=3)
|
46 |
+
context_list = [m["text"] for m in results["metadatas"][0]] # استخراج السياق من النتائج
|
47 |
+
return "\n\n".join(context_list)
|
48 |
|
49 |
+
# توقيع RAG
|
50 |
class RagSig(dspy.Signature):
|
51 |
question: str = dspy.InputField()
|
52 |
context: str = dspy.InputField()
|
|
|
69 |
out = model(question)
|
70 |
return out.answer
|
71 |
|
72 |
+
# تحميل بيانات تدريب/تقييم
|
73 |
def load_dataset(path):
|
74 |
with open(path, "r", encoding="utf-8") as f:
|
75 |
return [Example(**json.loads(l)).with_inputs("question") for l in f]
|
76 |
|
77 |
+
# تحسين النموذج باستخدام MIPROv2
|
78 |
def optimize(train_file, val_file):
|
79 |
global model
|
80 |
trainset = load_dataset(train_file.name)
|
|
|
89 |
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
|
90 |
|
91 |
with gr.Tab("📥 تحميل وتخزين"):
|
92 |
+
pdf_input = gr.File(label="ارفع ملف PDF", type="file")
|
93 |
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
94 |
+
ingest_out = gr.Textbox(label="نتيجة الإضافة")
|
95 |
+
ingest_btn.click(ingest, inputs=pdf_input, outputs=ingest_out)
|
96 |
|
97 |
with gr.Tab("❓ سؤال"):
|
98 |
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
99 |
answer_btn = gr.Button("احصل على الإجابة")
|
100 |
out = gr.Textbox(label="الإجابة")
|
101 |
+
answer_btn.click(answer, inputs=q, outputs=out)
|
102 |
|
103 |
with gr.Tab("⚙️ تحسين النموذج"):
|
104 |
+
train_file = gr.File(label="trainset.jsonl")
|
105 |
+
val_file = gr.File(label="valset.jsonl")
|
106 |
opt_btn = gr.Button("ابدأ التحسين")
|
107 |
result = gr.Textbox(label="نتيجة التحسين")
|
108 |
opt_btn.click(optimize, inputs=[train_file, val_file], outputs=result)
|