Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🏷️ Zero-Shot Text Classification | CPU-only HF Space
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
|
| 6 |
+
# Load the zero-shot pipeline once at startup
|
| 7 |
+
classifier = pipeline(
|
| 8 |
+
"zero-shot-classification",
|
| 9 |
+
model="facebook/bart-large-mnli",
|
| 10 |
+
device=-1 # CPU only
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
def zero_shot(text: str, labels: str, multi_label: bool):
|
| 14 |
+
if not text.strip() or not labels.strip():
|
| 15 |
+
return []
|
| 16 |
+
# parse comma-separated labels
|
| 17 |
+
candidate_list = [lbl.strip() for lbl in labels.split(",") if lbl.strip()]
|
| 18 |
+
res = classifier(text, candidate_list, multi_label=multi_label)
|
| 19 |
+
# build table of [label, score]
|
| 20 |
+
table = [
|
| 21 |
+
[label, round(score, 3)]
|
| 22 |
+
for label, score in zip(res["labels"], res["scores"])
|
| 23 |
+
]
|
| 24 |
+
return table
|
| 25 |
+
|
| 26 |
+
with gr.Blocks(title="🏷️ Zero-Shot Classifier") as demo:
|
| 27 |
+
gr.Markdown(
|
| 28 |
+
"# 🏷️ Zero-Shot Text Classification\n"
|
| 29 |
+
"Paste any text, list your candidate labels (comma-separated),\n"
|
| 30 |
+
"choose single- or multi-label mode, and see scores instantly."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
with gr.Row():
|
| 34 |
+
text_in = gr.Textbox(
|
| 35 |
+
label="Input Text",
|
| 36 |
+
lines=4,
|
| 37 |
+
placeholder="e.g. The new conditioner left my hair incredibly soft!"
|
| 38 |
+
)
|
| 39 |
+
labels_in = gr.Textbox(
|
| 40 |
+
label="Candidate Labels",
|
| 41 |
+
lines=2,
|
| 42 |
+
placeholder="e.g. Positive, Negative, Question, Feedback"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
multi_in = gr.Checkbox(
|
| 46 |
+
label="Multi-label classification",
|
| 47 |
+
info="Assign multiple labels if checked; otherwise picks the top label."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
run_btn = gr.Button("Classify 🏷️", variant="primary")
|
| 51 |
+
|
| 52 |
+
result_df = gr.Dataframe(
|
| 53 |
+
headers=["Label", "Score"],
|
| 54 |
+
datatype=["str", "number"],
|
| 55 |
+
interactive=False,
|
| 56 |
+
wrap=True,
|
| 57 |
+
label="Prediction Scores"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
run_btn.click(
|
| 61 |
+
zero_shot,
|
| 62 |
+
inputs=[text_in, labels_in, multi_in],
|
| 63 |
+
outputs=result_df
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
demo.launch(server_name="0.0.0.0")
|