maddiman's picture
Switch to smaller DistilBERT model for HF free tier compatibility
cb7d043
Raw History Blame Contribute Delete
4.96 kB
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()