Spaces:
Sleeping
Sleeping
Simplify app to only show text classification API integration
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515237 unmodified lines909192939495962 unmodified lines99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297import gradio as grimport timefrom datetime import datetimeimport requestsimport jsondef greet(name, enthusiasm):"""Simple greeting function"""if not name:return "Please enter your name!"exclamation = "!" * enthusiasmgreeting = f"Hello, {name}{exclamation}"return greetingdef calculate(num1, operation, num2):"""Simple calculator"""try:num1 = float(num1)num2 = float(num2)if operation == "Add":result = num1 + num2elif operation == "Subtract":result = num1 - num2elif operation == "Multiply":result = num1 * num2elif operation == "Divide":if num2 == 0:return "Error: Cannot divide by zero!"result = num1 / num2else: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:37 unmodified lineselse: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."2 unmodified linesexcept 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 AppA 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 ClassificationClassify 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 UsageYou can also use this app as an API:```pythonimport requestsresponse = requests.post("https://YOUR-USERNAME-YOUR-SPACE.hf.space/api/predict",json={"data": ["Alice", 3]})print(response.json())```---### About This AppThis is a simple test application for Hugging Face Spaces deployment.- **Framework:** Gradio- **Size:** Lightweight (~5MB)- **Purpose:** Testing deployment and API functionalityBuilt with ❤️ using Gradio""")123456737 unmodified lines454647484950512 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import gradio as grimport requestsimport jsondef classify_text_api(text, labels_str):"""Call the DeBERTa classifier API from the other space"""if not text or not labels_str:37 unmodified lineselse: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."2 unmodified linesexcept Exception as e:return f"❌ Error: {str(e)}"# Create the Gradio interfacewith gr.Blocks(title="Text Classification Test App", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎯 Text Classification Test AppTest the DeBERTa-v3-large-mnli classifier API.This app connects to the DeBERTa classifier space to perform 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""")
app.py+41-219