import gradio as gr import time from datetime import datetime from sentence_transformers import SentenceTransformer from qdrant_client import QdrantClient from qdrant_client.models import Filter, FieldCondition, MatchValue import os from rapidfuzz import fuzz from pyairtable import Table from pyairtable import Api import re import unicodedata # Setup Qdrant Client qdrant_client = QdrantClient( url=os.environ.get("Qdrant_url"), api_key=os.environ.get("Qdrant_api"), timeout=30.0 ) # Airtable Config AIRTABLE_API_KEY = os.environ.get("airtable_api") BASE_ID = os.environ.get("airtable_baseid") TABLE_NAME = "Feedback_search" api = Api(AIRTABLE_API_KEY) table = api.table(BASE_ID, TABLE_NAME) # Preload Models model = SentenceTransformer("BAAI/bge-m3") collection_name = "product_bge-m3" threshold = 0.45 # Utils def is_non_thai(text): return re.match(r'^[A-Za-z0-9&\-\s]+$', text) is not None def normalize(text: str) -> str: if is_non_thai(text): return text.strip() text = unicodedata.normalize("NFC", text) return text.replace("เแ", "แ").replace("เเ", "แ").strip().lower() # Global state latest_query_result = {"query": "", "result": "", "raw_query": "", "time": ""} # Search Function def search_product(query): yield gr.update(value="🔄 กำลังค้นหา..."), "" start_time = time.time() latest_query_result["raw_query"] = query corrected_query = normalize(query) query_embed = model.encode(corrected_query) try: result = qdrant_client.query_points( collection_name=collection_name, query=query_embed.tolist(), with_payload=True, query_filter=Filter(must=[FieldCondition(key="type", match=MatchValue(value="product"))]), limit=50 ).points except Exception as e: yield gr.update(value="❌ Qdrant error"), f"
❌ Qdrant error: {str(e)}
" return if len(result) > 0: topk = 50 # ดึงมา rerank แค่ 50 อันดับแรกจาก Qdrant result = result[:topk] scored = [] for r in result: name = r.payload.get("name", "") # ถ้า query สั้นเกินไป ให้ fuzzy_score = 0 เพื่อกันเพี้ยน if len(corrected_query) >= 3 and name: fuzzy_score = fuzz.partial_ratio(corrected_query, name) / 100.0 else: fuzzy_score = 0.0 # รวม hybrid score if fuzzy_score < 0.5: hybrid_score = r.score else: hybrid_score = 0.7 * r.score + 0.3 * fuzzy_score r.payload["score"] = hybrid_score # เก็บลง payload ใช้เทียบ treshold ตอนเเสดงผล r.payload["fuzzy_score"] = fuzzy_score # เก็บไว้เผื่อ debug r.payload['semantic_score'] = r.score # เก็บไว้เผื่อ debug scored.append((r, hybrid_score)) # เรียงตาม hybrid score แล้วกรองผลลัพธ์ที่ hybrid score ต่ำเกิน scored = sorted(scored, key=lambda x: x[1], reverse=True) result = [r[0] for r in scored] elapsed = time.time() - start_time html_output = f"⏱ {elapsed:.2f} วินาที
" if corrected_query != query: html_output += f"🔧 แก้คำค้นจาก: {query}
→ {corrected_query}