sibthinon commited on
Commit
28b8e02
·
verified ·
1 Parent(s): 553e0f8

Set up model

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ from datetime import datetime
4
+ import pandas as pd
5
+ from sentence_transformers import SentenceTransformer
6
+ from qdrant_client import QdrantClient
7
+ from qdrant_client.models import Filter, FieldCondition, MatchValue
8
+
9
+ import os
10
+ from qdrant_client import QdrantClient
11
+
12
+ qdrant_client = QdrantClient(
13
+ url=os.environ.get("Qdrant_url"),
14
+ api_key=os.environ.get("Qdrant_api")
15
+ )
16
+
17
+ # โมเดลที่โหลดล่วงหน้า
18
+ models = {
19
+ "E5 (intfloat/multilingual-e5-small)": SentenceTransformer('intfloat/multilingual-e5-small'),
20
+ "MiniLM (paraphrase-multilingual-MiniLM-L12-v2)": SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2'),
21
+ "DistilUSE (distiluse-base-multilingual-cased-v1)": SentenceTransformer('sentence-transformers/distiluse-base-multilingual-cased-v1')
22
+ }
23
+
24
+ # Global memory to hold feedback state
25
+ latest_query_result = {"query": "", "result": "", "model": ""}
26
+
27
+
28
+ # 🔍 Search Functions
29
+ def search_with_e5(query):
30
+ embed = models["E5 (intfloat/multilingual-e5-small)"].encode("query: " + query)
31
+ return embed
32
+
33
+ def search_with_minilm(query):
34
+ embed = models["MiniLM (paraphrase-multilingual-MiniLM-L12-v2)"].encode(query)
35
+ return embed
36
+
37
+ def search_with_distiluse(query):
38
+ embed = models["DistilUSE (distiluse-base-multilingual-cased-v1)"].encode(query)
39
+ return embed
40
+
41
+
42
+ # 🌟 Main search function
43
+ def search_product(query, model_name):
44
+ start_time = time.time()
45
+
46
+ # Choose encoder function
47
+ if "E5" in model_name:
48
+ query_embed = search_with_e5(query)
49
+ elif "MiniLM" in model_name:
50
+ query_embed = search_with_minilm(query)
51
+ elif "DistilUSE" in model_name:
52
+ query_embed = search_with_distiluse(query)
53
+ else:
54
+ return "❌ ไม่พบโมเดล"
55
+
56
+ # Query Qdrant
57
+ result = qdrant_client.query_points(
58
+ collection_name="product_E5",
59
+ query=query_embed.tolist(),
60
+ with_payload=True,
61
+ query_filter=Filter(
62
+ must=[FieldCondition(key="type", match=MatchValue(value="product"))]
63
+ )
64
+ ).points
65
+
66
+ elapsed = time.time() - start_time
67
+
68
+ # Format result
69
+ output = f"⏱ Time: {elapsed:.2f}s\n\n📦 ผลลัพธ์:\n"
70
+ result_summary = ""
71
+ for res in result:
72
+ line = f"- {res.payload.get('name', '')} (score: {res.score:.4f})"
73
+ output += line + "\n"
74
+ result_summary += line + " | "
75
+
76
+ # Save latest query
77
+ latest_query_result["query"] = query
78
+ latest_query_result["result"] = result_summary.strip()
79
+ latest_query_result["model"] = model_name
80
+
81
+ return output
82
+
83
+
84
+ # 📝 Logging feedback
85
+ def log_feedback(feedback):
86
+ now = datetime.now().isoformat()
87
+ log_entry = {
88
+ "timestamp": now,
89
+ "model": latest_query_result["model"],
90
+ "query": latest_query_result["query"],
91
+ "result": latest_query_result["result"],
92
+ "feedback": feedback
93
+ }
94
+ df = pd.DataFrame([log_entry])
95
+ df.to_csv("feedback_log.csv", mode='a', header=not pd.io.common.file_exists("feedback_log.csv"), index=False)
96
+ return f"✅ Feedback saved: {feedback}"
97
+
98
+
99
+ # 🎨 Gradio UI
100
+ with gr.Blocks() as demo:
101
+ gr.Markdown("## 🔎 Product Semantic Search (Vector Search + Qdrant)")
102
+
103
+ with gr.Row():
104
+ model_selector = gr.Dropdown(
105
+ choices=list(models.keys()),
106
+ label="เลือกโมเดล",
107
+ value="E5 (intfloat/multilingual-e5-small)"
108
+ )
109
+ query_input = gr.Textbox(label="พิมพ์คำค้นหา")
110
+
111
+ result_output = gr.Textbox(label="📋 ผลลัพธ์")
112
+
113
+ with gr.Row():
114
+ match_btn = gr.Button("✅ ตรง")
115
+ not_match_btn = gr.Button("❌ ไม่ตรง")
116
+
117
+ feedback_status = gr.Textbox(label="📬 สถานะ Feedback")
118
+
119
+ # Events
120
+ submit_fn = lambda q, m: search_product(q, m)
121
+ query_input.submit(submit_fn, inputs=[query_input, model_selector], outputs=result_output)
122
+ match_btn.click(lambda: log_feedback("match"), outputs=feedback_status)
123
+ not_match_btn.click(lambda: log_feedback("not_match"), outputs=feedback_status)
124
+
125
+ # Run app
126
+ demo.launch(share=True)