Spaces:
Sleeping
Sleeping
mastershlfu commited on
Commit ·
cb3d0a6
1
Parent(s): 52ac84d
Add gradio demo
Browse files- analyze_embedding.py +100 -0
- app.py +48 -0
- requirments.txt +5 -0
analyze_embedding.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import plotly.express as px
|
| 3 |
+
from sklearn.decomposition import PCA
|
| 4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
import warnings
|
| 7 |
+
warnings.filterwarnings('ignore')
|
| 8 |
+
|
| 9 |
+
# ==========================================
|
| 10 |
+
# 1. KHỞI TẠO MODELS (Load sẵn khi import file)
|
| 11 |
+
# ==========================================
|
| 12 |
+
print("[Utils] Đang khởi tạo các mô hình...")
|
| 13 |
+
model_sbert = SentenceTransformer('keepitreal/vietnamese-sbert')
|
| 14 |
+
model_e5 = SentenceTransformer('intfloat/multilingual-e5-base')
|
| 15 |
+
model_bge = SentenceTransformer('BAAI/bge-m3')
|
| 16 |
+
print("[Utils] Đã load xong 3 models!")
|
| 17 |
+
|
| 18 |
+
# ==========================================
|
| 19 |
+
# 2. DỮ LIỆU NỀN (KNOWLEDGE BASE)
|
| 20 |
+
# ==========================================
|
| 21 |
+
base_sentences = [
|
| 22 |
+
"Tôi rất thích nghiên cứu về Trí tuệ nhân tạo.",
|
| 23 |
+
"I love studying Artificial Intelligence.",
|
| 24 |
+
"Con mèo đang ngủ trên ghế sofa.",
|
| 25 |
+
"The cat is taking a nap on the couch.",
|
| 26 |
+
"Công thức làm bánh pizza ngon nhất thế giới."
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
# ==========================================
|
| 30 |
+
# 3. HÀM XỬ LÝ LOGIC LÕI
|
| 31 |
+
# ==========================================
|
| 32 |
+
def process_embedding_analysis(user_text):
|
| 33 |
+
"""
|
| 34 |
+
Nhận text từ UI, tính toán vector, trả về Biểu đồ Plotly và Dataframe kết quả.
|
| 35 |
+
"""
|
| 36 |
+
if not user_text.strip():
|
| 37 |
+
return None, None, None, pd.DataFrame()
|
| 38 |
+
|
| 39 |
+
# Tui viết một cái hàm nhỏ (helper function) bên trong để tái sử dụng code cho gọn nè
|
| 40 |
+
def get_plot_and_sim(model, model_name, is_e5=False):
|
| 41 |
+
sentences_to_encode = base_sentences.copy()
|
| 42 |
+
query_to_encode = user_text
|
| 43 |
+
|
| 44 |
+
# Xử lý riêng cho E5 (cái vụ gắn prefix á)
|
| 45 |
+
if is_e5:
|
| 46 |
+
sentences_to_encode = [f"passage: {text}" for text in base_sentences]
|
| 47 |
+
query_to_encode = f"query: {user_text}"
|
| 48 |
+
|
| 49 |
+
base_embeddings = model.encode(sentences_to_encode)
|
| 50 |
+
user_embedding = model.encode([query_to_encode])
|
| 51 |
+
similarities = cosine_similarity(user_embedding, base_embeddings)[0]
|
| 52 |
+
|
| 53 |
+
# Tính PCA
|
| 54 |
+
all_texts = sentences_to_encode + [query_to_encode]
|
| 55 |
+
all_emb = model.encode(all_texts)
|
| 56 |
+
pca = PCA(n_components=2)
|
| 57 |
+
emb_2d = pca.fit_transform(all_emb)
|
| 58 |
+
|
| 59 |
+
df_plot = pd.DataFrame({
|
| 60 |
+
'X': emb_2d[:, 0], 'Y': emb_2d[:, 1],
|
| 61 |
+
'Text': base_sentences + [user_text],
|
| 62 |
+
'Loại': ["Dữ liệu nền"] * len(base_sentences) + ["Câu bạn nhập"]
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
# Vẽ hình
|
| 66 |
+
fig = px.scatter(
|
| 67 |
+
df_plot, x='X', y='Y', color='Loại', hover_name='Text',
|
| 68 |
+
title=f"{model_name}",
|
| 69 |
+
color_discrete_map={"Dữ liệu nền": "#636EFA", "Câu bạn nhập": "#EF553B"}
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Vẽ đường nối
|
| 73 |
+
best_match_idx = similarities.argmax()
|
| 74 |
+
fig.add_shape(
|
| 75 |
+
type="line",
|
| 76 |
+
x0=emb_2d[-1, 0], y0=emb_2d[-1, 1],
|
| 77 |
+
x1=emb_2d[best_match_idx, 0], y1=emb_2d[best_match_idx, 1],
|
| 78 |
+
line=dict(color="gray", width=2, dash="dot"), layer="below"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Thu nhỏ margin xíu cho 3 biểu đồ đứng cạnh nhau không bị chật
|
| 82 |
+
fig.update_traces(marker=dict(size=10, line=dict(width=1, color='white')))
|
| 83 |
+
fig.update_layout(template="plotly_white", margin=dict(l=10, r=10, t=35, b=10))
|
| 84 |
+
|
| 85 |
+
return fig, similarities
|
| 86 |
+
|
| 87 |
+
# Bắt đầu chạy cả 3 con AI nè
|
| 88 |
+
fig_sbert, sim_sbert = get_plot_and_sim(model_sbert, "1. Vietnamese SBERT")
|
| 89 |
+
fig_e5, sim_e5 = get_plot_and_sim(model_e5, "2. Microsoft E5", is_e5=True)
|
| 90 |
+
fig_bge, sim_bge = get_plot_and_sim(model_bge, "3. BAAI BGE-M3")
|
| 91 |
+
|
| 92 |
+
# Gộp điểm của 3 con vào chung 1 cái bảng cho dễ nhìn á
|
| 93 |
+
results_df = pd.DataFrame({
|
| 94 |
+
"Câu trong Database": base_sentences,
|
| 95 |
+
"SBERT (%)": [round(s * 100, 1) for s in sim_sbert],
|
| 96 |
+
"E5 (%)": [round(s * 100, 1) for s in sim_e5],
|
| 97 |
+
"BGE-M3 (%)": [round(s * 100, 1) for s in sim_bge]
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
return fig_sbert, fig_e5, fig_bge, results_df
|
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import analyze_embedding # Gọi file logic của bà vô
|
| 4 |
+
|
| 5 |
+
# Biến này tui set sẵn vài câu mẫu cho sếp vô có cái test liền
|
| 6 |
+
default_base_text = """Tôi rất thích nghiên cứu về Trí tuệ nhân tạo.
|
| 7 |
+
I love studying Artificial Intelligence.
|
| 8 |
+
Con mèo đang ngủ trên ghế sofa.
|
| 9 |
+
The cat is taking a nap on the couch.
|
| 10 |
+
Công thức làm bánh pizza ngon nhất thế giới."""
|
| 11 |
+
|
| 12 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 13 |
+
gr.Markdown("### Interactive Demo: Đại chiến 3 Mô hình (Dữ liệu nền động)")
|
| 14 |
+
gr.Markdown("Bạn có thể thêm, sửa, xóa dữ liệu nền (Knowledge Base) tùy ý. Mỗi câu nằm trên một dòng.")
|
| 15 |
+
|
| 16 |
+
with gr.Row():
|
| 17 |
+
with gr.Column(scale=1):
|
| 18 |
+
base_input = gr.Textbox(
|
| 19 |
+
label="Dữ liệu nền (Knowledge Base)",
|
| 20 |
+
value=default_base_text,
|
| 21 |
+
lines=7,
|
| 22 |
+
info="Ấn Enter để xuống dòng thêm câu mới."
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
with gr.Column(scale=1):
|
| 26 |
+
user_input = gr.Textbox(
|
| 27 |
+
label="Nhập câu của bạn:",
|
| 28 |
+
placeholder="VD: Mèo là loài động vật rất dễ thương...",
|
| 29 |
+
lines=2
|
| 30 |
+
)
|
| 31 |
+
analyze_btn = gr.Button("Phân tích cả 3 Models", variant="primary")
|
| 32 |
+
|
| 33 |
+
with gr.Row():
|
| 34 |
+
plot_sbert = gr.Plot(label="Vietnamese SBERT")
|
| 35 |
+
plot_e5 = gr.Plot(label="Microsoft E5")
|
| 36 |
+
plot_bge = gr.Plot(label="BAAI BGE-M3")
|
| 37 |
+
|
| 38 |
+
gr.Markdown("### Bảng so sánh Độ tương đồng Cosine")
|
| 39 |
+
table_output = gr.Dataframe()
|
| 40 |
+
|
| 41 |
+
analyze_btn.click(
|
| 42 |
+
fn=analyze_embedding.process_all_models, # Tên hàm bà tự sửa lại cho khớp với file logic nha
|
| 43 |
+
inputs=[user_input, base_input],
|
| 44 |
+
outputs=[plot_sbert, plot_e5, plot_bge, table_output]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Lên web thì bỏ inline=True đi nha
|
| 48 |
+
demo.launch()
|
requirments.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sentence-transformers
|
| 2 |
+
scikit-learn
|
| 3 |
+
plotly
|
| 4 |
+
pandas
|
| 5 |
+
gradio
|