logging prediksi jawaban ada/tidak
Browse filesmengubah app.py agar memprediksi indikasi jawaban tidak ada/tidak ditemukan
app.py
CHANGED
@@ -1,14 +1,125 @@
|
|
1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
import torch
|
3 |
import gradio as gr
|
|
|
4 |
|
5 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
12 |
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
iface.launch()
|
|
|
1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
import torch
|
3 |
import gradio as gr
|
4 |
+
import numpy as np # Import numpy jika belum ada
|
5 |
|
6 |
+
# --- 1. Inisialisasi Model dan Tokenizer (Dilakukan Sekali Saat Aplikasi Dimulai) ---
|
7 |
+
# Pastikan 'model_name' ini adalah model yang sudah kamu unggah ke Hugging Face Hub
|
8 |
+
# atau model publik lain yang ingin kamu gunakan.
|
9 |
+
model_name = "atsnetwork/my-custom-tinyllama-chatbot"
|
10 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
+
tokenizer.pad_token = tokenizer.eos_token # Pastikan token padding diatur
|
13 |
+
tokenizer.padding_side = "right" # Penting untuk efisiensi saat memproses sequence
|
14 |
|
15 |
+
# --- 2. Fungsi Pemroses Utama untuk Chatbot (Dipanggil Oleh Gradio) ---
|
16 |
+
# Fungsi ini mengintegrasikan logika inferensi dan analisis developer info
|
17 |
+
def generate_response_with_dev_info(prompt, max_new_tokens=100, temperature=0.7, top_k=50):
|
18 |
+
formatted_prompt = f"<s>[INST] {prompt} [/INST]"
|
19 |
+
inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
|
20 |
|
21 |
+
# Generate dengan output_scores=True untuk analisis probabilitas
|
22 |
+
outputs = model.generate(
|
23 |
+
**inputs,
|
24 |
+
max_new_tokens=max_new_tokens,
|
25 |
+
do_sample=True,
|
26 |
+
temperature=temperature,
|
27 |
+
top_k=top_k,
|
28 |
+
eos_token_id=tokenizer.eos_token_id,
|
29 |
+
pad_token_id=tokenizer.pad_token_id,
|
30 |
+
return_dict_in_generate=True,
|
31 |
+
output_scores=True
|
32 |
+
)
|
33 |
+
|
34 |
+
generated_ids = outputs.sequences[0]
|
35 |
+
generated_text = tokenizer.decode(generated_ids, skip_special_tokens=True)
|
36 |
+
|
37 |
+
# Ekstrak jawaban bersih
|
38 |
+
answer = ""
|
39 |
+
start_answer = generated_text.find("[/INST]")
|
40 |
+
if start_answer != -1:
|
41 |
+
answer = generated_text[start_answer + len("[/INST]"):].strip()
|
42 |
+
if answer.endswith("</s>"):
|
43 |
+
answer = answer[:-len("</s>")].strip()
|
44 |
+
else:
|
45 |
+
answer = generated_text.strip() # Fallback jika format tidak ditemukan
|
46 |
+
|
47 |
+
# --- Analisis Konfidensi Berbasis Probabilitas Token ---
|
48 |
+
avg_max_prob = 0
|
49 |
+
total_generated_tokens = 0
|
50 |
+
if outputs.scores:
|
51 |
+
# Menghitung rata-rata probabilitas token tertinggi
|
52 |
+
for score_tensor in outputs.scores:
|
53 |
+
probabilities = torch.softmax(score_tensor, dim=-1)
|
54 |
+
max_prob = torch.max(probabilities).item()
|
55 |
+
avg_max_prob += max_prob
|
56 |
+
total_generated_tokens += 1
|
57 |
+
|
58 |
+
if total_generated_tokens > 0:
|
59 |
+
avg_max_prob /= total_generated_tokens
|
60 |
+
|
61 |
+
confidence_threshold = 0.5 # Ambang batas konfidensi rata-rata (bisa disesuaikan)
|
62 |
+
confidence_status = "HIGH_CONFIDENCE"
|
63 |
+
if avg_max_prob < confidence_threshold:
|
64 |
+
confidence_status = "LOW_CONFIDENCE"
|
65 |
+
|
66 |
+
# --- Analisis Frasa "Tidak Tahu" yang Dilatih ---
|
67 |
+
is_explicitly_unknown = False
|
68 |
+
explicit_unknown_reason = ""
|
69 |
+
unknown_phrases = [
|
70 |
+
"maaf, saya tidak memiliki informasi",
|
71 |
+
"saya tidak familiar dengan",
|
72 |
+
"di luar cakupan data pelatihan saya",
|
73 |
+
"saya tidak tahu",
|
74 |
+
"tidak dapat menemukan informasi"
|
75 |
+
]
|
76 |
+
answer_lower = answer.lower()
|
77 |
+
for phrase in unknown_phrases:
|
78 |
+
if phrase in answer_lower:
|
79 |
+
is_explicitly_unknown = True
|
80 |
+
explicit_unknown_reason = f"Model menggunakan frasa 'tidak tahu': '{phrase}'"
|
81 |
+
break # Hentikan setelah menemukan frasa pertama
|
82 |
+
|
83 |
+
# --- Gabungkan Informasi untuk Developer ---
|
84 |
+
developer_info = {
|
85 |
+
"confidence_score": f"{avg_max_prob:.4f}",
|
86 |
+
"confidence_status": confidence_status,
|
87 |
+
"explicit_unknown_phrase_detected": is_explicitly_unknown,
|
88 |
+
"explicit_unknown_reason": explicit_unknown_reason if is_explicitly_unknown else "Tidak ada frasa 'tidak tahu' eksplisit.",
|
89 |
+
# "raw_generated_text": generated_text # Bisa diaktifkan untuk debug, tapi akan terlihat di UI
|
90 |
+
}
|
91 |
+
|
92 |
+
# Untuk tampilan user, hanya tampilkan jawabannya.
|
93 |
+
# Informasi developer bisa ditampilkan di antarmuka terpisah atau log.
|
94 |
+
return answer, developer_info
|
95 |
+
|
96 |
+
# --- 3. Fungsi Adaptor untuk Gradio Interface (Mengonversi Dictionary info menjadi String) ---
|
97 |
+
# Gradio Interface mengharapkan output string/angka, bukan dictionary.
|
98 |
+
# Fungsi ini akan mengubah dictionary developer_info menjadi string yang mudah dibaca.
|
99 |
+
def gradio_interface_fn(prompt):
|
100 |
+
answer, dev_info = generate_response_with_dev_info(prompt)
|
101 |
+
|
102 |
+
# Format developer info untuk ditampilkan di Gradio
|
103 |
+
dev_info_str = "--- Developer Info ---\n"
|
104 |
+
dev_info_str += f"Confidence Score: {dev_info['confidence_score']} ({dev_info['confidence_status']})\n"
|
105 |
+
dev_info_str += f"Explicit Unknown Phrase Detected: {dev_info['explicit_unknown_phrase_detected']}\n"
|
106 |
+
dev_info_str += f"Reason: {dev_info['explicit_unknown_reason']}\n"
|
107 |
+
# dev_info_str += f"Raw Generated Text: {dev_info['raw_generated_text']}\n"
|
108 |
+
|
109 |
+
return answer, dev_info_str
|
110 |
+
|
111 |
+
# --- 4. Inisialisasi Antarmuka Gradio ---
|
112 |
+
# Ini yang akan membangun UI di Hugging Face Space.
|
113 |
+
iface = gr.Interface(
|
114 |
+
fn=gradio_interface_fn, # Fungsi yang akan dipanggil saat ada input
|
115 |
+
inputs=gr.Textbox(lines=2, label="Your Question"), # Input berupa kotak teks untuk pertanyaan
|
116 |
+
outputs=[
|
117 |
+
gr.Textbox(label="Chatbot Response", lines=5), # Output pertama untuk jawaban chatbot
|
118 |
+
gr.Textbox(label="Developer Information", lines=5) # Output kedua untuk informasi developer
|
119 |
+
],
|
120 |
+
title="TinyLlama Custom Chatbot with Developer Insights 🚀",
|
121 |
+
description="Ask anything and get a response from the chatbot. Additional information for developers will be displayed below."
|
122 |
+
)
|
123 |
+
|
124 |
+
# --- 5. Jalankan Aplikasi Gradio ---
|
125 |
iface.launch()
|