Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,134 +1,150 @@
|
|
| 1 |
-
__import__('pysqlite3')
|
| 2 |
-
import sys
|
| 3 |
-
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
| 4 |
-
|
| 5 |
-
# DATABASES = {
|
| 6 |
-
# 'default': {
|
| 7 |
-
# 'ENGINE': 'django.db.backends.sqlite3',
|
| 8 |
-
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
| 9 |
-
# }
|
| 10 |
-
# }
|
| 11 |
-
import streamlit as st
|
| 12 |
-
from huggingface_hub import InferenceClient
|
| 13 |
-
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, PromptTemplate
|
| 14 |
-
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 15 |
-
from llama_index.core import StorageContext
|
| 16 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
| 17 |
-
from langchain.text_splitter import CharacterTextSplitter
|
| 18 |
-
from langchain.vectorstores import Chroma
|
| 19 |
-
import chromadb
|
| 20 |
-
from langchain.memory import ConversationBufferMemory
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
@st.cache_resource
|
| 33 |
-
def init_chroma():
|
| 34 |
-
persist_directory = "chroma_db"
|
| 35 |
-
chroma_client = chromadb.PersistentClient(path=persist_directory)
|
| 36 |
-
chroma_collection = chroma_client.get_or_create_collection("my_collection")
|
| 37 |
-
return chroma_client, chroma_collection
|
| 38 |
-
|
| 39 |
-
@st.cache_resource
|
| 40 |
-
def init_vectorstore():
|
| 41 |
-
persist_directory = "chroma_db"
|
| 42 |
-
embeddings = HuggingFaceEmbeddings()
|
| 43 |
-
vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings, collection_name="my_collection")
|
| 44 |
-
return vectorstore
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
#
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
#
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
st.markdown("<div style='text-align:center;'></div>", unsafe_allow_html=True)
|
|
|
|
| 1 |
+
__import__('pysqlite3')
|
| 2 |
+
import sys
|
| 3 |
+
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
| 4 |
+
|
| 5 |
+
# DATABASES = {
|
| 6 |
+
# 'default': {
|
| 7 |
+
# 'ENGINE': 'django.db.backends.sqlite3',
|
| 8 |
+
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
| 9 |
+
# }
|
| 10 |
+
# }
|
| 11 |
+
import streamlit as st
|
| 12 |
+
from huggingface_hub import InferenceClient
|
| 13 |
+
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, PromptTemplate
|
| 14 |
+
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 15 |
+
from llama_index.core import StorageContext
|
| 16 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 17 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 18 |
+
from langchain.vectorstores import Chroma
|
| 19 |
+
import chromadb
|
| 20 |
+
from langchain.memory import ConversationBufferMemory
|
| 21 |
+
import pandas as pd
|
| 22 |
+
from langchain.schema import Document
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Set page config
|
| 26 |
+
st.set_page_config(page_title="MBAL Chatbot", page_icon="🛡️", layout="wide")
|
| 27 |
+
|
| 28 |
+
# Set your Hugging Face token here
|
| 29 |
+
|
| 30 |
+
HF_TOKEN = st.secrets["HF_TOKEN"]
|
| 31 |
+
|
| 32 |
+
@st.cache_resource
|
| 33 |
+
def init_chroma():
|
| 34 |
+
persist_directory = "chroma_db"
|
| 35 |
+
chroma_client = chromadb.PersistentClient(path=persist_directory)
|
| 36 |
+
chroma_collection = chroma_client.get_or_create_collection("my_collection")
|
| 37 |
+
return chroma_client, chroma_collection
|
| 38 |
+
|
| 39 |
+
@st.cache_resource
|
| 40 |
+
def init_vectorstore():
|
| 41 |
+
persist_directory = "chroma_db"
|
| 42 |
+
embeddings = HuggingFaceEmbeddings()
|
| 43 |
+
vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings, collection_name="my_collection")
|
| 44 |
+
return vectorstore
|
| 45 |
+
@st.cache_resource
|
| 46 |
+
def setup_vector():
|
| 47 |
+
# Đọc dữ liệu từ file Excel
|
| 48 |
+
df = pd.read_excel("chunk_metadata_template.xlsx")
|
| 49 |
+
chunks = []
|
| 50 |
+
|
| 51 |
+
# Tạo danh sách các Document có metadata
|
| 52 |
+
for _, row in df.iterrows():
|
| 53 |
+
chunk_with_metadata = Document(
|
| 54 |
+
page_content=row['page_content'],
|
| 55 |
+
metadata={
|
| 56 |
+
'chunk_id': row['chunk_id'],
|
| 57 |
+
'document_title': row['document_title'],
|
| 58 |
+
'topic': row['topic'],
|
| 59 |
+
'access': row['access']
|
| 60 |
+
}
|
| 61 |
+
)
|
| 62 |
+
chunks.append(chunk_with_metadata)
|
| 63 |
+
|
| 64 |
+
# Khởi tạo embedding
|
| 65 |
+
embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
|
| 66 |
+
|
| 67 |
+
# Khởi tạo hoặc ghi vào vectorstore đã tồn tại
|
| 68 |
+
persist_directory = "chroma_db"
|
| 69 |
+
collection_name = "my_collection"
|
| 70 |
+
|
| 71 |
+
# Tạo vectorstore từ dữ liệu và ghi vào Chroma
|
| 72 |
+
vectorstore = Chroma.from_documents(
|
| 73 |
+
documents=chunks,
|
| 74 |
+
embedding=embeddings,
|
| 75 |
+
persist_directory=persist_directory,
|
| 76 |
+
collection_name=collection_name
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Ghi xuống đĩa để đảm bảo dữ liệu được lưu
|
| 80 |
+
vectorstore.persist()
|
| 81 |
+
|
| 82 |
+
return vectorstore
|
| 83 |
+
|
| 84 |
+
# Initialize components
|
| 85 |
+
client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3", token=HF_TOKEN)
|
| 86 |
+
chroma_client, chroma_collection = init_chroma()
|
| 87 |
+
init_vectorstore()
|
| 88 |
+
vectorstore = setup_vector()
|
| 89 |
+
|
| 90 |
+
# Initialize memory buffer
|
| 91 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 92 |
+
|
| 93 |
+
def rag_query(query):
|
| 94 |
+
# Lấy tài liệu liên quan
|
| 95 |
+
retrieved_docs = vectorstore.similarity_search(query, k=5)
|
| 96 |
+
context = "\n".join([doc.page_content for doc in retrieved_docs]) if retrieved_docs else ""
|
| 97 |
+
|
| 98 |
+
# Lấy tương tác cũ
|
| 99 |
+
past_interactions = memory.load_memory_variables({})[memory.memory_key]
|
| 100 |
+
context_with_memory = f"{context}\n\nConversation History:\n{past_interactions}"
|
| 101 |
+
|
| 102 |
+
# Chuẩn bị prompt
|
| 103 |
+
messages = [
|
| 104 |
+
{
|
| 105 |
+
"role": "user",
|
| 106 |
+
"content": f"""You are a consultant advising clients on insurance products from MB Ageas Life in Vietnam. Please respond professionally and accurately, and suggest suitable products by asking a few questions about the customer's needs. All information provided must remain within the scope of MBAL. Invite the customer to register for a more detailed consultation at https://www.mbageas.life/
|
| 107 |
+
{context_with_memory}
|
| 108 |
+
Question: {query}
|
| 109 |
+
Answer:"""
|
| 110 |
+
}
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
response_content = client.chat_completion(messages=messages, max_tokens=1024, stream=False)
|
| 114 |
+
response = response_content.choices[0].message.content.split("Answer:")[-1].strip()
|
| 115 |
+
return response
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def process_feedback(query, response, feedback):
|
| 119 |
+
# st.write(f"Feedback received: {'👍' if feedback else '👎'} for query: {query}")
|
| 120 |
+
if feedback:
|
| 121 |
+
# If thumbs up, store the response in memory buffer
|
| 122 |
+
memory.chat_memory.add_ai_message(response)
|
| 123 |
+
else:
|
| 124 |
+
# If thumbs down, remove the response from memory buffer and regenerate the response
|
| 125 |
+
# memory.chat_memory.messages = [msg for msg in memory.chat_memory.messages if msg.get("content") != response]
|
| 126 |
+
new_query=f"{query}. Tạo câu trả lời đúng với câu hỏi"
|
| 127 |
+
new_response = rag_query(new_query)
|
| 128 |
+
st.markdown(new_response)
|
| 129 |
+
memory.chat_memory.add_ai_message(new_response)
|
| 130 |
+
|
| 131 |
+
# Streamlit interface
|
| 132 |
+
|
| 133 |
+
st.title("Chào mừng bạn đã đến với MBAL Chatbot")
|
| 134 |
+
st.markdown("***")
|
| 135 |
+
st.info('''
|
| 136 |
+
Tôi sẽ giải đáp các thắc mắc của bạn liên quan đến các sản phẩm bảo hiểm nhân thọ của MB Ageas Life''')
|
| 137 |
+
|
| 138 |
+
col1, col2 = st.columns(2)
|
| 139 |
+
|
| 140 |
+
with col1:
|
| 141 |
+
chat = st.button("Chat")
|
| 142 |
+
if chat:
|
| 143 |
+
st.switch_page("pages/chatbot.py")
|
| 144 |
+
|
| 145 |
+
with col2:
|
| 146 |
+
rag = st.button("Store Document")
|
| 147 |
+
if rag:
|
| 148 |
+
st.switch_page("pages/management.py")
|
| 149 |
+
|
| 150 |
st.markdown("<div style='text-align:center;'></div>", unsafe_allow_html=True)
|