-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
173 lines (133 loc) · 5.56 KB
/
app.py
File metadata and controls
173 lines (133 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Streamlit UI for zero-shot smart-home intent classification.
The app uses Hugging Face's zero-shot-classification pipeline so it can map
unseen user commands to one of seven predefined intents without fine-tuning.
"""
from __future__ import annotations
from typing import List, Dict
import streamlit as st
from transformers import pipeline
from intent_config import (
CANDIDATE_LABELS,
CANDIDATE_LABEL_TO_INTENT,
HYPOTHESIS_TEMPLATE,
INTENTS,
MODEL_REGISTRY,
)
st.set_page_config(
page_title="Zero-Shot Intent Classifier",
page_icon="AI",
layout="wide",
)
@st.cache_resource(show_spinner=False)
def load_zero_shot_pipeline(model_id: str):
"""Load and cache a Hugging Face zero-shot pipeline for the selected model.
Streamlit keeps this resource in memory across reruns, which prevents the
application from downloading and rebuilding the model on every button click.
"""
return pipeline(
task="zero-shot-classification",
model=model_id,
)
def classify_utterance(user_text: str, model_id: str) -> List[Dict[str, float]]:
"""Run zero-shot inference and return ranked intent predictions."""
classifier = load_zero_shot_pipeline(model_id)
result = classifier(
sequences=user_text,
candidate_labels=CANDIDATE_LABELS,
hypothesis_template=HYPOTHESIS_TEMPLATE,
multi_label=False,
)
ranked_predictions: List[Dict[str, float]] = []
for candidate_label, score in zip(result["labels"], result["scores"]):
ranked_predictions.append(
{
"intent": CANDIDATE_LABEL_TO_INTENT[candidate_label],
"candidate_label": candidate_label,
"score": float(score),
}
)
return ranked_predictions
def render_confidence_bars(predictions: List[Dict[str, float]]) -> None:
"""Show all intent scores as readable confidence bars."""
st.subheader("Confidence Across All 7 Intents")
for prediction in predictions:
label_col, score_col = st.columns([4, 1])
label_col.markdown(f"**{prediction['intent']}**")
score_col.markdown(f"**{prediction['score'] * 100:.2f}%**")
st.progress(int(round(prediction["score"] * 100)))
def main() -> None:
"""Render the full Streamlit application."""
st.title("Zero-Shot Intent Classification for a Voice Assistant")
st.write(
"Zero-shot classification lets a model assign unseen text commands to "
"predefined intents without any task-specific training examples."
)
st.sidebar.header("Ablation Study")
selected_model_label = st.sidebar.selectbox(
"Choose the model used for inference",
options=list(MODEL_REGISTRY.keys()),
help=(
"Switch between the full BART MNLI model and the smaller distilled "
"version to compare speed and confidence behaviour."
),
)
selected_model = MODEL_REGISTRY[selected_model_label]
# Community Cloud has finite memory, so when the user switches models we
# clear the previous cached pipeline and keep only the currently selected
# model warm in memory.
previous_model_id = st.session_state.get("active_model_id")
if previous_model_id and previous_model_id != selected_model["model_id"]:
load_zero_shot_pipeline.clear()
st.session_state["active_model_id"] = selected_model["model_id"]
st.sidebar.info(f"**Model ID:** `{selected_model['model_id']}`")
st.sidebar.caption(selected_model["summary"])
st.sidebar.subheader("Available Intents")
for intent in INTENTS:
st.sidebar.write(f"- {intent}")
st.sidebar.markdown("---")
st.sidebar.caption(
"Ablation idea: run the same utterance with both models and compare the "
"top prediction confidence and response speed."
)
user_text = st.text_area(
"Enter a natural voice command",
placeholder=(
"Examples: 'Set a timer for 20 minutes', "
"'Could you send a message to Sarah?', "
"'It's way too bright in this room.'"
),
height=140,
)
if st.button("Classify", type="primary", use_container_width=True):
cleaned_text = user_text.strip()
if not cleaned_text:
st.warning("Please enter a voice command before clicking Classify.")
return
try:
with st.spinner("Loading model and classifying the command..."):
predictions = classify_utterance(
user_text=cleaned_text,
model_id=selected_model["model_id"],
)
except Exception as error: # pragma: no cover - UI path
st.error("The model could not complete the classification request.")
st.exception(error)
return
top_prediction = predictions[0]
st.markdown("---")
st.subheader("Top Predicted Intent")
st.success(
f"{top_prediction['intent']} "
f"({top_prediction['score'] * 100:.2f}% confidence)"
)
render_confidence_bars(predictions)
with st.expander("Why this is an ablation study"):
st.write(
"The sidebar switches between a large baseline model "
"(`facebook/bart-large-mnli`) and a smaller distilled model "
"(`valhalla/distilbart-mnli-12-3`). By keeping the same 7 intents "
"and the same user command while changing only the model, you can "
"measure how model size affects prediction confidence and speed."
)
if __name__ == "__main__":
main()