Spaces:
Sleeping
Sleeping
File size: 9,323 Bytes
e2ff4e7 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 e2ff4e7 dcd75a7 e2ff4e7 dcd75a7 e2ff4e7 dcd75a7 e2ff4e7 fb4889d e2ff4e7 fb4889d e2ff4e7 d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d d4033b5 fb4889d 28dd2df e2ff4e7 dcd75a7 e2ff4e7 dcd75a7 e2ff4e7 dcd75a7 e2ff4e7 dcd75a7 e2ff4e7 | 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | 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()
|