ramysaidagieb commited on
Commit
3b6dd97
·
verified ·
1 Parent(s): b22c352

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -50
app.py CHANGED
@@ -1,64 +1,89 @@
1
  import os
 
2
  import gradio as gr
 
 
3
  from langchain_community.vectorstores import Chroma
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
5
- from langchain_community.llms import CTransformers
6
- from langchain_community.document_loaders import PyPDFLoader
7
- from langchain.text_splitter import RecursiveCharacterTextSplitter
8
  from langchain.chains import RetrievalQA
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # مسار النموذج المحلي (يمكن تحميله مسبقًا ووضعه في هذا المسار)
11
- MODEL_PATH = "TheBloke/Mistral-7B-Instruct-v0.2-GGUF" # استخدم gguf فقط
12
- MODEL_FILE = "mistral-7b-instruct-v0.2.Q4_K_M.gguf"
13
-
14
- def process_pdf_and_answer(pdf_path, question):
15
- # تحميل ملف PDF
16
- loader = PyPDFLoader(pdf_path)
17
- pages = loader.load()
18
-
19
- # تقسيم النصوص
20
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
21
- texts = text_splitter.split_documents(pages)
22
-
23
- # التضمين باستخدام نموذج مجاني
24
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
25
- vectorstore = Chroma.from_documents(texts, embedding=embeddings)
26
-
27
- # إعداد LLM محلي عبر ctransformers
28
- llm = CTransformers(
29
- model=MODEL_FILE,
30
- model_path=MODEL_PATH,
31
- model_type="mistral",
32
- config={
33
- "max_new_tokens": 512,
34
- "temperature": 0.1
35
- }
36
- )
37
-
38
- # بناء سلسلة RAG
39
- qa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=vectorstore.as_retriever(), return_source_documents=True)
40
-
41
- # الإجابة على السؤال
42
  result = qa_chain({"query": question})
43
- return result["result"]
 
 
 
44
 
45
- # واجهة Gradio
46
- with gr.Blocks() as demo:
47
- gr.Markdown("## 📄🤖 مساعد PDF الذكي - بدون API")
48
 
49
- with gr.Row():
50
- file_input = gr.File(label="📥 ملف PDF", type="filepath", file_types=[".pdf"])
51
- question_input = gr.Textbox(label=" سؤالك", placeholder="ما هو موضوع الصفحة الأولى؟")
52
- output = gr.Textbox(label="📝 الإجابة", lines=10)
53
- submit_btn = gr.Button("�� استخرج الإجابة")
54
 
55
- def handle_submit(file, question):
56
- if file is None or question.strip() == "":
57
- return "يرجى رفع ملف PDF وكتابة سؤال."
58
- return process_pdf_and_answer(file, question)
59
 
60
- submit_btn.click(handle_submit, inputs=[file_input, question_input], outputs=output)
 
61
 
62
- # تشغيل التطبيق
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
  import os
2
+ import shutil
3
  import gradio as gr
4
+
5
+ from langchain_community.document_loaders import PyPDFLoader
6
  from langchain_community.vectorstores import Chroma
7
  from langchain_community.embeddings import HuggingFaceEmbeddings
8
+ from langchain_community.llms import HuggingFaceHub
 
 
9
  from langchain.chains import RetrievalQA
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+
12
+ # إعداد مجلد التخزين للملفات والبيانات
13
+ CHROMA_PATH = "chroma_db"
14
+ os.makedirs("docs", exist_ok=True)
15
+
16
+ # متغير عالمي للسلسلة
17
+ qa_chain = None
18
+
19
+ # الدالة لنسخ الملف إلى مجلد docs
20
+ def save_pdf_to_docs(uploaded_file):
21
+ filename = os.path.basename(uploaded_file.name)
22
+ destination_path = os.path.join("docs", filename)
23
+ if os.path.abspath(uploaded_file.name) != os.path.abspath(destination_path):
24
+ shutil.copy(uploaded_file.name, destination_path)
25
+ return destination_path
26
+
27
+ # الدالة لمعالجة الملف وبناء قاعدة البيانات
28
+ def process_file(file):
29
+ global qa_chain
30
+
31
+ try:
32
+ path = save_pdf_to_docs(file)
33
+
34
+ loader = PyPDFLoader(path)
35
+ docs = loader.load()
36
+
37
+ # تقسيم النصوص إلى أجزاء صغيرة
38
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
39
+ split_docs = splitter.split_documents(docs)
40
+
41
+ # إعداد التضمينات
42
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
43
+
44
+ # إنشاء قاعدة بيانات شعاعية
45
+ vectordb = Chroma.from_documents(split_docs, embedding=embeddings, persist_directory=CHROMA_PATH)
46
+ retriever = vectordb.as_retriever(search_kwargs={"k": 3})
47
+
48
+ # استخدام نموذج مجاني من Hugging Face لا يتطلب مفتاح API
49
+ llm = HuggingFaceHub(
50
+ repo_id="mistralai/Mistral-7B-Instruct-v0.2",
51
+ huggingfacehub_api_token="", # تركها فارغة على Hugging Face Spaces
52
+ model_kwargs={"temperature": 0.2, "max_new_tokens": 512}
53
+ )
54
+
55
+ qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True)
56
+
57
+ return "✅ تم تحميل الملف بنجاح، يمكنك الآن طرح الأسئلة."
58
+
59
+ except Exception as e:
60
+ return f"❌ حدث خطأ أثناء المعالجة: {e}"
61
+
62
+ # الدالة للإجابة على السؤال
63
+ def answer_question(question):
64
+ if qa_chain is None:
65
+ return "⚠️ الرجاء رفع ومعالجة ملف PDF أولاً."
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  result = qa_chain({"query": question})
68
+ answer = result["result"]
69
+
70
+ # عرض النتيجة من اليمين إلى اليسار
71
+ return f"<div dir='rtl'><b>🔍 الإجابة:</b><br>{answer}</div>"
72
 
73
+ # بناء واجهة Gradio
74
+ with gr.Blocks(title="مساعد عربي ذكي للملفات") as demo:
75
+ gr.Markdown("## 🤖 مساعد الملفات العربية باستخدام RAG", elem_id="title")
76
 
77
+ file_input = gr.File(label="📄 ارفع ملف PDF بالعربية", type="filepath")
78
+ upload_button = gr.Button("🚀 تحميل ومعالجة الملف")
79
+ status_box = gr.Textbox(label="📝 الحالة", interactive=False)
 
 
80
 
81
+ question_input = gr.Textbox(label="❓ اطرح سؤالك هنا", elem_id="question", rtl=True)
82
+ answer_output = gr.HTML(label="📘 الإجابة", elem_id="answer")
 
 
83
 
84
+ upload_button.click(fn=process_file, inputs=[file_input], outputs=[status_box])
85
+ question_input.submit(fn=answer_question, inputs=[question_input], outputs=[answer_output])
86
 
87
+ # إطلاق التطبيق
88
  if __name__ == "__main__":
89
  demo.launch()