Famazo commited on
Commit
cf7d8ac
·
1 Parent(s): 1d94b12

Update backend/api.py

Browse files
Files changed (1) hide show
  1. backend/api.py +13 -18
backend/api.py CHANGED
@@ -3,7 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from transformers import AutoTokenizer
5
  import onnxruntime as ort
6
- import numpy as np # Digunakan untuk operasi tensor ONNX
7
  from pathlib import Path
8
  import traceback
9
 
@@ -24,12 +24,10 @@ BASE_DIR = Path(__file__).resolve().parent
24
  # PASTIKAN PATH INI SESUAI DENGAN REPOSITORI ANDA
25
  MODEL_PATH = BASE_DIR / "models" / "bert_chatbot.onnx"
26
  TOKENIZER_PATH = BASE_DIR / "models" / "bert-base-multilingual-cased"
27
- # DATASET_PATH dan df_jawaban DIHAPUS
28
 
29
  # === Global Variables ===
30
  tokenizer = None
31
  session = None
32
- # Hapus: df_jawaban = None
33
 
34
  # === Load tokenizer dan model ===
35
  try:
@@ -38,18 +36,14 @@ try:
38
  tokenizer = AutoTokenizer.from_pretrained(str(TOKENIZER_PATH))
39
  session = ort.InferenceSession(str(MODEL_PATH), providers=["CPUExecutionProvider"])
40
 
41
- # Hapus logika pemuatan Excel
42
- # df_jawaban = pd.read_excel(DATASET_PATH) <-- DIHAPUS
43
-
44
  print("✅ ONNX model loaded!")
45
 
46
  except Exception as e:
47
- # Log ini akan muncul jika ada masalah Path/File saat startup
48
  print("--------------------------------------------------")
49
  print(f"❌ FATAL ERROR SAAT MEMUAT ONNX/SUMBER DAYA: {e}")
50
  traceback.print_exc()
51
  print("--------------------------------------------------")
52
- # Biarkan session = None jika ada error
53
 
54
  # === Default responses ===
55
  responses = {
@@ -72,6 +66,9 @@ async def root():
72
 
73
  @app.post("/chatbot")
74
  async def chatbot(req: ChatRequest):
 
 
 
75
  if session is None:
76
  return {"reply": responses["fallback"], "intent": "error_loading"}
77
 
@@ -85,7 +82,6 @@ async def chatbot(req: ChatRequest):
85
 
86
  for name in input_names:
87
  if name in inputs:
88
- # Memastikan tipe int64
89
  ort_inputs[name] = inputs[name].astype(np.int64)
90
 
91
  # 3. Inferensi ONNX
@@ -97,16 +93,14 @@ async def chatbot(req: ChatRequest):
97
 
98
  # === Mapping ID ke label ===
99
  id2label = {
100
- 0: "greeting", # <-- GANTI INI
101
- 1: "about_me", # <-- GANTI INI
102
- 2: "skills",
103
- 3: "projects",
104
- 4: "experience",
105
- 5: "career_goal",
106
- 6: "fallback" # <-- TAMBAHKAN FALLBACK DI SINI
107
  }
 
 
 
 
108
  # === Ambil jawaban ===
109
- # Respon diambil dari dictionary responses global
110
  reply = responses.get(intent, responses["fallback"])
111
 
112
  return {"reply": str(reply), "intent": intent}
@@ -115,4 +109,5 @@ async def chatbot(req: ChatRequest):
115
  import traceback
116
  print(f"❌ Runtime error in /chatbot: {e}")
117
  traceback.print_exc()
118
- return {"reply": "⚠️ Internal server error.", "intent": "error"}
 
 
3
  from pydantic import BaseModel
4
  from transformers import AutoTokenizer
5
  import onnxruntime as ort
6
+ import numpy as np
7
  from pathlib import Path
8
  import traceback
9
 
 
24
  # PASTIKAN PATH INI SESUAI DENGAN REPOSITORI ANDA
25
  MODEL_PATH = BASE_DIR / "models" / "bert_chatbot.onnx"
26
  TOKENIZER_PATH = BASE_DIR / "models" / "bert-base-multilingual-cased"
 
27
 
28
  # === Global Variables ===
29
  tokenizer = None
30
  session = None
 
31
 
32
  # === Load tokenizer dan model ===
33
  try:
 
36
  tokenizer = AutoTokenizer.from_pretrained(str(TOKENIZER_PATH))
37
  session = ort.InferenceSession(str(MODEL_PATH), providers=["CPUExecutionProvider"])
38
 
 
 
 
39
  print("✅ ONNX model loaded!")
40
 
41
  except Exception as e:
 
42
  print("--------------------------------------------------")
43
  print(f"❌ FATAL ERROR SAAT MEMUAT ONNX/SUMBER DAYA: {e}")
44
  traceback.print_exc()
45
  print("--------------------------------------------------")
46
+ pass
47
 
48
  # === Default responses ===
49
  responses = {
 
66
 
67
  @app.post("/chatbot")
68
  async def chatbot(req: ChatRequest):
69
+ # ⭐ PERBAIKAN: Deklarasikan 'intent' di luar blok try agar bisa diakses di 'except'
70
+ intent = "fallback"
71
+
72
  if session is None:
73
  return {"reply": responses["fallback"], "intent": "error_loading"}
74
 
 
82
 
83
  for name in input_names:
84
  if name in inputs:
 
85
  ort_inputs[name] = inputs[name].astype(np.int64)
86
 
87
  # 3. Inferensi ONNX
 
93
 
94
  # === Mapping ID ke label ===
95
  id2label = {
96
+ 0: "greeting", 1: "about_me", 2: "skills", 3: "projects",
97
+ 4: "experience", 5: "career_goal", 6: "fallback", # <--- Gunakan semua intent Anda
 
 
 
 
 
98
  }
99
+
100
+ # Nilai 'intent' yang benar disimpan di sini
101
+ intent = id2label.get(pred_id, "fallback")
102
+
103
  # === Ambil jawaban ===
 
104
  reply = responses.get(intent, responses["fallback"])
105
 
106
  return {"reply": str(reply), "intent": intent}
 
109
  import traceback
110
  print(f"❌ Runtime error in /chatbot: {e}")
111
  traceback.print_exc()
112
+ # Mengembalikan error dengan nilai 'intent' yang dijamin terdefinisi
113
+ return {"reply": "⚠️ Internal server error.", "intent": intent} # <--- TIDAK AKAN CRASH LAGI