Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import chromadb
|
4 |
+
import fitz # PyMuPDF
|
5 |
+
import json
|
6 |
+
import dspy
|
7 |
+
from sentence_transformers import SentenceTransformer
|
8 |
+
from dspy import Example, MIPROv2, Evaluate, evaluate
|
9 |
+
from dspy import LiteLLM
|
10 |
+
|
11 |
+
# تحميل التوكن من secrets
|
12 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
13 |
+
|
14 |
+
# إعداد النموذج عبر LiteLLM من Hugging Face Inference Endpoints
|
15 |
+
dspy.settings.configure(
|
16 |
+
lm=LiteLLM(
|
17 |
+
model="HuggingFaceH4/zephyr-7b-beta", # يمكنك تغييره لأي نموذج Instruct مفتوح
|
18 |
+
api_base="https://api-inference.huggingface.co/v1",
|
19 |
+
api_key=HF_TOKEN
|
20 |
+
)
|
21 |
+
)
|
22 |
+
|
23 |
+
# إعداد ChromaDB
|
24 |
+
client = chromadb.PersistentClient(path="./chroma_db")
|
25 |
+
col = client.get_or_create_collection(name="arabic_docs")
|
26 |
+
|
27 |
+
# نموذج Embedding يدعم العربية
|
28 |
+
embedder = SentenceTransformer("sentence-transformers/LaBSE")
|
29 |
+
|
30 |
+
# استخراج النصوص من PDF
|
31 |
+
def process_pdf(pdf_bytes):
|
32 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
33 |
+
texts = []
|
34 |
+
for page in doc:
|
35 |
+
text = page.get_text()
|
36 |
+
for chunk in text.split("\n\n"):
|
37 |
+
if len(chunk.strip()) > 50:
|
38 |
+
texts.append(chunk.strip())
|
39 |
+
return texts
|
40 |
+
|
41 |
+
# إدخال النصوص إلى قاعدة Chroma
|
42 |
+
def ingest(pdf_file):
|
43 |
+
pdf_bytes = pdf_file
|
44 |
+
texts = process_pdf(pdf_bytes)
|
45 |
+
embeddings = embedder.encode(texts, show_progress_bar=True)
|
46 |
+
for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
|
47 |
+
col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
|
48 |
+
return f"✅ تمت إضافة {len(texts)} مقطعاً."
|
49 |
+
|
50 |
+
# استرجاع السياق الأقرب للسؤال
|
51 |
+
def retrieve_context(question):
|
52 |
+
embedding = embedder.encode([question])[0]
|
53 |
+
results = col.query(query_embeddings=[embedding.tolist()], n_results=3)
|
54 |
+
context_list = [m["text"] for m in results["metadatas"][0]]
|
55 |
+
return "\n\n".join(context_list)
|
56 |
+
|
57 |
+
# تعريف توقيع وحدة RAG
|
58 |
+
class RagSig(dspy.Signature):
|
59 |
+
question: str = dspy.InputField()
|
60 |
+
context: str = dspy.InputField()
|
61 |
+
answer: str = dspy.OutputField()
|
62 |
+
|
63 |
+
# وحدة RAG
|
64 |
+
class RagMod(dspy.Module):
|
65 |
+
def __init__(self):
|
66 |
+
super().__init__()
|
67 |
+
self.predictor = dspy.Predict(RagSig)
|
68 |
+
|
69 |
+
def forward(self, question):
|
70 |
+
context = retrieve_context(question)
|
71 |
+
return self.predictor(question=question, context=context)
|
72 |
+
|
73 |
+
model = RagMod()
|
74 |
+
|
75 |
+
# توليد الإجابة
|
76 |
+
def answer(question):
|
77 |
+
out = model(question)
|
78 |
+
return out.answer
|
79 |
+
|
80 |
+
# تحميل مجموعة بيانات التدريب
|
81 |
+
def load_dataset(path):
|
82 |
+
with open(path, "r", encoding="utf-8") as f:
|
83 |
+
return [Example(**json.loads(l)).with_inputs("question") for l in f]
|
84 |
+
|
85 |
+
# تحسين النموذج
|
86 |
+
def optimize(train_file, val_file):
|
87 |
+
global model
|
88 |
+
trainset = load_dataset(train_file.name)
|
89 |
+
valset = load_dataset(val_file.name)
|
90 |
+
tp = MIPROv2(metric=evaluate.answer_exact_match, auto="light", num_threads=4)
|
91 |
+
optimized = tp.compile(model, trainset=trainset, valset=valset)
|
92 |
+
model = optimized
|
93 |
+
return "✅ تم تحسين النموذج!"
|
94 |
+
|
95 |
+
# واجهة Gradio
|
96 |
+
with gr.Blocks() as demo:
|
97 |
+
gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + ChromaDB + HF Inference")
|
98 |
+
|
99 |
+
with gr.Tab("📥 تحميل وتخزين"):
|
100 |
+
pdf_input = gr.File(label="ارفع ملف PDF", type="binary")
|
101 |
+
ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
|
102 |
+
ingest_out = gr.Textbox(label="نتيجة الإضافة")
|
103 |
+
ingest_btn.click(ingest, inputs=pdf_input, outputs=ingest_out)
|
104 |
+
|
105 |
+
with gr.Tab("❓ سؤال"):
|
106 |
+
q = gr.Textbox(label="اكتب سؤالك بالعربية")
|
107 |
+
answer_btn = gr.Button("احصل على الإجابة")
|
108 |
+
out = gr.Textbox(label="الإجابة")
|
109 |
+
answer_btn.click(answer, inputs=q, outputs=out)
|
110 |
+
|
111 |
+
with gr.Tab("⚙️ تحسين النموذج"):
|
112 |
+
train_file = gr.File(label="trainset.jsonl")
|
113 |
+
val_file = gr.File(label="valset.jsonl")
|
114 |
+
opt_btn = gr.Button("ابدأ التحسين")
|
115 |
+
result = gr.Textbox(label="نتيجة التحسين")
|
116 |
+
opt_btn.click(optimize, inputs=[train_file, val_file], outputs=result)
|
117 |
+
|
118 |
+
demo.launch()
|