Spaces:
Sleeping
Sleeping
File size: 4,667 Bytes
d9ac973 3b521f3 d9ac973 b4cb652 d9ac973 3b521f3 d9ac973 3b521f3 d9ac973 b48c4e5 b866721 d9ac973 b866721 d9ac973 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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 | 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
)
|