Spaces:
Sleeping

simple-test-app / app.py
maddiman's picture
Update markdown tab to use DeBERTa classification with markdown formatted output
d4033b5
Raw History Blame Contribute Delete
9.32 kB
import gradio as gr
import requests
import json
from datetime import datetime
def classify_with_markdown(text, labels_str):
"""Call DeBERTa API and return markdown formatted results"""
if not text or not labels_str:
return "❌ Please provide both text and labels"
# Parse labels
labels = [label.strip() for label in labels_str.split(',')]
if len(labels) < 2:
return "❌ Please provide at least 2 labels separated by commas"
try:
# Call the DeBERTa classifier API
api_url = "https://maddiman-text-classifier-api.hf.space/api/predict"
response = requests.post(
api_url,
json={"data": [text, labels_str, True]},
timeout=60
)
if response.status_code == 200:
result = response.json()
# Format the output as markdown
if "data" in result and len(result["data"]) > 0:
classification_result = json.loads(result["data"][0])
output = f"""
# 🎯 DeBERTa Classification Results
**Timestamp:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
---
## πŸ“ Input Text
> {classification_result['text']}
---
## πŸ† Top Prediction
**{classification_result['prediction'].upper()}**
Confidence: `{classification_result['confidence']}`
---
## πŸ“Š All Classification Scores
| Label | Score | Bar |
|-------|-------|-----|
"""
# Add scores table
for label, score in classification_result['all_scores'].items():
bar_length = int(float(score) * 20)
bar = "β–ˆ" * bar_length
output += f"| **{label}** | {score} | {bar} |\n"
output += f"""
---
## ℹ️ Model Information
- **Model:** `{classification_result['model']}`
- **Type:** Zero-Shot Classification
- **Framework:** Hugging Face Transformers
---
βœ… **Status:** Successfully classified using DeBERTa API with markdown formatting!
"""
return output
else:
return "❌ Error: Unexpected response format"
else:
return f"❌ **Error:** API returned status code `{response.status_code}`\n\nMake sure the classifier API is public and running."
except requests.exceptions.Timeout:
return "⏱️ **Timeout Error**\n\nThe request timed out. The model may still be loading. Please try again in a few minutes."
except requests.exceptions.ConnectionError:
return "πŸ”Œ **Connection Error**\n\nCould not connect to the classifier API. Make sure the DeBERTa space is running."
except Exception as e:
return f"❌ **Error:** {str(e)}"
def classify_text_api(text, labels_str):
"""Call the DeBERTa classifier API from the other space"""
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:
# Call the DeBERTa classifier API
api_url = "https://maddiman-text-classifier-api.hf.space/api/predict"
response = requests.post(
api_url,
json={"data": [text, labels_str, True]},
timeout=60
)
if response.status_code == 200:
result = response.json()
# Format the output nicely
if "data" in result and len(result["data"]) > 0:
classification_result = json.loads(result["data"][0])
output = f"βœ… **Classification Result**\n\n"
output += f"**Text:** {classification_result['text']}\n\n"
output += f"**Top Prediction:** {classification_result['prediction']} "
output += f"(confidence: {classification_result['confidence']})\n\n"
output += f"**All Scores:**\n"
for label, score in classification_result['all_scores'].items():
output += f"- {label}: {score}\n"
output += f"\n**Model:** {classification_result['model']}"
return output
else:
return "❌ Error: Unexpected response format"
else:
return f"❌ Error: API returned status code {response.status_code}. Make sure the classifier API is public and running."
except requests.exceptions.Timeout:
return "⏱️ Error: Request timed out. The model may still be loading. Please try again in a few minutes."
except requests.exceptions.ConnectionError:
return "πŸ”Œ Error: Could not connect to the classifier API. Make sure the DeBERTa space is running."
except Exception as e:
return f"❌ Error: {str(e)}"
# Create the Gradio interface
with gr.Blocks(title="Text Classification Test App", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# 🎯 Text Classification Test App
Test the DeBERTa-v3-large-mnli classifier API and markdown formatting.
**Features:**
- πŸ“ Markdown Formatter (local testing - no API required)
- πŸ€– AI Text Classification (calls DeBERTa API)
"""
)
with gr.Tab("πŸ“ Markdown Output"):
gr.Markdown(
"""
### DeBERTa Classification with Markdown Formatting
This tab uses the DeBERTa classifier API and returns beautifully formatted markdown results.
"""
)
with gr.Row():
with gr.Column():
markdown_text_input = gr.Textbox(
label="Text to Classify",
placeholder="Enter text to classify...",
lines=5,
value="I absolutely love this product! Best purchase ever!"
)
markdown_labels_input = gr.Textbox(
label="Labels (comma-separated)",
placeholder="positive, negative, neutral",
value="positive, negative, neutral"
)
markdown_btn = gr.Button("Classify with Markdown", variant="primary")
with gr.Column():
markdown_output = gr.Markdown(label="Markdown Results")
markdown_btn.click(
fn=classify_with_markdown,
inputs=[markdown_text_input, markdown_labels_input],
outputs=markdown_output
)
gr.Examples(
examples=[
["I absolutely love this product! Best purchase ever!", "positive, negative, neutral"],
["Python is a programming language used for data science.", "technology, politics, sports, entertainment"],
["The movie was boring and too long.", "positive, negative, neutral"],
],
inputs=[markdown_text_input, markdown_labels_input],
outputs=markdown_output,
fn=classify_with_markdown,
cache_examples=False
)
with gr.Tab("πŸ€– AI Classification"):
gr.Markdown(
"""
### AI Text Classification
This tab calls the DeBERTa classifier API for zero-shot text classification.
"""
)
with gr.Row():
with gr.Column():
classify_text_input = gr.Textbox(
label="Text to Classify",
placeholder="Enter the text you want to classify...",
lines=5,
value="I absolutely love this product! Best purchase ever!"
)
classify_labels_input = gr.Textbox(
label="Labels (comma-separated)",
placeholder="positive, negative, neutral",
value="positive, negative, neutral"
)
classify_btn = gr.Button("Classify Text", variant="primary")
with gr.Column():
classify_output = gr.Markdown(label="Classification Results")
classify_btn.click(
fn=classify_text_api,
inputs=[classify_text_input, classify_labels_input],
outputs=classify_output
)
gr.Examples(
examples=[
["I absolutely love this product! Best purchase ever!", "positive, negative, neutral"],
["Python is a programming language used for data science.", "technology, politics, sports, entertainment"],
["The movie was boring and too long.", "positive, negative, neutral"],
["Climate change is a pressing global issue.", "politics, science, entertainment, sports"],
["This restaurant has excellent food and service!", "positive, negative, neutral"],
],
inputs=[classify_text_input, classify_labels_input],
outputs=classify_output,
fn=classify_text_api,
cache_examples=False
)
gr.Markdown(
"""
---
**Note:** This feature calls the DeBERTa classifier API from our text-classifier-api space.
First request may be slower as the model loads (~30 seconds).
**API Endpoint:** https://maddiman-text-classifier-api.hf.space/api/predict
---
Built with ❀️ using Gradio
"""
)
# Launch the app
if __name__ == "__main__":
demo.launch()