MOHAMMED-N commited on
Commit
7815660
·
verified ·
1 Parent(s): 33cc936

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -55
app.py CHANGED
@@ -1,16 +1,18 @@
1
- import streamlit as st
2
  import os
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
 
 
 
4
  from langchain_community.document_loaders import PyPDFLoader
5
  from langchain_experimental.text_splitter import SemanticChunker
6
  from langchain_huggingface import HuggingFaceEmbeddings
7
  from langchain_community.vectorstores import FAISS
8
- from langchain.memory import ConversationBufferMemory
9
 
10
  # --- 1) إعداد الصفحة ---
 
 
11
  st.title("💬 المحادثة التفاعلية - إدارة البيانات وحماية البيانات الشخصية")
12
  local_file = "Policies001.pdf"
13
-
14
  index_folder = "faiss_index"
15
 
16
  # إضافة CSS مخصص لدعم النصوص من اليمين لليسار
@@ -27,56 +29,86 @@ st.markdown(
27
  )
28
 
29
  # --- 2) تحميل أو بناء قاعدة بيانات FAISS ---
30
- embeddings = HuggingFaceEmbeddings(
31
- model_name="CAMeL-Lab/bert-base-arabic-camelbert-mix",
32
- model_kwargs={"trust_remote_code": True}
33
- )
 
34
 
35
- if os.path.exists(index_folder):
36
- # تحميل قاعدة البيانات إذا كانت موجودة
37
- vectorstore = FAISS.load_local(index_folder, embeddings, allow_dangerous_deserialization=True)
38
- else:
39
- # تحميل PDF وتقسيم النصوص
40
- loader = PyPDFLoader(local_file)
41
- documents = loader.load()
42
-
43
- text_splitter = SemanticChunker(
44
- embeddings=embeddings,
45
- breakpoint_threshold_type='percentile',
46
- breakpoint_threshold_amount=90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  )
48
- chunked_docs = text_splitter.split_documents(documents)
49
 
50
- # إنشاء قاعدة بيانات FAISS
51
- vectorstore = FAISS.from_documents(chunked_docs, embeddings)
52
- vectorstore.save_local(index_folder)
 
 
 
 
 
53
 
54
- # --- 3) إعداد المسترجع ---
55
- retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5})
56
 
57
- # --- 4) إعداد نموذج النص ---
58
- model_name = "CohereForAI/c4ai-command-r7b-arabic-02-2025" # اسم النموذج
59
 
60
- # التأكد من وجود توكن Hugging Face
61
- hf_token = os.getenv("HF_TOKEN")
62
- if hf_token is None:
63
- st.error("Hugging Face token not found. Please set the 'HF_TOKEN' environment variable.")
64
- st.stop()
 
 
65
 
66
- # تحميل النموذج والمحول
67
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=hf_token)
68
- model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=hf_token)
 
 
69
 
70
- # إعداد pipeline لتوليد النصوص
71
- qa_pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0)
 
 
 
 
 
 
72
 
73
- # --- 5) إعداد الذاكرة ---
74
- memory = ConversationBufferMemory(
75
- memory_key="chat_history",
76
- return_messages=True
77
- )
78
 
79
- # --- 6) إدارة رسائل المستخدم ---
 
 
 
80
  if "messages" not in st.session_state:
81
  st.session_state["messages"] = [
82
  {"role": "assistant", "content": "👋 مرحبًا! اسألني أي شيء عن إدارة البيانات وحماية البيانات الشخصية!"}
@@ -87,25 +119,20 @@ for msg in st.session_state["messages"]:
87
  with st.chat_message(msg["role"]):
88
  st.markdown(f'<div class="rtl">{msg["content"]}</div>', unsafe_allow_html=True)
89
 
90
- # --- 7) إدخال المستخدم ---
91
  user_input = st.chat_input("اكتب سؤالك هنا")
92
 
93
- # --- 8) معالجة رسالة المستخدم ---
94
  if user_input:
95
  # عرض رسالة المستخدم
96
  st.session_state["messages"].append({"role": "user", "content": user_input})
97
  with st.chat_message("user"):
98
  st.markdown(f'<div class="rtl">{user_input}</div>', unsafe_allow_html=True)
99
 
100
- # استرجاع المستندات ذات الصلة
101
- retrieved_docs = retriever.get_relevant_documents(user_input)
102
- context = "\n".join([doc.page_content for doc in retrieved_docs])
103
- full_input = f"السياق:\n{context}\n\nالسؤال:\n{user_input}"
104
-
105
- # توليد الإجابة باستخدام النموذج
106
- response = qa_pipeline(full_input, max_length=500, num_return_sequences=1)[0]["generated_text"]
107
 
108
  # عرض الإجابة
109
- st.session_state["messages"].append({"role": "assistant", "content": response})
 
110
  with st.chat_message("assistant"):
111
- st.markdown(f'<div class="rtl">{response}</div>', unsafe_allow_html=True)
 
 
1
  import os
2
+ from huggingface_hub import hf_hub_download
3
+ from langchain.llms import LlamaCpp
4
+ from langchain.chains import ConversationalRetrievalChain
5
+ from langchain.memory import ConversationBufferMemory
6
  from langchain_community.document_loaders import PyPDFLoader
7
  from langchain_experimental.text_splitter import SemanticChunker
8
  from langchain_huggingface import HuggingFaceEmbeddings
9
  from langchain_community.vectorstores import FAISS
 
10
 
11
  # --- 1) إعداد الصفحة ---
12
+ import streamlit as st
13
+
14
  st.title("💬 المحادثة التفاعلية - إدارة البيانات وحماية البيانات الشخصية")
15
  local_file = "Policies001.pdf"
 
16
  index_folder = "faiss_index"
17
 
18
  # إضافة CSS مخصص لدعم النصوص من اليمين لليسار
 
29
  )
