File size: 6,301 Bytes
8c2203f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- 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
"""

pip install scikit-learn gradio pandas

"""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!
"""