Spaces:
Sleeping
Sleeping
File size: 4,963 Bytes
79a3e7e cb7d043 79a3e7e cb7d043 79a3e7e cb7d043 79a3e7e cb7d043 79a3e7e 7de90f8 79a3e7e cb7d043 79a3e7e cb7d043 79a3e7e | 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 | import gradio as gr
from transformers import pipeline
import json
# Load the zero-shot classification model (smaller model for free tier)
print("Loading model: typeform/distilbert-base-uncased-mnli...")
classifier = pipeline(
"zero-shot-classification",
model="typeform/distilbert-base-uncased-mnli",
device=-1 # Use CPU
)
print("Model loaded successfully!")
def classify_text(text, labels_str, return_all_scores=True):
"""
Classify text using zero-shot classification
Args:
text: Text to classify
labels_str: Comma-separated labels
return_all_scores: Whether to return all scores or just top prediction
Returns:
dict with classification results
"""
if not text or not labels_str:
return {"error": "Please provide both text and labels"}
# Parse labels
labels = [label.strip() for label in labels_str.split(',')]
if len(labels) < 2:
return {"error": "Please provide at least 2 labels separated by commas"}
try:
# Perform classification
result = classifier(text, labels, multi_label=False)
# Format results
if return_all_scores:
scores_dict = {label: f"{score:.4f}" for label, score in zip(result['labels'], result['scores'])}
output = {
"text": text,
"prediction": result['labels'][0],
"confidence": f"{result['scores'][0]:.4f}",
"all_scores": scores_dict,
"model": "typeform/distilbert-base-uncased-mnli"
}
else:
output = {
"text": text,
"prediction": result['labels'][0],
"confidence": f"{result['scores'][0]:.4f}",
"model": "typeform/distilbert-base-uncased-mnli"
}
return output
except Exception as e:
return {"error": f"Classification failed: {str(e)}"}
# Create Gradio interface
with gr.Blocks(title="Zero-Shot Text Classification") as demo:
gr.Markdown(
"""
# 🎯 Zero-Shot Text Classification
Classify any text into custom categories using **DistilBERT-base-uncased-mnli** model.
This model can classify text into any categories you define, without needing training data!
"""
)
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Text to Classify",
placeholder="Enter the text you want to classify...",
lines=5
)
labels_input = gr.Textbox(
label="Labels (comma-separated)",
placeholder="positive, negative, neutral",
value="positive, negative, neutral"
)
show_all_scores = gr.Checkbox(
label="Show all label scores",
value=True
)
classify_btn = gr.Button("Classify", variant="primary")
with gr.Column():
output = gr.JSON(label="Classification Results")
# Examples
gr.Examples(
examples=[
["I absolutely love this product! Best purchase ever!", "positive, negative, neutral", True],
["Python is a programming language used for data science.", "technology, politics, sports, entertainment", True],
["The movie was boring and too long.", "positive, negative, neutral", True],
["Climate change is a pressing global issue.", "politics, science, entertainment, sports", True],
],
inputs=[text_input, labels_input, show_all_scores],
outputs=output,
fn=classify_text,
cache_examples=False,
)
classify_btn.click(
fn=classify_text,
inputs=[text_input, labels_input, show_all_scores],
outputs=output
)
gr.Markdown(
"""
---
## 🔌 API Usage
You can also use this as an API endpoint:
**POST Request:**
```python
import requests
response = requests.post(
"https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space/api/predict",
json={
"data": [
"I love this product!",
"positive, negative, neutral",
true
]
}
)
print(response.json())
```
**cURL:**
```bash
curl -X POST "https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space/api/predict" \\
-H "Content-Type: application/json" \\
-d '{"data": ["I love this product!", "positive, negative, neutral", true]}'
```
---
### Model Information
- **Model:** typeform/distilbert-base-uncased-mnli
- **Task:** Zero-Shot Text Classification
- **License:** MIT
Built with ❤️ using Hugging Face Transformers
"""
)
# Launch the app
if __name__ == "__main__":
demo.launch()
|