30
 
31
  # --- 2) تحميل أو بناء قاعدة بيانات FAISS ---
32
+ def build_vectorstore():
33
+ embeddings = HuggingFaceEmbeddings(
34
+ model_name="CAMeL-Lab/bert-base-arabic-camelbert-mix",
35
+ model_kwargs={"trust_remote_code": True}
36
+ )
37
 
38
+ if os.path.exists(index_folder):
39
+ # تحميل قاعدة البيانات إذا كانت موجودة
40
+ return FAISS.load_local(index_folder, embeddings, allow_dangerous_deserialization=True)
41
+ else:
42
+ # تحميل PDF وتقسيم النصوص
43
+ loader = PyPDFLoader(local_file)
44
+ documents = loader.load()
45
+
46
+ text_splitter = SemanticChunker(
47
+ embeddings=embeddings,
48
+ breakpoint_threshold_type='percentile',
49
+ breakpoint_threshold_amount=90
50
+ )
51
+ chunked_docs = text_splitter.split_documents(documents)
52
+
53
+ # إنشاء قاعدة بيانات FAISS
54
+ vectorstore = FAISS.from_documents(chunked_docs, embeddings)
55
+ vectorstore.save_local(index_folder)
56
+ return vectorstore
57
+
58
+
59
+ # --- 3) تحميل النموذج ---
60
+ def load_llm():
61
+ """
62
+ Downloads a Q4_K_M GGUF model and loads it via llama-cpp.
63
+ """
64
+ # 1) Download the GGUF model from Hugging Face
65
+ model_file = hf_hub_download(
66
+ repo_id="DevQuasar/CohereForAI.c4ai-command-r7b-arabic-02-2025-GGUF",
67
+ filename="CohereForAI.c4ai-command-r7b-arabic-02-2025-Q4_K_M.gguf",
68
+ local_dir="./models",
69
+ local_dir_use_symlinks=False
70
  )
 
71
 
72
+ # 2) Load the model with llama-cpp via LangChain’s LlamaCpp
73
+ llm = LlamaCpp(
74
+ model_path=model_file,
75
+ flash_attn=False,
76
+ n_ctx=2048, # or 4096
77
+ n_batch=512, # or even 256
78
+ chat_format='chatml'
79
+ )
80
 
81
+ return llm
 
82
 
 
 
83
 
84
+ # --- 4) بناء سلسلة المحادثة ---
85
+ def build_conversational_chain(vectorstore):
86
+ """
87
+ Creates a ConversationalRetrievalChain using the local llama-cpp-based LLM
88
+ and a ConversationBufferMemory for multi-turn Q&A.
89
+ """
90
+ llm = load_llm()
91
 
92
+ # We'll store chat history in memory so the chain can handle multi-turn conversations
93
+ memory = ConversationBufferMemory(
94
+ memory_key="chat_history",
95
+ return_messages=True
96
+ )
97
 
98
+ qa_chain = ConversationalRetrievalChain.from_llm(
99
+ llm=llm,
100
+ retriever=vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5}),
101
+ memory=memory,
102
+ verbose=True
103
+ )
104
+
105
+ return qa_chain
106
 
 
 
 
 
 
107
 
108
+ # --- 5) تنفيذ التطبيق ---
109
+ vectorstore = build_vectorstore()
110
+ qa_chain = build_conversational_chain(vectorstore)
111
+
112
  if "messages" not in st.session_state:
113
  st.session_state["messages"] = [
114
  {"role": "assistant", "content": "👋 مرحبًا! اسألني أي شيء عن إدارة البيانات وحماية البيانات الشخصية!"}
 
119
  with st.chat_message(msg["role"]):
120
  st.markdown(f'<div class="rtl">{msg["content"]}</div>', unsafe_allow_html=True)
121
 
122
+ # إدخال المستخدم
123
  user_input = st.chat_input("اكتب سؤالك هنا")
124
 
 
125
  if user_input:
126
  # عرض رسالة المستخدم
127
  st.session_state["messages"].append({"role": "user", "content": user_input})
128
  with st.chat_message("user"):
129
  st.markdown(f'<div class="rtl">{user_input}</div>', unsafe_allow_html=True)
130
 
131
+ # استدعاء سلسلة المحادثة للحصول على الإجابة
132
+ response = qa_chain({"question": user_input})
 
 
 
 
 
133
 
134
  # عرض الإجابة
135
+ answer = response["answer"]
136
+ st.session_state["messages"].append({"role": "assistant", "content": answer})
137
  with st.chat_message("assistant"):
138
+ st.markdown(f'<div class="rtl">{answer}</div>', unsafe_allow_html=True)