ramysaidagieb commited on
Commit
f206e7d
·
verified ·
1 Parent(s): 7562d5e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -14
app.py CHANGED
@@ -5,19 +5,19 @@ 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_file):
20
- doc = fitz.open(pdf_file.name)
21
  texts = []
22
  for page in doc:
23
  text = page.get_text()
@@ -26,40 +26,45 @@ def process_pdf(pdf_file):
26
  texts.append(chunk.strip())
27
  return texts
28
 
29
- # إدخال النصوص في قاعدة Chroma
30
  def ingest(pdf_file):
31
  texts = process_pdf(pdf_file)
32
  embeddings = embedder.encode(texts, show_progress_bar=True)
33
  for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
34
- col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
 
 
 
 
35
  return f"✅ تمت إضافة {len(texts)} مقطعاً."
36
 
37
- # تعريف التوقيع باستخدام InputField و OutputField
38
  class RagSig(dspy.Signature):
39
  question: str = dspy.InputField()
40
  context: str = dspy.InputField()
41
  answer: str = dspy.OutputField()
42
 
43
- # وحدة DSPy مع استرجاع السياق من Chroma داخل forward
44
  class RagMod(dspy.Module):
45
  def __init__(self):
46
  super().__init__()
47
  self.predictor = dspy.Predict(RagSig)
48
 
49
  def forward(self, question):
50
- results = col.query(question, n_results=1)
 
51
  context_list = [m["text"] for m in results["metadatas"]]
52
  context = context_list[0] if context_list else ""
53
  return self.predictor(question=question, context=context)
54
 
55
  model = RagMod()
56
 
57
- # توليد إجابة
58
  def answer(question):
59
  out = model(question)
60
  return out.answer
61
 
62
- # تحميل بيانات تدريب/تقييم
63
  def load_dataset(path):
64
  with open(path, "r", encoding="utf-8") as f:
65
  return [Example(**json.loads(l)).with_inputs("question") for l in f]
@@ -79,9 +84,10 @@ with gr.Blocks() as demo:
79
  gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
80
 
81
  with gr.Tab("📥 تحميل وتخزين"):
82
- pdf_input = gr.File(label="ارفع ملف PDF")
83
  ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
84
- ingest_btn.click(ingest, inputs=pdf_input, outputs=gr.Textbox())
 
85
 
86
  with gr.Tab("❓ سؤال"):
87
  q = gr.Textbox(label="اكتب سؤالك بالعربية")
 
5
  import json
6
  from dspy import Example, MIPROv2, Evaluate, evaluate
7
 
8
+ # إعداد نموذج DSPy بلغة عربية باستخدام Mistral
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_file):
20
+ doc = fitz.open(pdf_file.name) # استخدام .name بدلاً من .read()
21
  texts = []
22
  for page in doc:
23
  text = page.get_text()
 
26
  texts.append(chunk.strip())
27
  return texts
28
 
29
+ # إدخال النصوص إلى قاعدة البيانات
30
  def ingest(pdf_file):
31
  texts = process_pdf(pdf_file)
32
  embeddings = embedder.encode(texts, show_progress_bar=True)
33
  for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
34
+ col.add(
35
+ ids=[f"chunk_{i}"],
36
+ embeddings=[emb.tolist()],
37
+ metadatas=[{"text": chunk}]
38
+ )
39
  return f"✅ تمت إضافة {len(texts)} مقطعاً."
40
 
41
+ # توقيع النموذج
42
  class RagSig(dspy.Signature):
43
  question: str = dspy.InputField()
44
  context: str = dspy.InputField()
45
  answer: str = dspy.OutputField()
46
 
47
+ # وحدة Rag
48
  class RagMod(dspy.Module):
49
  def __init__(self):
50
  super().__init__()
51
  self.predictor = dspy.Predict(RagSig)
52
 
53
  def forward(self, question):
54
+ query_embedding = embedder.encode([question])[0]
55
+ results = col.query(query_embeddings=[query_embedding], n_results=1)
56
  context_list = [m["text"] for m in results["metadatas"]]
57
  context = context_list[0] if context_list else ""
58
  return self.predictor(question=question, context=context)
59
 
60
  model = RagMod()
61
 
62
+ # دالة للإجابة على سؤال
63
  def answer(question):
64
  out = model(question)
65
  return out.answer
66
 
67
+ # تحميل بيانات التقييم
68
  def load_dataset(path):
69
  with open(path, "r", encoding="utf-8") as f:
70
  return [Example(**json.loads(l)).with_inputs("question") for l in f]
 
84
  gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + نموذج مفتوح المصدر")
85
 
86
  with gr.Tab("📥 تحميل وتخزين"):
87
+ pdf_input = gr.File(label="ارفع ملف PDF", file_types=[".pdf"])
88
  ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
89
+ ingest_out = gr.Textbox(label="النتيجة")
90
+ ingest_btn.click(ingest, inputs=pdf_input, outputs=ingest_out)
91
 
92
  with gr.Tab("❓ سؤال"):
93
  q = gr.Textbox(label="اكتب سؤالك بالعربية")