pkashibh commited on
Commit
8c2203f
·
verified ·
1 Parent(s): 6dd1830

Upload 2 files

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