Spaces:
Sleeping
Sleeping
Deploy DeBERTa text classifier with Gradio UI
Browse filesFiles changed (3)
- README.md+153-5
- app.pyAdded+161
- requirements.txtAdded+5
123456789101112---title: Text Classifier Apiemoji: 🏃colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 5.49.1app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160---title: Zero-Shot Text Classificationemoji: 🎯colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 4.44.0app_file: app.pypinned: false---# 🎯 Zero-Shot Text Classification APIA powerful text classification API using **microsoft/deberta-v3-large-mnli** model. Classify any text into custom categories without training!## Features- 🚀 **Zero-shot classification** - No training data needed- 🎨 **Interactive Gradio UI** - Easy-to-use web interface- 🔌 **RESTful API** - Programmatic access- 📊 **DeBERTa-v3-large** - State-of-the-art NLI model- 🔒 **Private Space Support** - Can be deployed as private## Usage### Web InterfaceSimply enter your text and comma-separated labels, then click "Classify"!### API Usage#### Python```pythonimport requestsresponse = requests.post("https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space/api/predict",json={"data": ["I absolutely love this product!","positive, negative, neutral",true]})result = response.json()print(result)```#### cURL```bashcurl -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]}'```#### JavaScript/Node.js```javascriptconst response = await fetch("https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space/api/predict", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({data: ["I love this product!","positive, negative, neutral",true]})});const result = await response.json();console.log(result);```## Response Format```json{"text": "I absolutely love this product!","prediction": "positive","confidence": "0.9876","all_scores": {"positive": "0.9876","neutral": "0.0098","negative": "0.0026"},"model": "microsoft/deberta-v3-large-mnli"}```## Model Information- **Model:** microsoft/deberta-v3-large-mnli- **Architecture:** DeBERTa (Decoding-enhanced BERT with disentangled attention)- **Task:** Zero-Shot Classification / Natural Language Inference- **Training Data:** MultiNLI dataset- **License:** MIT## Use Cases- **Sentiment Analysis** - Classify text as positive, negative, or neutral- **Topic Classification** - Categorize content into custom topics- **Intent Detection** - Determine user intent in chatbots- **Content Moderation** - Flag inappropriate content- **Custom Categories** - Any classification task with your own labels!## Examples### Sentiment Analysis```Text: "This movie was amazing! I loved every minute."Labels: positive, negative, neutralResult: positive (0.9821)```### Topic Classification```Text: "The new AI model achieves state-of-the-art results."Labels: technology, politics, sports, entertainmentResult: technology (0.9654)```### Intent Detection```Text: "I want to cancel my subscription"Labels: inquiry, complaint, cancellation, purchaseResult: cancellation (0.9432)```## Local Development1. Install dependencies:```bashpip install -r requirements.txt```2. Run the app:```bashpython app.py```3. Open http://localhost:7860 in your browser## Deployment on Hugging Face SpacesSee DEPLOYMENT.md for detailed instructions.## LicenseMIT License - Feel free to use this in your projects!---Built with ❤️ using Hugging Face Transformers and Gradio
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161import gradio as grfrom transformers import pipelineimport json
# Load the DeBERTa-v3-large-mnli modelprint("Loading model: microsoft/deberta-v3-large-mnli...")classifier = pipeline( "zero-shot-classification", model="microsoft/deberta-v3-large-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": "microsoft/deberta-v3-large-mnli" } else: output = { "text": text, "prediction": result['labels'][0], "confidence": f"{result['scores'][0]:.4f}", "model": "microsoft/deberta-v3-large-mnli" }
return json.dumps(output, indent=2)
except Exception as e: return {"error": f"Classification failed: {str(e)}"}
# Create Gradio interfacewith gr.Blocks(title="Zero-Shot Text Classification") as demo: gr.Markdown( """ # 🎯 Zero-Shot Text Classification
Classify any text into custom categories using **DeBERTa-v3-large-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:** microsoft/deberta-v3-large-mnli - **Task:** Zero-Shot Text Classification - **License:** MIT
Built with ❤️ using Hugging Face Transformers """ )
# Launch the appif __name__ == "__main__": demo.launch()12345gradio>=4.0.0transformers>=4.35.0torch>=2.0.0sentencepiece>=0.1.99protobuf>=3.20.0README.md+153-5
app.pyAdded+161
requirements.txtAdded+5