HIPPOCRATES / app.py
tbaro's picture
Update app.py
b48c4e5 verified
import streamlit as st
from sentence_transformers import SentenceTransformer
import sqlite3
import numpy as np
import pandas as pd
import json
from deep_translator import GoogleTranslator
# Khởi tạo Sentence Transformer
model = SentenceTransformer('all-MiniLM-L6-v2')
# Khởi tạo đối tượng dịch với googletrans
translator = GoogleTranslator()
# Kết nối SQLite
db_path = 'answers.db'
conn = sqlite3.connect(db_path)
# Tạo bảng lưu trữ lịch sử đoạn chat nếu chưa tồn tại
conn.execute('''
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_question TEXT,
bot_answer TEXT,
similarity REAL
)
''')
conn.commit()
# Hàm tính độ tương đồng cosine
def cosine_similarity(vec1, vec2):
vec1 = np.array(vec1)
vec2 = np.array(vec2)
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
# Tìm kiếm câu trả lời tương tự nhất
def search_similar_answer(query):
# Dịch câu hỏi từ tiếng Việt sang tiếng Anh
query_en = GoogleTranslator(source='vi', target='en').translate(query)
query_vector = model.encode(query_en).tolist()
# Tìm câu trả lời tương tự nhất trong cơ sở dữ liệu
df = pd.read_sql('SELECT * FROM answers', conn)
df['answer_vector'] = df['answer_vector'].apply(json.loads)
df['similarity'] = df['answer_vector'].apply(lambda x: cosine_similarity(x, query_vector))
best_match = df.loc[df['similarity'].idxmax()]
# Dịch câu trả lời từ tiếng Anh sang tiếng Việt
answer_vi = GoogleTranslator(source='en', target='vi').translate(best_match['answer'])
return best_match['question'], answer_vi, best_match['similarity']
# Tùy chỉnh giao diện Streamlit
st.set_page_config(
page_title="HIPPOCRATES",
page_icon="🩺",
layout="wide"
)
# Chia bố cục thành 3 cột: trái (lịch sử), giữa (nội dung chính), phải (tùy chọn)
col1, col2, col3 = st.columns([1.5, 3, 1.5])
# Phần bên trái: Lịch sử đoạn chat
with col1:
st.title("🗂️ Lịch sử đoạn chat")
history = pd.read_sql('SELECT * FROM chat_history ORDER BY id DESC LIMIT 10', conn)
if not history.empty:
for index, row in history.iterrows():
question_preview = row['user_question'][:30] if row['user_question'] else "Không có dữ liệu"
with st.expander(f"🔹 {question_preview}...", expanded=False):
st.markdown(f"**Câu hỏi:** {row['user_question'] or 'Không có dữ liệu'}")
st.markdown(f"**Trả lời:** {row['bot_answer'] or 'Không có dữ liệu'}")
else:
st.write("❌ Chưa có lịch sử chat nào.")
# Thêm nút để xóa toàn bộ lịch sử chat
if st.button("🗑️ Xóa toàn bộ lịch sử chat"):
conn.execute('DELETE FROM chat_history')
conn.commit()
st.success("✅ Đã xóa toàn bộ lịch sử chat.")
# Phần giữa: Nội dung chính
with col2:
st.title("🩺 HIPPOCRATES - TRỢ LÝ ẢO Y TẾ THÔNG MINH")
st.write("Bạn gặp vấn đề gì, hãy nói với chúng mình nhé!")
# Nhập câu hỏi
query = st.text_input("💬 **Câu hỏi của bạn:**", "")
if query:
with st.spinner("⏳ Đang tìm kiếm câu trả lời..."):
question, answer, similarity = search_similar_answer(query)
# Hiển thị kết quả
st.success("✅ Kết quả tìm kiếm:")
# st.markdown(f"**Câu hỏi liên quan nhất:** {question}")
st.markdown(f"**Câu trả lời:** {answer}")
# st.write(f"**Độ tương đồng:** `{similarity:.2f}`")
# Lưu đoạn chat vào lịch sử
conn.execute(
'INSERT INTO chat_history (user_question, bot_answer, similarity) VALUES (?, ?, ?)',
(query, answer, similarity)
)
conn.commit()
# Phần bên phải: Tùy chọn
with col3:
with st.expander("🔧 **Tùy chọn**", expanded=True):
st.markdown("""
- **Ứng dụng**: Tìm kiếm nhanh câu trả lời y tế.
- **Tính năng**: Thân thiện, chính xác, dễ sử dụng.
""")
st.write("**Liên hệ hỗ trợ:**")
st.markdown("""
📧 Email: edumakerlab1712@gmail.com
☎️ Phone: 0856991779
""")
# Footer
st.markdown("---")
st.markdown(
"<div style='text-align: center; font-size: 12px; color: #ffffff;'>© 2024 | Ứng dụng được phát triển bởi <b>HIPPOCRATES@ThaiSon</b></div>",
unsafe_allow_html=True
)