Spaces:
Sleeping
Sleeping
| # -*- coding: utf-8 -*- | |
| """gradio.ipynb | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1Kn9JCj7NyEmbQZD_QTrBwgMiUd42MH-J | |
| """ | |
| import gradio as gr | |
| print("Gradio version:", gr.__version__) | |
| import gradio as gr | |
| def add_numbers(a, b): | |
| return a + b | |
| demo = gr.Interface( | |
| fn=add_numbers, | |
| inputs=["number", "number"], | |
| outputs="number") | |
| demo.launch() | |
| import gradio as gr | |
| def simple_app(name, photo, age, language): | |
| greeting = f"Hello {name}!" | |
| info = f"You are {age} years old and prefer {language}." | |
| return greeting, photo, info | |
| demo = gr.Interface( | |
| fn=simple_app, | |
| inputs=[ | |
| gr.Textbox(label="Enter your name"), | |
| gr.Image(label="Upload your photo"), | |
| gr.Slider(0, 100, label="Your age"), | |
| gr.Dropdown(["Python", "JavaScript", "C++"], label="Favorite language"), ], | |
| outputs=[ | |
| gr.Textbox(label="Greeting"), | |
| gr.Image(label="Your Photo"), | |
| gr.Textbox(label="Your Info") ], | |
| ) | |
| demo.launch() | |
| import gradio as gr | |
| def greet(name): | |
| return f"Hello, {name}!" | |
| with gr.Blocks() as demo: | |
| name = gr.Textbox(label="Enter your name") | |
| button = gr.Button("Greet") | |
| output = gr.Textbox(label="Greeting") | |
| button.click(fn=greet, inputs=name, outputs=output) | |
| demo.launch() | |
| import gradio as gr | |
| def age_alert(age): | |
| return "You are", age,"years old!" | |
| with gr.Blocks() as demo: | |
| age_input = gr.Slider(0, 100, label="Select your age") | |
| output = gr.Textbox(label="Age Info") | |
| age_input.change(fn=age_alert, inputs=age_input, outputs=output) | |
| demo.launch() | |
| import gradio as gr | |
| import requests | |
| def get_joke(): | |
| response = requests.get("https://official-joke-api.appspot.com/random_joke") | |
| if response.status_code == 200: | |
| joke = response.json() | |
| return f"{joke['setup']} {joke['punchline']}" | |
| else: | |
| return "Oops! Could not fetch a joke right now." | |
| with gr.Blocks() as demo: | |
| btn = gr.Button("Tell me a joke!") | |
| output = gr.Textbox(label="Here's your joke") | |
| btn.click(fn=get_joke, inputs=None, outputs=output) | |
| demo.launch() | |
| """Sentiment Analyzer UI""" | |
| import gradio as gr | |
| from transformers import pipeline | |
| sentiment_pipeline = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment") | |
| def analyze_sentiment(text): | |
| result = sentiment_pipeline(text)[0] | |
| label = result['label'] | |
| score = result['score'] | |
| return f"Sentiment: {label}\nConfidence: {score:.2f}" | |
| gr.Interface( | |
| fn=analyze_sentiment, | |
| inputs=gr.Textbox(lines=3, placeholder="Type your sentence here..", label="Input Text"), | |
| outputs=gr.Textbox(label="Sentiment Result"), | |
| title="Sentiment Analyzer", | |
| description="Enter a sentence and find out its sentiment based on score." | |
| ).launch() | |
| """Creating Interfaces For Classic ML Models | |
| Setup the Project | |
| """ | |
| """Train a Simple Model""" | |
| # Load dataset | |
| from sklearn.datasets import fetch_california_housing | |
| import pandas as pd | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.pipeline import make_pipeline | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.ensemble import RandomForestRegressor | |
| data = fetch_california_housing(as_frame=True) | |
| df = data.frame | |
| X = df.drop(columns=["MedHouseVal"]) | |
| y = df["MedHouseVal"] | |
| X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) | |
| model = make_pipeline(StandardScaler(), RandomForestRegressor()) | |
| model.fit(X_train, y_train) | |
| """Create Prediction Function""" | |
| def predict_house_price(med_inc, house_age, ave_rooms, ave_bedrooms, population, | |
| ave_occup, latitude, longitude): | |
| input_data = pd.DataFrame([[ med_inc, house_age, ave_rooms, ave_bedrooms, | |
| population, ave_occup, latitude, longitude]], columns=X.columns) | |
| prediction = model.predict(input_data)[0] | |
| return f"Predicted Price: ${prediction * 100000:.2f}" | |
| """Build the Gradio Interface""" | |
| import gradio as gr | |
| interface = gr.Interface( | |
| fn=predict_house_price, | |
| inputs=[ | |
| gr.Slider(0.0, 20.0, label="Median Income (10k$ units)"), | |
| gr.Slider(1, 50, label="House Age"), | |
| gr.Slider(1, 10, label="Average Rooms"), | |
| gr.Slider(1, 5, label="Average Bedrooms"), | |
| gr.Slider(100, 50000, label="Population"), | |
| gr.Slider(1, 10, label="Average Occupancy"), | |
| gr.Slider(32, 42, label="Latitude"), | |
| gr.Slider(-125, -114, label="Longitude"), | |
| ], | |
| outputs="text", | |
| title="California House Price Predictor", | |
| description="Enter basic housing info to estimate price", | |
| ) | |
| interface.launch(share=True) | |
| """Deploying Gradio Apps | |
| Step 1: Prepare Your Files | |
| You’ll need 3 files in your project folder: | |
| 1. app.py | |
| Save your code in a file called app.py. This is the main app file. Hugging Face Spaces will run this file to launch your Gradio UI. | |
| 2. requirements.txt | |
| This file tells Hugging Face what Python libraries are needed to run your app. Create a requirements.txt file with this content: | |
| gradio | |
| pandas | |
| scikit-learn | |
| Hugging Face installs these packages in the background. If you miss one, your app might crash! | |
| 3. README.md (Optional) | |
| It is a project description for Hugging Face viewers. Add a README.md with a short intro to your app. Example: | |
| California House Price Predictor | |
| This Gradio app predicts the median house price in California based on features like income, age, rooms, etc. | |
| Built using: - Scikit-learn | |
| - Gradio | |
| - California Housing Dataset | |
| Step 2: Create a Hugging Face Space | |
| Go to Hugging Face Space and click on “Create new Space”. | |
| Fill the details: | |
| Space name: e.g., california-house-predictor | |
| Space SDK: Choose Gradio | |
| Visibility: Public or Private | |
| Click “Create Space” | |
| Step 3: Upload Your Files | |
| You’ll be taken to the Space repo view. Now: | |
| Click “Files” | |
| Click “Add file” --> Upload files | |
| Upload: app.py, requirements.txt and README.md (optional) | |
| Step 4: Wait for Build | |
| Once files are uploaded: | |
| Hugging Face will automatically install dependencies from requirements.txt | |
| Then it will run app.py, which launches the Gradio interface | |
| After a few seconds to minutes, your app will be live in the browser! | |
| """ | |