Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
from typing import Dict
|
| 4 |
|
|
@@ -27,10 +28,21 @@ def classify_text(
|
|
| 27 |
Returns:
|
| 28 |
Dict[str, float]: A dictionary mapping each label to its classification score.
|
| 29 |
"""
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# Example Input with Mutually Exclusive Labels from News Articles
|
| 36 |
examples = [
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
from transformers import pipeline
|
| 4 |
from typing import Dict
|
| 5 |
|
|
|
|
| 28 |
Returns:
|
| 29 |
Dict[str, float]: A dictionary mapping each label to its classification score.
|
| 30 |
"""
|
| 31 |
+
if not text.strip():
|
| 32 |
+
return "Error: Please enter some text to classify."
|
| 33 |
+
if not labels.strip():
|
| 34 |
+
return "Error: Please enter some labels to classify the text."
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
# Set device: 0 if GPU available, else -1 for CPU
|
| 38 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 39 |
+
|
| 40 |
+
classifier = pipeline("zero-shot-classification", model=model_name, device=device)
|
| 41 |
+
labels_list = [label.strip() for label in labels.split(",")]
|
| 42 |
+
result = classifier(text, candidate_labels=labels_list)
|
| 43 |
+
return {label: score for label, score in zip(result["labels"], result["scores"])}
|
| 44 |
+
except Exception as _:
|
| 45 |
+
return "Error: An unexpected error occurred. Please try again later."
|
| 46 |
|
| 47 |
# Example Input with Mutually Exclusive Labels from News Articles
|
| 48 |
examples = [
|