Ogghey commited on
Commit
981d40d
Β·
verified Β·
1 Parent(s): f78a03e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -47
app.py CHANGED
@@ -1,16 +1,19 @@
 
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,60 +21,44 @@ def get_faq_from_supabase(uid):
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)
 
1
+
2
  import gradio as gr
3
  from sentence_transformers import SentenceTransformer, util
4
  import torch
5
  import requests
6
+ from fastapi import FastAPI, Request
7
+ from gradio.routes import App
8
+ import uvicorn
9
 
10
+ # πŸ” Konfigurasi Supabase
 
 
 
11
  SUPABASE_URL = "https://olbjfxlclotxtnpjvpfj.supabase.co"
12
  SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9sYmpmeGxjbG90eHRucGp2cGZqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTIyMzYwMDEsImV4cCI6MjA2NzgxMjAwMX0.7q_o5DCFEAAysnWXMChH4MI5qNhIVc4OgpT5JvgYxc0"
13
 
14
+ # 🧠 Load model
15
+ model = SentenceTransformer('all-MiniLM-L6-v2')
16
+
17
  def get_faq_from_supabase(uid):
18
  url = f"{SUPABASE_URL}/rest/v1/faq_texts?uid=eq.{uid}"
19
  headers = {
 
21
  "Authorization": f"Bearer {SUPABASE_KEY}",
22
  "Content-Type": "application/json"
23
  }
 
24
  try:
25
  r = requests.get(url, headers=headers)
 
 
26
  r.raise_for_status()
 
 
 
 
 
27
  data = r.json()
28
+ return [{"q": d["question"], "a": d["answer"]} for d in data]
29
  except Exception as e:
30
+ print("❌ Supabase error:", e)
31
  return []
32
 
 
33
  def chatbot(uid, question):
34
+ faqs = get_faq_from_supabase(uid)
35
+ if not faqs:
36
+ return "Tidak ada data FAQ untuk pengguna ini."
 
37
 
38
+ questions = [f["q"] for f in faqs]
39
+ answers = [f["a"] for f in faqs]
 
40
 
41
+ embeddings = model.encode(questions, convert_to_tensor=True)
42
+ query_embedding = model.encode(question, convert_to_tensor=True)
 
43
 
44
+ scores = util.pytorch_cos_sim(query_embedding, embeddings)
45
+ best_idx = torch.argmax(scores).item()
46
+ return answers[best_idx]
47
 
48
+ # πŸŽ›οΈ Buat UI untuk testing
49
+ demo = gr.Interface(fn=chatbot, inputs=["text", "text"], outputs="text", title="Chatbot")
 
50
 
51
+ # πŸš€ Tambahkan FastAPI app agar bisa menerima POST request
52
+ app = FastAPI()
53
+ app = App(app, demo)
54
 
55
+ # βœ… Endpoint khusus untuk Flutter/Postman
56
+ @app.post("/predict")
57
+ async def predict(request: Request):
58
+ try:
59
+ payload = await request.json()
60
+ uid, question = payload["data"]
61
+ result = chatbot(uid, question)
62
+ return {"data": [result]}
63
  except Exception as e:
64
+ return {"error": str(e)}