MOHAMMED-N commited on
Commit
c0cca7d
·
verified ·
1 Parent(s): 39ff960

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+
4
+ # --- LANGCHAIN IMPORTS ---
5
+ from langchain_community.document_loaders import PyPDFLoader
6
+ from langchain_experimental.text_splitter import SemanticChunker
7
+ from langchain_huggingface import HuggingFaceEmbeddings
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ from langchain_community.chat_models import ChatOllama
11
+ from langchain.memory import ConversationBufferMemory
12
+
13
+ # 1) SET UP PAGE
14
+ st.title("💬 Conversational Chat - Data Management & Personal Data Protection")
15
+ local_file = "Policies001.pdf"
16
+ st.write(f"Loading local file: {local_file}")
17
+ index_folder = "faiss_index"
18
+
19
+ # 2) LOAD OR BUILD VECTORSTORE
20
+ embeddings = HuggingFaceEmbeddings(
21
+ model_name="CAMeL-Lab/bert-base-arabic-camelbert-mix",
22
+ model_kwargs={"trust_remote_code": True}
23
+ )
24
+
25
+ if os.path.exists(index_folder):
26
+ st.write("Loading existing FAISS index from disk...")
27
+ vectorstore = FAISS.load_local(index_folder, embeddings, allow_dangerous_deserialization=True)
28
+ else:
29
+ st.write("Building a new FAISS index...")
30
+ loader = PyPDFLoader(local_file)
31
+ documents = loader.load()
32
+
33
+ text_splitter = SemanticChunker(
34
+ embeddings=embeddings,
35
+ breakpoint_threshold_type='percentile',
36
+ breakpoint_threshold_amount=90
37
+ )
38
+ chunked_docs = text_splitter.split_documents(documents)
39
+ st.write(f"Document split into {len(chunked_docs)} chunks.")
40
+
41
+ vectorstore = FAISS.from_documents(chunked_docs, embeddings)
42
+ vectorstore.save_local(index_folder)
43
+
44
+ # 3) CREATE RETRIEVER
45
+ retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5})
46
+
47
+ # 4) SET UP LLM + CONVERSATIONAL RETRIEVAL CHAIN
48
+ llm = ChatOllama(model="command-r7b-arabic")
49
+
50
+ # IMPORTANT: Memory object to store conversation
51
+ memory = ConversationBufferMemory(
52
+ memory_key="chat_history", # key used internally by the chain
53
+ return_messages=True # ensures we get the entire message history
54
+ )
55
+
56
+ qa_chain = ConversationalRetrievalChain.from_llm(
57
+ llm=llm,
58
+ retriever=retriever,
59
+ memory=memory,
60
+ verbose=True # optional: prints chain's internal logs in the console
61
+ )
62
+
63
+ # 5) MANAGE SESSION STATE FOR UI CHAT
64
+ if "messages" not in st.session_state:
65
+ st.session_state["messages"] = [
66
+ {"role": "assistant", "content": "👋 Hello! Ask me anything about Data Management & Personal Data Protection!"}
67
+ ]
68
+
69
+ # Display existing messages in chat format
70
+ for msg in st.session_state["messages"]:
71
+ with st.chat_message(msg["role"]):
72
+ st.markdown(msg["content"])
73
+
74
+ # 6) CHAT INPUT
75
+ user_input = st.chat_input("Type your question...")
76
+
77
+ # 7) PROCESS NEW USER MESSAGE
78
+ if user_input:
79
+ # a) Display user message in UI
80
+ st.session_state["messages"].append({"role": "user", "content": user_input})
81
+ with st.chat_message("user"):
82
+ st.markdown(user_input)
83
+
84
+ # b) Run chain with conversation memory
85
+ # We pass user_input as the "question" to the chain.
86
+ response_dict = qa_chain({"question": user_input})
87
+ answer = response_dict["answer"]
88
+
89
+ # c) Display assistant response
90
+ st.session_state["messages"].append({"role": "assistant", "content": answer})
91
+ with st.chat_message("assistant"):
92
+ st.markdown(answer)