ramysaidagieb commited on
Commit
26c4c4f
·
verified ·
1 Parent(s): 053a53d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -23
app.py CHANGED
@@ -1,58 +1,55 @@
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 = []
22
- for p in doc:
23
- text = p.get_text()
24
  for chunk in text.split("\n\n"):
25
  if len(chunk.strip()) > 50:
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)):
39
  col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
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()
53
  answer: str = dspy.OutputField()
54
 
55
- # وحدة DSPy
56
  class RagMod(dspy.Module):
57
  def __init__(self):
58
  super().__init__()
@@ -64,17 +61,17 @@ class RagMod(dspy.Module):
64
 
65
  model = RagMod()
66
 
67
- # توليد إجابة
68
  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
- # تحسين النموذج باستخدام MIPROv2
78
  def optimize(train_file, val_file):
79
  global model
80
  trainset = load_dataset(train_file.name)
@@ -86,10 +83,10 @@ def optimize(train_file, val_file):
86
 
87
  # واجهة Gradio
88
  with gr.Blocks() as demo:
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)
 
1
+ import dspy
2
+ import gradio as gr
3
  import chromadb
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
+ # إعداد قاعدة Chroma
13
  client = chromadb.PersistentClient(path="./chroma_db")
14
  col = client.get_or_create_collection(name="arabic_docs")
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 page in doc:
24
+ text = page.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
+ # إدخال البيانات في Chroma
31
  def ingest(pdf_file):
32
+ pdf_bytes = pdf_file # لأننا استخدمنا type='binary'
 
 
 
 
33
  texts = process_pdf(pdf_bytes)
34
  embeddings = embedder.encode(texts, show_progress_bar=True)
35
  for i, (chunk, emb) in enumerate(zip(texts, embeddings)):
36
  col.add(ids=[f"chunk_{i}"], embeddings=[emb.tolist()], metadatas=[{"text": chunk}])
37
  return f"✅ تمت إضافة {len(texts)} مقطعاً."
38
 
39
+ # استرجاع السياق
40
  def retrieve_context(question):
41
+ embedding = embedder.encode([question])[0]
42
+ results = col.query(query_embeddings=[embedding.tolist()], n_results=3)
43
+ context_list = [m["text"] for m in results["metadatas"][0]]
44
  return "\n\n".join(context_list)
45
 
46
+ # توقيع وحدة RAG
47
  class RagSig(dspy.Signature):
48
  question: str = dspy.InputField()
49
  context: str = dspy.InputField()
50
  answer: str = dspy.OutputField()
51
 
52
+ # وحدة RAG
53
  class RagMod(dspy.Module):
54
  def __init__(self):
55
  super().__init__()
 
61
 
62
  model = RagMod()
63
 
64
+ # توليد الإجابة
65
  def answer(question):
66
  out = model(question)
67
  return out.answer
68
 
69
+ # تحميل مجموعة بيانات التدريب/التحقق
70
  def load_dataset(path):
71
  with open(path, "r", encoding="utf-8") as f:
72
  return [Example(**json.loads(l)).with_inputs("question") for l in f]
73
 
74
+ # تحسين النموذج
75
  def optimize(train_file, val_file):
76
  global model
77
  trainset = load_dataset(train_file.name)
 
83
 
84
  # واجهة Gradio
85
  with gr.Blocks() as demo:
86
+ gr.Markdown("## 🧠 نظام RAG عربي باستخدام DSPy + ChromaDB + Mistral")
87
 
88
  with gr.Tab("📥 تحميل وتخزين"):
89
+ pdf_input = gr.File(label="ارفع ملف PDF", type="binary") # ← هنا التعديل
90
  ingest_btn = gr.Button("إضافة إلى قاعدة البيانات")
91
  ingest_out = gr.Textbox(label="نتيجة الإضافة")
92
  ingest_btn.click(ingest, inputs=pdf_input, outputs=ingest_out)