Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,16 +3,10 @@ import random
|
|
| 3 |
import pickle
|
| 4 |
import numpy as np
|
| 5 |
import re
|
|
|
|
| 6 |
from flask import Flask, request, jsonify
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
-
# import os
|
| 10 |
-
|
| 11 |
-
# os.environ['HF_HOME'] = '/tmp/huggingface'
|
| 12 |
-
# os.environ['TRANSFORMERS_CACHE'] = '/tmp/huggingface/transformers'
|
| 13 |
-
# os.environ['HF_DATASETS_CACHE'] = '/tmp/huggingface/datasets'
|
| 14 |
-
# os.environ['HF_METRICS_CACHE'] = '/tmp/huggingface/metrics'
|
| 15 |
-
|
| 16 |
|
| 17 |
class ImprovedBPJSChatbot:
|
| 18 |
def __init__(self):
|
|
@@ -167,6 +161,10 @@ app = Flask(__name__)
|
|
| 167 |
def chat():
|
| 168 |
try:
|
| 169 |
msg = request.json.get("message", "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
response = chatbot.generate_response(msg)
|
| 171 |
return jsonify({"reply": response})
|
| 172 |
except Exception as e:
|
|
@@ -181,3 +179,188 @@ if __name__ == '__main__':
|
|
| 181 |
from waitress import serve
|
| 182 |
serve(app, host='0.0.0.0', port=7860)
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import pickle
|
| 4 |
import numpy as np
|
| 5 |
import re
|
| 6 |
+
import time # Import modul time untuk delay
|
| 7 |
from flask import Flask, request, jsonify
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
class ImprovedBPJSChatbot:
|
| 12 |
def __init__(self):
|
|
|
|
| 161 |
def chat():
|
| 162 |
try:
|
| 163 |
msg = request.json.get("message", "").strip()
|
| 164 |
+
|
| 165 |
+
# Tambahkan delay 1 detik sebelum memproses pesan
|
| 166 |
+
time.sleep(1)
|
| 167 |
+
|
| 168 |
response = chatbot.generate_response(msg)
|
| 169 |
return jsonify({"reply": response})
|
| 170 |
except Exception as e:
|
|
|
|
| 179 |
from waitress import serve
|
| 180 |
serve(app, host='0.0.0.0', port=7860)
|
| 181 |
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# import json
|
| 185 |
+
# import random
|
| 186 |
+
# import pickle
|
| 187 |
+
# import numpy as np
|
| 188 |
+
# import re
|
| 189 |
+
# from flask import Flask, request, jsonify
|
| 190 |
+
# from sentence_transformers import SentenceTransformer
|
| 191 |
+
# from sklearn.metrics.pairwise import cosine_similarity
|
| 192 |
+
# # import os
|
| 193 |
+
|
| 194 |
+
# # os.environ['HF_HOME'] = '/tmp/huggingface'
|
| 195 |
+
# # os.environ['TRANSFORMERS_CACHE'] = '/tmp/huggingface/transformers'
|
| 196 |
+
# # os.environ['HF_DATASETS_CACHE'] = '/tmp/huggingface/datasets'
|
| 197 |
+
# # os.environ['HF_METRICS_CACHE'] = '/tmp/huggingface/metrics'
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# class ImprovedBPJSChatbot:
|
| 201 |
+
# def __init__(self):
|
| 202 |
+
# self.load_models()
|
| 203 |
+
# self.load_intents()
|
| 204 |
+
|
| 205 |
+
# def load_models(self):
|
| 206 |
+
# """Load semua model yang diperlukan"""
|
| 207 |
+
# print("Memuat model dan konfigurasi...")
|
| 208 |
+
|
| 209 |
+
# # Load konfigurasi
|
| 210 |
+
# with open('model_config.pkl', 'rb') as f:
|
| 211 |
+
# config = pickle.load(f)
|
| 212 |
+
|
| 213 |
+
# # Load sentence transformer
|
| 214 |
+
# self.st_model = SentenceTransformer("Dyna-99/local-st-model")
|
| 215 |
+
# self.preprocessing_enabled = config['preprocessing_enabled']
|
| 216 |
+
|
| 217 |
+
# # Load classifier
|
| 218 |
+
# with open('svm_model.pkl', 'rb') as f:
|
| 219 |
+
# self.clf = pickle.load(f)
|
| 220 |
+
|
| 221 |
+
# # Load label encoder
|
| 222 |
+
# with open('label_encoder.pkl', 'rb') as f:
|
| 223 |
+
# self.label_encoder = pickle.load(f)
|
| 224 |
+
|
| 225 |
+
# print("Semua model berhasil dimuat!")
|
| 226 |
+
|
| 227 |
+
# def load_intents(self):
|
| 228 |
+
# """Load data intents untuk responses"""
|
| 229 |
+
# with open('intents.json', 'r', encoding='utf-8') as f:
|
| 230 |
+
# self.intents_data = json.load(f)
|
| 231 |
+
|
| 232 |
+
# self.tag_responses = {intent['tag']: intent['responses'] for intent in self.intents_data['intents']}
|
| 233 |
+
|
| 234 |
+
# # Buat embeddings untuk semua patterns (untuk similarity fallback)
|
| 235 |
+
# self.pattern_embeddings = []
|
| 236 |
+
# self.pattern_tags = []
|
| 237 |
+
|
| 238 |
+
# for intent in self.intents_data['intents']:
|
| 239 |
+
# for pattern in intent['patterns']:
|
| 240 |
+
# processed_pattern = self.preprocess_text(pattern) if self.preprocessing_enabled else pattern
|
| 241 |
+
# embedding = self.st_model.encode(processed_pattern)
|
| 242 |
+
# self.pattern_embeddings.append(embedding)
|
| 243 |
+
# self.pattern_tags.append(intent['tag'])
|
| 244 |
+
|
| 245 |
+
# self.pattern_embeddings = np.array(self.pattern_embeddings)
|
| 246 |
+
|
| 247 |
+
# def preprocess_text(self, text):
|
| 248 |
+
# """Preprocessing teks yang sama dengan training"""
|
| 249 |
+
# text = text.lower()
|
| 250 |
+
|
| 251 |
+
# # Normalisasi singkatan
|
| 252 |
+
# text = re.sub(r'\bjkk\b', 'jaminan kecelakaan kerja', text)
|
| 253 |
+
# text = re.sub(r'\bjkm\b', 'jaminan kematian', text)
|
| 254 |
+
# text = re.sub(r'\bjht\b', 'jaminan hari tua', text)
|
| 255 |
+
# text = re.sub(r'\bjp\b', 'jaminan pensiun', text)
|
| 256 |
+
# text = re.sub(r'\bbpjs\b', 'bpjs ketenagakerjaan', text)
|
| 257 |
+
|
| 258 |
+
# # Hapus karakter khusus
|
| 259 |
+
# text = re.sub(r'[^\w\s]', ' ', text)
|
| 260 |
+
# text = re.sub(r'\s+', ' ', text).strip()
|
| 261 |
+
|
| 262 |
+
# return text
|
| 263 |
+
|
| 264 |
+
# def get_prediction_confidence(self, msg_embedding):
|
| 265 |
+
# """Dapatkan prediksi dengan confidence score"""
|
| 266 |
+
# # Prediksi probabilitas
|
| 267 |
+
# probabilities = self.clf.predict_proba(msg_embedding)[0]
|
| 268 |
+
# max_prob = np.max(probabilities)
|
| 269 |
+
# predicted_class = np.argmax(probabilities)
|
| 270 |
+
# predicted_tag = self.label_encoder.inverse_transform([predicted_class])[0]
|
| 271 |
+
|
| 272 |
+
# return predicted_tag, max_prob
|
| 273 |
+
|
| 274 |
+
# def similarity_fallback(self, msg_embedding, threshold=0.7):
|
| 275 |
+
# """Fallback menggunakan cosine similarity"""
|
| 276 |
+
# similarities = cosine_similarity(msg_embedding, self.pattern_embeddings)[0]
|
| 277 |
+
# max_similarity_idx = np.argmax(similarities)
|
| 278 |
+
# max_similarity = similarities[max_similarity_idx]
|
| 279 |
+
|
| 280 |
+
# if max_similarity >= threshold:
|
| 281 |
+
# return self.pattern_tags[max_similarity_idx], max_similarity
|
| 282 |
+
|
| 283 |
+
# return 'fallback', max_similarity
|
| 284 |
+
|
| 285 |
+
# def get_contextual_response(self, tag, user_message):
|
| 286 |
+
# """Pilih response yang paling kontekstual"""
|
| 287 |
+
# responses = self.tag_responses.get(tag, self.tag_responses['fallback'])
|
| 288 |
+
|
| 289 |
+
# # Jika hanya ada satu response, return langsung
|
| 290 |
+
# if len(responses) == 1:
|
| 291 |
+
# return responses[0]
|
| 292 |
+
|
| 293 |
+
# # Pilih response berdasarkan kata kunci dalam pesan user
|
| 294 |
+
# user_words = set(user_message.lower().split())
|
| 295 |
+
|
| 296 |
+
# best_response = responses[0]
|
| 297 |
+
# best_score = 0
|
| 298 |
+
|
| 299 |
+
# for response in responses:
|
| 300 |
+
# response_words = set(response.lower().split())
|
| 301 |
+
# # Hitung kesamaan kata
|
| 302 |
+
# common_words = user_words.intersection(response_words)
|
| 303 |
+
# score = len(common_words)
|
| 304 |
+
|
| 305 |
+
# if score > best_score:
|
| 306 |
+
# best_score = score
|
| 307 |
+
# best_response = response
|
| 308 |
+
|
| 309 |
+
# # Jika tidak ada yang cocok, pilih random
|
| 310 |
+
# if best_score == 0:
|
| 311 |
+
# return random.choice(responses)
|
| 312 |
+
|
| 313 |
+
# return best_response
|
| 314 |
+
|
| 315 |
+
# def generate_response(self, message):
|
| 316 |
+
# """Generate response dengan multiple strategies"""
|
| 317 |
+
# if not message.strip():
|
| 318 |
+
# return "Tolong kirim sebuah pesan."
|
| 319 |
+
|
| 320 |
+
# # Preprocessing
|
| 321 |
+
# processed_msg = self.preprocess_text(message) if self.preprocessing_enabled else message
|
| 322 |
+
# msg_embedding = self.st_model.encode(processed_msg).reshape(1, -1)
|
| 323 |
+
|
| 324 |
+
# # Strategy 1: SVM prediction dengan confidence
|
| 325 |
+
# predicted_tag, confidence = self.get_prediction_confidence(msg_embedding)
|
| 326 |
+
|
| 327 |
+
# # Strategy 2: Similarity fallback jika confidence rendah
|
| 328 |
+
# if confidence < 0.6: # Threshold bisa di-adjust
|
| 329 |
+
# fallback_tag, similarity = self.similarity_fallback(msg_embedding)
|
| 330 |
+
# if similarity > confidence:
|
| 331 |
+
# predicted_tag = fallback_tag
|
| 332 |
+
|
| 333 |
+
# # Strategy 3: Contextual response selection
|
| 334 |
+
# response = self.get_contextual_response(predicted_tag, message)
|
| 335 |
+
|
| 336 |
+
# # Logging untuk debugging
|
| 337 |
+
# print(f"Input: {message}")
|
| 338 |
+
# print(f"Processed: {processed_msg}")
|
| 339 |
+
# print(f"Predicted tag: {predicted_tag} (confidence: {confidence:.3f})")
|
| 340 |
+
|
| 341 |
+
# return response
|
| 342 |
+
|
| 343 |
+
# # Inisialisasi chatbot
|
| 344 |
+
# chatbot = ImprovedBPJSChatbot()
|
| 345 |
+
|
| 346 |
+
# # Flask app
|
| 347 |
+
# app = Flask(__name__)
|
| 348 |
+
|
| 349 |
+
# @app.route('/chat', methods=['POST'])
|
| 350 |
+
# def chat():
|
| 351 |
+
# try:
|
| 352 |
+
# msg = request.json.get("message", "").strip()
|
| 353 |
+
# response = chatbot.generate_response(msg)
|
| 354 |
+
# return jsonify({"reply": response})
|
| 355 |
+
# except Exception as e:
|
| 356 |
+
# print(f"Error: {e}")
|
| 357 |
+
# return jsonify({"reply": "Maaf, terjadi kesalahan sistem. Silakan coba lagi."})
|
| 358 |
+
|
| 359 |
+
# @app.route('/health', methods=['GET'])
|
| 360 |
+
# def health():
|
| 361 |
+
# return jsonify({"status": "healthy", "model": "BPJS Chatbot Improved"})
|
| 362 |
+
|
| 363 |
+
# if __name__ == '__main__':
|
| 364 |
+
# from waitress import serve
|
| 365 |
+
# serve(app, host='0.0.0.0', port=7860)
|
| 366 |
+
|