Spaces:
Sleeping
Sleeping
Add complete Gradio app with DeBERTa integration
Browse filesFiles changed (3)
- README.md+104-5
- app.pyAdded+301
- requirements.txtAdded+2
123456789101112---title: Simple Test Appemoji: ⚡colorFrom: graycolorTo: graysdk: gradiosdk_version: 5.49.1app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111---title: Simple Test Appemoji: 🧪colorFrom: greencolorTo: bluesdk: gradiosdk_version: 4.44.0app_file: app.pypinned: false---# 🧪 Simple Gradio Test AppA lightweight test application to verify Hugging Face Spaces deployment.## Features- **Greeting Generator** - Create personalized greetings with adjustable enthusiasm- **Calculator** - Perform basic arithmetic operations- **Text Reverser** - Reverse any text input- **Timestamp** - Display current server time## PurposeThis is a minimal test app designed to:- ✅ Verify Hugging Face Spaces deployment works- ✅ Test the Gradio interface- ✅ Test API endpoints- ✅ Ensure quick build times (~1 minute)- ✅ Use minimal resources (perfect for free tier)## Local Development```bash# Install dependenciespip install -r requirements.txt# Run the apppython app.py```Open http://localhost:7860 in your browser.## API Usage### Greeting Endpoint```pythonimport requestsresponse = requests.post("https://YOUR-USERNAME-YOUR-SPACE.hf.space/api/predict",json={"data": ["Alice", 3]})print(response.json())```### Calculator Endpoint```pythonresponse = requests.post("https://YOUR-USERNAME-YOUR-SPACE.hf.space/api/predict",json={"data": [10, "Add", 5]})print(response.json())```### cURL Example```bashcurl -X POST "https://YOUR-USERNAME-YOUR-SPACE.hf.space/api/predict" \-H "Content-Type: application/json" \-d '{"data": ["World", 2]}'```## DeploymentThis app deploys in about 1 minute on Hugging Face Spaces (free tier).### Quick Deploy Steps1. Go to https://huggingface.co/spaces2. Click "Create new Space"3. Choose Gradio SDK4. Upload the files:- `app.py`- `requirements.txt`- `README.md`5. Wait ~1 minute for build6. Done!## Tech Stack- **Framework:** Gradio 4.0+- **Language:** Python 3.12- **Size:** ~5MB (very lightweight)- **Build Time:** ~60 seconds## LicenseMIT License - Feel free to use and modify!---Built with ❤️ using GradioPerfect for testing HF Spaces deployment before deploying larger models!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301import gradio as grimport timefrom datetime import datetimeimport requestsimport json
def greet(name, enthusiasm): """Simple greeting function""" if not name: return "Please enter your name!"
exclamation = "!" * enthusiasm greeting = f"Hello, {name}{exclamation}"
return greeting
def calculate(num1, operation, num2): """Simple calculator""" try: num1 = float(num1) num2 = float(num2)
if operation == "Add": result = num1 + num2 elif operation == "Subtract": result = num1 - num2 elif operation == "Multiply": result = num1 * num2 elif operation == "Divide": if num2 == 0: return "Error: Cannot divide by zero!" result = num1 / num2 else: return "Invalid operation"
return f"{num1} {operation.lower()} {num2} = {result}" except ValueError: return "Error: Please enter valid numbers"
def reverse_text(text): """Reverse the input text""" if not text: return "Please enter some text!" return text[::-1]
def get_timestamp(): """Return current timestamp""" return f"Current time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
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}"
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 multiple tabswith gr.Blocks(title="Simple Test App", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # 🧪 Simple Gradio Test App
A lightweight test application to verify Hugging Face Spaces deployment.
**Features:** - Simple greeting generator - Basic calculator - Text reverser - Timestamp display - **🎯 AI Text Classification** - Using DeBERTa-v3-large-mnli """ )
with gr.Tab("Greeting"): gr.Markdown("### Generate a personalized greeting") with gr.Row(): with gr.Column(): name_input = gr.Textbox( label="Your Name", placeholder="Enter your name...", value="World" ) enthusiasm_slider = gr.Slider( minimum=1, maximum=5, value=1, step=1, label="Enthusiasm Level" ) greet_btn = gr.Button("Generate Greeting", variant="primary")
with gr.Column(): greeting_output = gr.Textbox(label="Greeting", lines=3)
greet_btn.click( fn=greet, inputs=[name_input, enthusiasm_slider], outputs=greeting_output )
gr.Examples( examples=[ ["Alice", 3], ["Bob", 1], ["Charlie", 5] ], inputs=[name_input, enthusiasm_slider], outputs=greeting_output, fn=greet, cache_examples=False )
with gr.Tab("Calculator"): gr.Markdown("### Perform basic calculations") with gr.Row(): with gr.Column(): num1_input = gr.Number(label="Number 1", value=10) operation_dropdown = gr.Dropdown( choices=["Add", "Subtract", "Multiply", "Divide"], value="Add", label="Operation" ) num2_input = gr.Number(label="Number 2", value=5) calc_btn = gr.Button("Calculate", variant="primary")
with gr.Column(): calc_output = gr.Textbox(label="Result", lines=2)
calc_btn.click( fn=calculate, inputs=[num1_input, operation_dropdown, num2_input], outputs=calc_output )
with gr.Tab("Text Tools"): gr.Markdown("### Text manipulation tools")
with gr.Row(): text_input = gr.Textbox( label="Input Text", placeholder="Enter text to reverse...", lines=3 ) reverse_output = gr.Textbox( label="Reversed Text", lines=3 )
reverse_btn = gr.Button("Reverse Text", variant="primary") reverse_btn.click( fn=reverse_text, inputs=text_input, outputs=reverse_output )
gr.Markdown("---")
timestamp_output = gr.Textbox(label="Server Timestamp", lines=1) timestamp_btn = gr.Button("Get Timestamp") timestamp_btn.click( fn=get_timestamp, inputs=None, outputs=timestamp_output )
with gr.Tab("🎯 Text Classification"): gr.Markdown( """ ### AI-Powered Zero-Shot Text Classification
Classify any text into custom categories using the **DeBERTa-v3-large-mnli** model.
This tab connects to our DeBERTa classifier space to perform state-of-the-art 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 other space. First request may be slower as the model loads (~30 seconds). """ )
gr.Markdown( """ ---
## 🔌 API Usage
You can also use this app as an API:
```python import requests
response = requests.post( "https://YOUR-USERNAME-YOUR-SPACE.hf.space/api/predict", json={"data": ["Alice", 3]} ) print(response.json()) ```
---
### About This App
This is a simple test application for Hugging Face Spaces deployment. - **Framework:** Gradio - **Size:** Lightweight (~5MB) - **Purpose:** Testing deployment and API functionality
Built with ❤️ using Gradio """ )
# Launch the appif __name__ == "__main__": demo.launch()12gradio>=4.0.0requests>=2.31.0README.md+104-5
app.pyAdded+301
requirements.txtAdded+2