Download app.py from ktopwal/KomalTopwal-AI-Model-Demo: direct link, hf CLI and curl.
- Browser
- Download file 2.19 kB
-
https://huggingface.co/spaces/ktopwal/KomalTopwal-AI-Model-Demo/resolve/main/app.py
- Command line
-
hf download hf://spaces/ktopwal/KomalTopwal-AI-Model-Demo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ktopwal/KomalTopwal-AI-Model-Demo/resolve/main/app.py
2.19 kB
| import gradio as gr | |
| from transformers_js_py import import_transformers_js | |
| # Load Transformers.js | |
| transformers = await import_transformers_js() | |
| pipeline = transformers.pipeline | |
| # Model 1: Sentiment Analysis | |
| sentiment_model = await pipeline( | |
| "sentiment-analysis", | |
| "Xenova/distilbert-base-uncased-finetuned-sst-2-english" | |
| ) | |
| # Model 2: Text Generation | |
| text_model = await pipeline( | |
| "text-generation", | |
| "Xenova/gpt2" | |
| ) | |
| # Callback 1: Sentiment Analysis | |
| async def analyze_sentiment(text): | |
| if not text or not text.strip(): | |
| return "Please enter some text." | |
| result = await sentiment_model(text) | |
| result = result[0] | |
| return ( | |
| f"Sentiment: {result['label']}\n" | |
| f"Confidence: {result['score']:.2%}" | |
| ) | |
| # Callback 2: Text Generation | |
| async def generate_text(prompt): | |
| if not prompt or not prompt.strip(): | |
| return "Please enter a prompt." | |
| result = await text_model( | |
| prompt, | |
| max_new_tokens=40, | |
| do_sample=True, | |
| temperature=0.7 | |
| ) | |
| return result[0]["generated_text"] | |
| # Gradio GUI | |
| with gr.Blocks(title="AI Model Demo") as demo: | |
| gr.Markdown("# AI Model Demo") | |
| gr.Markdown( | |
| "An application using two pretrained models." | |
| ) | |
| with gr.Tab("Sentiment Analysis"): | |
| sentiment_input = gr.Textbox( | |
| label="Enter a sentence", | |
| placeholder="I love learning artificial intelligence!" | |
| ) | |
| sentiment_button = gr.Button("Analyze Sentiment") | |
| sentiment_output = gr.Textbox(label="Sentiment Result") | |
| sentiment_button.click( | |
| fn=analyze_sentiment, | |
| inputs=sentiment_input, | |
| outputs=sentiment_output | |
| ) | |
| with gr.Tab("Text Generation"): | |
| prompt_input = gr.Textbox( | |
| label="Enter a prompt", | |
| placeholder="Artificial intelligence is" | |
| ) | |
| generate_button = gr.Button("Generate Text") | |
| generated_output = gr.Textbox( | |
| label="Generated Text", | |
| lines=5 | |
| ) | |
| generate_button.click( | |
| fn=generate_text, | |
| inputs=prompt_input, | |
| outputs=generated_output | |
| ) | |
| demo.launch() |