pkashibh commited on
Commit
cb61bbe
·
verified ·
1 Parent(s): 0496fa6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +222 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """gradio.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1Kn9JCj7NyEmbQZD_QTrBwgMiUd42MH-J
8
+ """
9
+
10
+ import gradio as gr
11
+ print("Gradio version:", gr.__version__)
12
+
13
+ import gradio as gr
14
+
15
+ def add_numbers(a, b):
16
+ return a + b
17
+
18
+ demo = gr.Interface(
19
+ fn=add_numbers,
20
+ inputs=["number", "number"],
21
+ outputs="number")
22
+ demo.launch()
23
+
24
+ import gradio as gr
25
+
26
+ def simple_app(name, photo, age, language):
27
+ greeting = f"Hello {name}!"
28
+ info = f"You are {age} years old and prefer {language}."
29
+ return greeting, photo, info
30
+
31
+ demo = gr.Interface(
32
+ fn=simple_app,
33
+ inputs=[
34
+ gr.Textbox(label="Enter your name"),
35
+ gr.Image(label="Upload your photo"),
36
+ gr.Slider(0, 100, label="Your age"),
37
+ gr.Dropdown(["Python", "JavaScript", "C++"], label="Favorite language"), ],
38
+ outputs=[
39
+ gr.Textbox(label="Greeting"),
40
+ gr.Image(label="Your Photo"),
41
+ gr.Textbox(label="Your Info") ],
42
+ )
43
+ demo.launch()
44
+
45
+ import gradio as gr
46
+
47
+ def greet(name):
48
+ return f"Hello, {name}!"
49
+
50
+ with gr.Blocks() as demo:
51
+ name = gr.Textbox(label="Enter your name")
52
+ button = gr.Button("Greet")
53
+ output = gr.Textbox(label="Greeting")
54
+ button.click(fn=greet, inputs=name, outputs=output)
55
+
56
+ demo.launch()
57
+
58
+ import gradio as gr
59
+
60
+ def age_alert(age):
61
+ return "You are", age,"years old!"
62
+
63
+ with gr.Blocks() as demo:
64
+ age_input = gr.Slider(0, 100, label="Select your age")
65
+ output = gr.Textbox(label="Age Info")
66
+ age_input.change(fn=age_alert, inputs=age_input, outputs=output)
67
+
68
+ demo.launch()
69
+
70
+ import gradio as gr
71
+ import requests
72
+
73
+ def get_joke():
74
+ response = requests.get("https://official-joke-api.appspot.com/random_joke")
75
+ if response.status_code == 200:
76
+ joke = response.json()
77
+ return f"{joke['setup']} {joke['punchline']}"
78
+ else:
79
+ return "Oops! Could not fetch a joke right now."
80
+
81
+ with gr.Blocks() as demo:
82
+ btn = gr.Button("Tell me a joke!")
83
+ output = gr.Textbox(label="Here's your joke")
84
+ btn.click(fn=get_joke, inputs=None, outputs=output)
85
+
86
+ demo.launch()
87
+
88
+ """Sentiment Analyzer UI"""
89
+
90
+ import gradio as gr
91
+ from transformers import pipeline
92
+
93
+ sentiment_pipeline = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
94
+
95
+ def analyze_sentiment(text):
96
+ result = sentiment_pipeline(text)[0]
97
+ label = result['label']
98
+ score = result['score']
99
+ return f"Sentiment: {label}\nConfidence: {score:.2f}"
100
+
101
+ gr.Interface(
102
+ fn=analyze_sentiment,
103
+ inputs=gr.Textbox(lines=3, placeholder="Type your sentence here..", label="Input Text"),
104
+ outputs=gr.Textbox(label="Sentiment Result"),
105
+ title="Sentiment Analyzer",
106
+ description="Enter a sentence and find out its sentiment based on score."
107
+ ).launch()
108
+
109
+ """Creating Interfaces For Classic ML Models
110
+
111
+ Setup the Project
112
+ """
113
+
114
+ pip install scikit-learn gradio pandas
115
+
116
+ """Train a Simple Model"""
117
+
118
+ # Load dataset
119
+ from sklearn.datasets import fetch_california_housing
120
+ import pandas as pd
121
+ from sklearn.model_selection import train_test_split
122
+ from sklearn.pipeline import make_pipeline
123
+ from sklearn.preprocessing import StandardScaler
124
+ from sklearn.ensemble import RandomForestRegressor
125
+
126
+ data = fetch_california_housing(as_frame=True)
127
+ df = data.frame
128
+
129
+ X = df.drop(columns=["MedHouseVal"])
130
+ y = df["MedHouseVal"]
131
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
132
+
133
+ model = make_pipeline(StandardScaler(), RandomForestRegressor())
134
+ model.fit(X_train, y_train)
135
+
136
+ """Create Prediction Function"""
137
+
138
+ def predict_house_price(med_inc, house_age, ave_rooms, ave_bedrooms, population,
139
+ ave_occup, latitude, longitude):
140
+ input_data = pd.DataFrame([[ med_inc, house_age, ave_rooms, ave_bedrooms,
141
+ population, ave_occup, latitude, longitude]], columns=X.columns)
142
+ prediction = model.predict(input_data)[0]
143
+ return f"Predicted Price: ${prediction * 100000:.2f}"
144
+
145
+ """Build the Gradio Interface"""
146
+
147
+ import gradio as gr
148
+
149
+ interface = gr.Interface(
150
+ fn=predict_house_price,
151
+ inputs=[
152
+ gr.Slider(0.0, 20.0, label="Median Income (10k$ units)"),
153
+ gr.Slider(1, 50, label="House Age"),
154
+ gr.Slider(1, 10, label="Average Rooms"),
155
+ gr.Slider(1, 5, label="Average Bedrooms"),
156
+ gr.Slider(100, 50000, label="Population"),
157
+ gr.Slider(1, 10, label="Average Occupancy"),
158
+ gr.Slider(32, 42, label="Latitude"),
159
+ gr.Slider(-125, -114, label="Longitude"),
160
+ ],
161
+ outputs="text",
162
+ title="California House Price Predictor",
163
+ description="Enter basic housing info to estimate price",
164
+ )
165
+
166
+ interface.launch(share=True)
167
+
168
+
169
+
170
+ """Deploying Gradio Apps
171
+ Step 1: Prepare Your Files
172
+ You’ll need 3 files in your project folder:
173
+
174
+ 1. app.py
175
+
176
+ 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.
177
+
178
+ 2. requirements.txt
179
+
180
+ This file tells Hugging Face what Python libraries are needed to run your app. Create a requirements.txt file with this content:
181
+
182
+ gradio
183
+ pandas
184
+ scikit-learn
185
+
186
+ Hugging Face installs these packages in the background. If you miss one, your app might crash!
187
+
188
+ 3. README.md (Optional)
189
+
190
+ It is a project description for Hugging Face viewers. Add a README.md with a short intro to your app. Example:
191
+
192
+ California House Price Predictor
193
+
194
+ This Gradio app predicts the median house price in California based on features like income, age, rooms, etc.
195
+
196
+ Built using: - Scikit-learn
197
+ - Gradio
198
+ - California Housing Dataset
199
+
200
+ Step 2: Create a Hugging Face Space
201
+ Go to Hugging Face Space and click on “Create new Space”.
202
+
203
+ Fill the details:
204
+
205
+ Space name: e.g., california-house-predictor
206
+ Space SDK: Choose Gradio
207
+ Visibility: Public or Private
208
+ Click “Create Space”
209
+ Step 3: Upload Your Files
210
+ You’ll be taken to the Space repo view. Now:
211
+
212
+ Click “Files”
213
+ Click “Add file” --> Upload files
214
+ Upload: app.py, requirements.txt and README.md (optional)
215
+ Step 4: Wait for Build
216
+ Once files are uploaded:
217
+
218
+ Hugging Face will automatically install dependencies from requirements.txt
219
+ Then it will run app.py, which launches the Gradio interface
220
+ After a few seconds to minutes, your app will be live in the browser!
221
+ """
222
+
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ pandas
3
+ scikit-learn