Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
from bertopic import BERTopic
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import numpy as np
|
| 6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
class BERTopicChatbot:
|
| 10 |
+
def __init__(self, data_path):
|
| 11 |
+
# Initialize BERT sentence transformer
|
| 12 |
+
self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 13 |
+
|
| 14 |
+
# Load and preprocess your custom dataset
|
| 15 |
+
self.df = pd.read_csv(data_path) # Adjust based on your data format
|
| 16 |
+
self.documents = self.df['text'].tolist() # Adjust column name as needed
|
| 17 |
+
|
| 18 |
+
# Create and train BERTopic model
|
| 19 |
+
self.topic_model = BERTopic(embedding_model=self.sentence_model)
|
| 20 |
+
self.topics, self.probs = self.topic_model.fit_transform(self.documents)
|
| 21 |
+
|
| 22 |
+
# Create document embeddings for similarity search
|
| 23 |
+
self.doc_embeddings = self.sentence_model.encode(self.documents)
|
| 24 |
+
|
| 25 |
+
def get_most_similar_document(self, query, top_k=3):
|
| 26 |
+
# Encode the query
|
| 27 |
+
query_embedding = self.sentence_model.encode([query])[0]
|
| 28 |
+
|
| 29 |
+
# Calculate similarities
|
| 30 |
+
similarities = cosine_similarity([query_embedding], self.doc_embeddings)[0]
|
| 31 |
+
|
| 32 |
+
# Get top k most similar documents
|
| 33 |
+
top_indices = similarities.argsort()[-top_k:][::-1]
|
| 34 |
+
|
| 35 |
+
return [self.documents[i] for i in top_indices], similarities[top_indices]
|
| 36 |
+
|
| 37 |
+
def get_response(self, user_query):
|
| 38 |
+
try:
|
| 39 |
+
# Get most similar documents
|
| 40 |
+
similar_docs, similarities = self.get_most_similar_document(user_query)
|
| 41 |
+
|
| 42 |
+
# Get topic for the query
|
| 43 |
+
query_topic, _ = self.topic_model.transform([user_query])
|
| 44 |
+
|
| 45 |
+
# If similarity is too low, return a default response
|
| 46 |
+
if max(similarities) < 0.5:
|
| 47 |
+
return "Xin lỗi, tôi không có đủ thông tin để trả lời câu hỏi này một cách chính xác."
|
| 48 |
+
|
| 49 |
+
# Construct response using the most similar document
|
| 50 |
+
response = similar_docs[0]
|
| 51 |
+
|
| 52 |
+
return response
|
| 53 |
+
|
| 54 |
+
@st.cache_resource
|
| 55 |
+
def initialize_chatbot():
|
| 56 |
+
return BERTopicChatbot('path_to_your_dataset.csv')
|
| 57 |
+
|
| 58 |
+
def main():
|
| 59 |
+
st.title("🤖 Trợ Lý AI - BERTopic")
|
| 60 |
+
st.caption("Trò chuyện với chúng mình nhé!")
|
| 61 |
+
|
| 62 |
+
# Initialize chatbot using cached initialization
|
| 63 |
+
chatbot = initialize_chatbot()
|
| 64 |
+
|
| 65 |
+
# Chat history in session state
|
| 66 |
+
if 'messages' not in st.session_state:
|
| 67 |
+
st.session_state.messages = []
|
| 68 |
+
|
| 69 |
+
# Display chat messages
|
| 70 |
+
for message in st.session_state.messages:
|
| 71 |
+
with st.chat_message(message["role"]):
|
| 72 |
+
st.markdown(message["content"])
|
| 73 |
+
|
| 74 |
+
# User input
|
| 75 |
+
if prompt := st.chat_input("Hãy nói gì đó..."):
|
| 76 |
+
# Add user message to chat history
|
| 77 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 78 |
+
|
| 79 |
+
# Display user message
|
| 80 |
+
with st.chat_message("user"):
|
| 81 |
+
st.markdown(prompt)
|
| 82 |
+
|
| 83 |
+
# Get chatbot response
|
| 84 |
+
response = chatbot.get_response(prompt)
|
| 85 |
+
|
| 86 |
+
# Display chatbot response
|
| 87 |
+
with st.chat_message("assistant"):
|
| 88 |
+
st.markdown(response)
|
| 89 |
+
|
| 90 |
+
# Add assistant message to chat history
|
| 91 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|