Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,21 @@
|
|
1 |
import dspy, gradio as gr
|
2 |
import chromadb
|
3 |
-
from chromadb.config import Settings
|
4 |
import fitz # PyMuPDF
|
5 |
from sentence_transformers import SentenceTransformer
|
6 |
import json
|
7 |
from dspy import Example, MIPROv2, Evaluate, evaluate
|
8 |
|
9 |
-
# ✅ إعداد نموذج مفتوح المصدر
|
10 |
dspy.settings.configure(lm=dspy.LM("mistralai/Mistral-7B-Instruct-v0.2"))
|
11 |
|
12 |
-
# إعداد
|
13 |
-
client = chromadb.
|
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,7 +26,7 @@ def process_pdf(pdf_bytes):
|
|
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)
|
@@ -35,16 +34,16 @@ def ingest(pdf_bytes):
|
|
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 |
-
#
|
42 |
class RagSig(dspy.Signature):
|
43 |
question: str
|
44 |
context: str
|
45 |
answer: str
|
46 |
|
47 |
-
# وحدة
|
48 |
class RagMod(dspy.Module):
|
49 |
def __init__(self):
|
50 |
super().__init__()
|
@@ -54,20 +53,19 @@ class RagMod(dspy.Module):
|
|
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,21 +75,21 @@ def optimize(train_file, val_file):
|
|
77 |
model = optimized
|
78 |
return "✅ تم تحسين النموذج!"
|
79 |
|
80 |
-
# واجهة Gradio
|
81 |
with gr.Blocks() as demo:
|
82 |
-
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر
|
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")
|
|
|
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 |
+
# ✅ إعداد نموذج مفتوح المصدر متاح على Hugging Face
|
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 |
+
# ⬇️ إضافة المحتوى إلى قاعدة البيانات
|
30 |
def ingest(pdf_bytes):
|
31 |
texts = process_pdf(pdf_bytes)
|
32 |
embeddings = embedder.encode(texts, show_progress_bar=True)
|
|
|
34 |
col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
|
35 |
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
36 |
|
37 |
+
# ⬇️ محدد سياق من Chroma
|
38 |
retriever = dspy.Retrieve(lambda q: [m["text"] for m in col.query(q, n_results=3)["metadatas"]], k=1)
|
39 |
|
40 |
+
# 🧠 تعريف توقيع الاستجابة
|
41 |
class RagSig(dspy.Signature):
|
42 |
question: str
|
43 |
context: str
|
44 |
answer: str
|
45 |
|
46 |
+
# وحدة توليد الإجابة من DSPy
|
47 |
class RagMod(dspy.Module):
|
48 |
def __init__(self):
|
49 |
super().__init__()
|
|
|
53 |
context = retriever(question)[0]
|
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]
|
67 |
|
68 |
+
# ⬇️ تحسين النموذج باستخدام MIPROv2
|
69 |
def optimize(train_file, val_file):
|
70 |
global model
|
71 |
trainset = load_dataset(train_file.name)
|
|
|
75 |
model = optimized
|
76 |
return "✅ تم تحسين النموذج!"
|
77 |
|
78 |
+
# 🖼️ واجهة Gradio
|
79 |
with gr.Blocks() as demo:
|
80 |
+
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
|
81 |
+
|
82 |
with gr.Tab("📥 تحميل وتخزين"):
|
83 |
pdf_input = gr.File(label="ارفع ملف PDF")
|
84 |
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
85 |
ingest_btn.click(ingest, inputs=pdf_input, outputs=gr.Textbox())
|
86 |
+
|
87 |
with gr.Tab("❓ سؤال"):
|
88 |
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
89 |
answer_btn = gr.Button("احصل على الإجابة")
|
90 |
out = gr.Textbox(label="الإجابة")
|
91 |
answer_btn.click(answer, inputs=q, outputs=out)
|
92 |
+
|
93 |
with gr.Tab("⚙️ تحسين النموذج"):
|
94 |
train_file = gr.File(label="trainset.jsonl")
|
95 |
val_file = gr.File(label="valset.jsonl")
|