vinapatri commited on
Commit
6ef4ac0
·
verified ·
1 Parent(s): 1e7904c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -53
app.py CHANGED
@@ -1,64 +1,86 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import random
4
+ import pickle
5
+ import torch
6
+ from transformers import BertForSequenceClassification, BertTokenizerFast
7
+ from huggingface_hub import hf_hub_download
8
  import gradio as gr
 
9
 
10
+ # Configuration
11
+ MODEL_NAME = "vinapatri/intent-classification-jkn-kis"
12
+ CONFIDENCE_THRESHOLD = 0.6 # Adjust this based on your model's performance
 
13
 
14
+ # --- Model Functions ---
15
+ def load_model_components():
16
+ model = BertForSequenceClassification.from_pretrained(MODEL_NAME)
17
+ tokenizer = BertTokenizerFast.from_pretrained(MODEL_NAME)
18
+
19
+ label_encoder_path = hf_hub_download(repo_id=MODEL_NAME, filename="label_encoder.pkl")
20
+ responses_path = hf_hub_download(repo_id=MODEL_NAME, filename="tag_to_responses.pkl")
21
+
22
+ with open(label_encoder_path, "rb") as f:
23
+ le = pickle.load(f)
24
+
25
+ with open(responses_path, "rb") as f:
26
+ tag_to_responses = pickle.load(f)
27
+
28
+ # Ensure we have an 'unknown' response category
29
+ if 'unknown' not in tag_to_responses:
30
+ tag_to_responses['unknown'] = [
31
+ "Maaf, saya tidak mengerti pertanyaan Anda",
32
+ "Saya belum bisa menjawab pertanyaan tersebut"
33
+ ]
34
+
35
+ return model, tokenizer, le, tag_to_responses
36
 
37
+ model, tokenizer, le, tag_to_responses = load_model_components()
 
 
 
 
 
 
 
 
38
 
39
+ def predict_intent(text):
40
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
41
+
42
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
43
+ model.to(device)
44
+ inputs = {k: v.to(device) for k, v in inputs.items()}
45
+
46
+ with torch.no_grad():
47
+ outputs = model(**inputs)
48
+
49
+ # Get confidence scores
50
+ probabilities = torch.softmax(outputs.logits, dim=1)[0]
51
+ confidence, predicted_class_id = torch.max(probabilities, 0)
52
+ confidence = confidence.item()
53
+
54
+ # Return 'unknown' if confidence is below threshold
55
+ if confidence < CONFIDENCE_THRESHOLD:
56
+ return "unknown"
57
+
58
+ tag = le.inverse_transform([predicted_class_id.item()])[0]
59
+ return tag
60
 
61
+ def get_response(user_input):
62
+ tag = predict_intent(user_input)
63
+ responses = tag_to_responses.get(tag, tag_to_responses['unknown'])
64
+ return random.choice(responses)
65
 
66
+ # --- Gradio Interface ---
67
+ def chat_interface(message, history):
68
+ return get_response(message)
69
 
70
+ gradio_app = gr.ChatInterface(
71
+ fn=chat_interface,
72
+ title="JKN-KIS Intent Classification",
73
+ description="Bot untuk klasifikasi intent terkait JKN-KIS",
74
+ examples=[
75
+ "Bagaimana cara daftar Mobile JKN?",
76
+ "Gimana cara buat rujukan online?",
77
+ "Kenapa OTP Mobile JKN tidak masuk?"
78
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  )
80
 
 
81
  if __name__ == "__main__":
82
+ logging.basicConfig(
83
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
84
+ level=logging.INFO
85
+ )
86
+ gradio_app.launch(server_name="0.0.0.0", server_port=7860)