ramysaidagieb commited on
Commit
2d232ac
·
verified ·
1 Parent(s): 5259cb2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from langchain_community.vectorstores import Chroma
3
+ from langchain_community.embeddings import HuggingFaceEmbeddings
4
+ from langchain.chains import RetrievalQA
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain.document_loaders import PyPDFLoader
7
+ import os
8
+ import shutil
9
+
10
+ CHROMA_PATH = "chroma_db"
11
+ EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
12
+
13
+ def load_and_prepare_file(file_path):
14
+ # تنظيف المجلد القديم
15
+ if os.path.exists(CHROMA_PATH):
16
+ shutil.rmtree(CHROMA_PATH)
17
+
18
+ # تحميل وتقطيع النص
19
+ loader = PyPDFLoader(file_path)
20
+ pages = loader.load_and_split()
21
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
22
+ chunks = text_splitter.split_documents(pages)
23
+
24
+ # إنشاء قاعدة بيانات المتجهات
25
+ embedding_function = HuggingFaceEmbeddings(model_name=EMBED_MODEL)
26
+ vectordb = Chroma.from_documents(chunks, embedding_function, persist_directory=CHROMA_PATH)
27
+ vectordb.persist()
28
+ return "✅ تم تجهيز الملف بنجاح، يمكنك الآن طرح الأسئلة."
29
+
30
+ def answer_question(question):
31
+ embedding_function = HuggingFaceEmbeddings(model_name=EMBED_MODEL)
32
+ vectordb = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)
33
+ retriever = vectordb.as_retriever()
34
+ qa = RetrievalQA.from_chain_type(llm="gpt2", retriever=retriever)
35
+ result = qa.run(question)
36
+ return result
37
+
38
+ with gr.Blocks() as demo:
39
+ gr.Markdown("### 📚 Smart PDF Assistant - مساعد PDF الذكي")
40
+
41
+ file_input = gr.File(label="📄 ارفع ملف PDF", type="filepath")
42
+ upload_output = gr.Textbox(label="نتيجة الرفع")
43
+ upload_button = gr.Button("تحميل ومعالجة الملف")
44
+
45
+ question_input = gr.Textbox(label="✍️ اكتب سؤالك هنا")
46
+ answer_output = gr.Textbox(label="🔎 الإجابة")
47
+
48
+ upload_button.click(load_and_prepare_file, inputs=file_input, outputs=upload_output)
49
+ question_input.submit(answer_question, inputs=question_input, outputs=answer_output)
50
+
51
+ demo.launch()