File size: 1,087 Bytes
aad84fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from sentence_transformers import SentenceTransformer, util
import torch

model = SentenceTransformer('all-MiniLM-L6-v2')

# Dummy FAQ user
faq = {
    "uid123": [
        {"q": "Apakah bisa COD?", "a": "Bisa, seluruh Indonesia"},
        {"q": "Apakah ada garansi?", "a": "Garansi 7 hari"},
    ]
}

def chatbot(uid, question):
    user_faq = faq.get(uid, [])
    if not user_faq:
        return "FAQ belum tersedia."

    questions = [item["q"] for item in user_faq]
    answers = [item["a"] for item in user_faq]

    embeddings = model.encode(questions, convert_to_tensor=True)
    query_embedding = model.encode(question, convert_to_tensor=True)

    similarity = util.pytorch_cos_sim(query_embedding, embeddings)
    best_idx = torch.argmax(similarity).item()

    return answers[best_idx]

# Gradio Interface (bisa dipanggil via API juga)
iface = gr.Interface(
    fn=chatbot,
    inputs=["text", "text"],
    outputs="text",
    examples=[["uid123", "Apakah bisa bayar di tempat?"]],
    allow_flagging="never",
    title="Biruu Chatbot API"
)

iface.launch()