Ogghey commited on
Commit
a702cfd
Β·
verified Β·
1 Parent(s): a0b017e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -30
app.py CHANGED
@@ -1,16 +1,16 @@
1
  import gradio as gr
2
  from sentence_transformers import SentenceTransformer, util
3
  import torch
 
4
 
 
5
  model = SentenceTransformer('all-MiniLM-L6-v2')
6
 
7
- faq = {}
8
-
9
- import requests
10
-
11
  SUPABASE_URL = "https://olbjfxlclotxtnpjvpfj.supabase.co"
12
- SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9sYmpmeGxjbG90eHRucGp2cGZqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTIyMzYwMDEsImV4cCI6MjA2NzgxMjAwMX0.7q_o5DCFEAAysnWXMChH4MI5qNhIVc4OgpT5JvgYxc0" # anon key
13
 
 
14
  def get_faq_from_supabase(uid):
15
  url = f"{SUPABASE_URL}/rest/v1/faq_texts?uid=eq.{uid}"
16
  headers = {
@@ -18,43 +18,60 @@ def get_faq_from_supabase(uid):
18
  "Authorization": f"Bearer {SUPABASE_KEY}",
19
  "Content-Type": "application/json"
20
  }
21
-
22
- r = requests.get(url, headers=headers)
23
 
24
- # πŸ” Tambahkan debug log di sini
25
- print("πŸ“‘ Supabase GET:", url)
26
- print("πŸ” Status:", r.status_code)
27
- print("πŸ“¦ Body:", r.text)
 
 
 
 
28
 
29
- if r.status_code != 200:
 
 
 
 
30
  return []
31
- data = r.json()
32
- return [{"q": item["question"], "a": item["answer"]} for item in data]
33
 
 
34
  def chatbot(uid, question):
35
- user_faq = get_faq_from_supabase(uid)
36
- if not user_faq:
37
- return "FAQ belum tersedia."
 
 
 
 
 
 
 
 
 
38
 
39
- questions = [item["q"] for item in user_faq]
40
- answers = [item["a"] for item in user_faq]
41
 
42
- embeddings = model.encode(questions, convert_to_tensor=True)
43
- query_embedding = model.encode(question, convert_to_tensor=True)
 
44
 
45
- similarity = util.pytorch_cos_sim(query_embedding, embeddings)
46
- best_idx = torch.argmax(similarity).item()
47
 
48
- return {"data": [answers[best_idx]]}
 
 
49
 
50
- # Gradio Interface (bisa dipanggil via API juga)
51
  iface = gr.Interface(
52
  fn=chatbot,
53
- inputs=["text", "text"],
54
- outputs="text",
55
- examples=[["uid123", "Apakah bisa bayar di tempat?"]],
56
  allow_flagging="never",
57
- title="Biruu Chatbot API"
58
  )
59
 
60
- iface.launch()
 
1
  import gradio as gr
2
  from sentence_transformers import SentenceTransformer, util
3
  import torch
4
+ import requests
5
 
6
+ # πŸ’‘ Load model hanya sekali
7
  model = SentenceTransformer('all-MiniLM-L6-v2')
8
 
9
+ # πŸ”‘ Supabase credentials
 
 
 
10
  SUPABASE_URL = "https://olbjfxlclotxtnpjvpfj.supabase.co"
11
+ SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9sYmpmeGxjbG90eHRucGp2cGZqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTIyMzYwMDEsImV4cCI6MjA2NzgxMjAwMX0.7q_o5DCFEAAysnWXMChH4MI5qNhIVc4OgpT5JvgYxc0"
12
 
13
+ # πŸ“₯ Ambil data FAQ dari Supabase
14
  def get_faq_from_supabase(uid):
15
  url = f"{SUPABASE_URL}/rest/v1/faq_texts?uid=eq.{uid}"
16
  headers = {
 
18
  "Authorization": f"Bearer {SUPABASE_KEY}",
19
  "Content-Type": "application/json"
20
  }
 
 
21
 
22
+ try:
23
+ r = requests.get(url, headers=headers)
24
+ print(f"πŸ“‘ Supabase GET {url}")
25
+ print(f"πŸ“¦ Status: {r.status_code}, Body: {r.text}")
26
+ r.raise_for_status()
27
+ except Exception as e:
28
+ print(f"❌ Error fetching from Supabase: {e}")
29
+ return []
30
 
31
+ try:
32
+ data = r.json()
33
+ return [{"q": item["question"], "a": item["answer"]} for item in data]
34
+ except Exception as e:
35
+ print("❌ Failed to parse JSON:", e)
36
  return []
 
 
37
 
38
+ # πŸ€– Fungsi utama chatbot
39
  def chatbot(uid, question):
40
+ print(f"\nπŸ’¬ Received: UID={uid}, Question={question}")
41
+
42
+ if not uid or not question:
43
+ return {"data": ["Pertanyaan atau UID tidak valid."]}
44
+
45
+ faq_list = get_faq_from_supabase(uid)
46
+ if not faq_list:
47
+ return {"data": ["FAQ belum tersedia untuk pengguna ini."]}
48
+
49
+ try:
50
+ questions = [item["q"] for item in faq_list]
51
+ answers = [item["a"] for item in faq_list]
52
 
53
+ embeddings = model.encode(questions, convert_to_tensor=True)
54
+ query_embedding = model.encode(question, convert_to_tensor=True)
55
 
56
+ similarity = util.pytorch_cos_sim(query_embedding, embeddings)
57
+ best_idx = torch.argmax(similarity).item()
58
+ jawaban = answers[best_idx]
59
 
60
+ print(f"βœ… Jawaban terbaik: {jawaban}")
61
+ return {"data": [jawaban]}
62
 
63
+ except Exception as e:
64
+ print("❌ Error saat memproses pertanyaan:", e)
65
+ return {"data": ["Terjadi kesalahan saat memproses pertanyaan."]}
66
 
67
+ # 🟒 Gradio API
68
  iface = gr.Interface(
69
  fn=chatbot,
70
+ inputs=["text", "text"], # UID, Pertanyaan
71
+ outputs="json", # hasil = { "data": [...] }
72
+ title="Biruu Chatbot API",
73
  allow_flagging="never",
74
+ examples=[["uid123", "Apakah bisa bayar di tempat?"]]
75
  )
76
 
77
+ iface.launch(share=True)