Nymbo commited on
Commit
8379d73
1 Parent(s): 4f9ea74

adding lots of tiny gradio snippets

Browse files
Files changed (1) hide show
  1. Snippets.py +252 -0
Snippets.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # zero gpus
2
+
3
+ +import spaces
4
+
5
+ +@spaces.GPU # wherever a GPU is needed to compute
6
+
7
+
8
+
9
+ # INSTALL LIBRARY
10
+ !pip install -q gradio
11
+
12
+ # IMPORT LIBRARY
13
+ import gradio as gr
14
+
15
+ # INCLUDE AT END OF APP.PY
16
+ demo.launch()
17
+
18
+ # TEXT BOX
19
+ import gradio as gr
20
+
21
+ with gr.Blocks() as demo:
22
+ gr.Textbox()
23
+
24
+ # DEAULT BUTTON
25
+ with gr.Blocks() as demo:
26
+ gr.Button()
27
+
28
+ # CLEAR BUTTON
29
+ with gr.Blocks() as demo:
30
+ textbox = gr.Textbox(value="This is some text")
31
+ gr.ClearButton(textbox)
32
+
33
+ if __name__ == "__main__":
34
+
35
+ # UPLOAD BUTTON (.txt & .csv)
36
+ def upload_file(files):
37
+ file_paths = [file.name for file in files]
38
+ return file_paths
39
+
40
+ with gr.Blocks() as demo:
41
+ file_output = gr.File()
42
+ upload_button = gr.UploadButton("Click to Upload a File", file_types=["txt", "csv"], file_count="multiple")
43
+ upload_button.upload(upload_file, upload_button, file_output)
44
+
45
+ # CHECKBOX
46
+ with gr.Blocks() as demo:
47
+ gr.Checkbox()
48
+
49
+ # CHECKBOX GROUP
50
+ with gr.Blocks() as demo:
51
+ gr.CheckboxGroup(choices=["First Choice", "Second Choice", "Third Choice"])
52
+
53
+ # RADIO CHOICES
54
+ with gr.Blocks() as demo:
55
+ gr.Radio(choices=["First Choice", "Second Choice", "Third Choice"])
56
+
57
+ # PROGRESS BAR
58
+ import time
59
+
60
+ def load_set(progress=gr.Progress()):
61
+ imgs = [None] * 24
62
+ for img in progress.tqdm(imgs, desc="Loading..."):
63
+ time.sleep(0.1)
64
+ return "Loaded"
65
+
66
+
67
+ with gr.Blocks() as demo:
68
+ load = gr.Button("Load")
69
+ label = gr.Label(label="Loader")
70
+ load.click(load_set, outputs=label)
71
+
72
+ demo.queue(concurrency_count=20).launch()
73
+
74
+ # DROPDOWN MENU
75
+ with gr.Blocks() as demo:
76
+ gr.Dropdown(choices=["First Choice", "Second Choice", "Third Choice"])
77
+
78
+ # MARKDOWN
79
+ with gr.Blocks() as demo:
80
+ gr.Markdown(value="This _example_ was **written** in [Markdown](https://en.wikipedia.org/wiki/Markdown)\n")
81
+
82
+ # NUMBERS
83
+ with gr.Blocks() as demo:
84
+ gr.Number()
85
+
86
+ # WEBCAM CAPTURE
87
+ def snap(image, video):
88
+ return [image, video]
89
+
90
+
91
+ demo = gr.Interface(
92
+ snap,
93
+ [gr.Image(source="webcam", tool=None), gr.Video(source="webcam")],
94
+ ["image", "video"],
95
+ )
96
+
97
+ if __name__ == "__main__":
98
+
99
+ # CANCEL EVENTS
100
+ import time
101
+ import gradio as gr
102
+
103
+
104
+ def fake_diffusion(steps):
105
+ for i in range(steps):
106
+ print(f"Current step: {i}")
107
+ time.sleep(0.2)
108
+ yield str(i)
109
+
110
+
111
+ def long_prediction(*args, **kwargs):
112
+ time.sleep(10)
113
+ return 42
114
+
115
+
116
+ with gr.Blocks() as demo:
117
+ with gr.Row():
118
+ with gr.Column():
119
+ n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
120
+ run = gr.Button(value="Start Iterating")
121
+ output = gr.Textbox(label="Iterative Output")
122
+ stop = gr.Button(value="Stop Iterating")
123
+ with gr.Column():
124
+ textbox = gr.Textbox(label="Prompt")
125
+ prediction = gr.Number(label="Expensive Calculation")
126
+ run_pred = gr.Button(value="Run Expensive Calculation")
127
+ with gr.Column():
128
+ cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")
129
+ cancel_on_submit = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Submit")
130
+ echo = gr.Textbox(label="Echo")
131
+ with gr.Row():
132
+ with gr.Column():
133
+ image = gr.Image(source="webcam", tool="editor", label="Cancel on edit", interactive=True)
134
+ with gr.Column():
135
+ video = gr.Video(source="webcam", label="Cancel on play", interactive=True)
136
+
137
+ click_event = run.click(fake_diffusion, n, output)
138
+ stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
139
+ pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)
140
+
141
+ cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])
142
+ cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])
143
+ image.edit(None, None, None, cancels=[click_event, pred_event])
144
+ video.play(None, None, None, cancels=[click_event, pred_event])
145
+
146
+ demo.queue(concurrency_count=2, max_size=20)
147
+
148
+ if __name__ == "__main__":
149
+ demo.launch()
150
+
151
+ # WEB SERVER
152
+ import portpicker
153
+ import threading
154
+ import socket
155
+ import IPython
156
+
157
+ from six.moves import socketserver
158
+ from six.moves import SimpleHTTPServer
159
+
160
+ class V6Server(socketserver.TCPServer):
161
+ address_family = socket.AF_INET6
162
+
163
+ class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
164
+ def do_GET(self):
165
+ self.send_response(200)
166
+ # If the response should not be cached in the notebook for
167
+ # offline access:
168
+ # self.send_header('x-colab-notebook-cache-control', 'no-cache')
169
+ self.end_headers()
170
+ self.wfile.write(b'''
171
+ document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));
172
+ ''')
173
+
174
+ port = portpicker.pick_unused_port()
175
+
176
+ def server_entry():
177
+ httpd = V6Server(('::', port), Handler)
178
+ # Handle a single request then exit the thread.
179
+ httpd.serve_forever()
180
+
181
+ thread = threading.Thread(target=server_entry)
182
+ thread.start()
183
+
184
+ # Display some HTML referencing the resource.
185
+ display(IPython.display.HTML('<script src="https://localhost:{port}/"></script>'.format(port=port)))
186
+
187
+ # CREATE WEB SERVER IFRAME
188
+ from google.colab import output
189
+ output.serve_kernel_port_as_iframe(port)
190
+
191
+ # VIEW WEB SERVER AS NEW BROWSER TAB
192
+ from google.colab import output
193
+ output.serve_kernel_port_as_window(port)
194
+
195
+ # CAMERA CAPTURE
196
+ from IPython.display import display, Javascript
197
+ from google.colab.output import eval_js
198
+ from base64 import b64decode
199
+
200
+ def take_photo(filename='photo.jpg', quality=0.8):
201
+ js = Javascript('''
202
+ async function takePhoto(quality) {
203
+ const div = document.createElement('div');
204
+ const capture = document.createElement('button');
205
+ capture.textContent = 'Capture';
206
+ div.appendChild(capture);
207
+
208
+ const video = document.createElement('video');
209
+ video.style.display = 'block';
210
+ const stream = await navigator.mediaDevices.getUserMedia({video: true});
211
+
212
+ document.body.appendChild(div);
213
+ div.appendChild(video);
214
+ video.srcObject = stream;
215
+ await video.play();
216
+
217
+ // Resize the output to fit the video element.
218
+ google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
219
+
220
+ // Wait for Capture to be clicked.
221
+ await new Promise((resolve) => capture.onclick = resolve);
222
+
223
+ const canvas = document.createElement('canvas');
224
+ canvas.width = video.videoWidth;
225
+ canvas.height = video.videoHeight;
226
+ canvas.getContext('2d').drawImage(video, 0, 0);
227
+ stream.getVideoTracks()[0].stop();
228
+ div.remove();
229
+ return canvas.toDataURL('image/jpeg', quality);
230
+ }
231
+ ''')
232
+ display(js)
233
+ data = eval_js('takePhoto({})'.format(quality))
234
+ binary = b64decode(data.split(',')[1])
235
+ with open(filename, 'wb') as f:
236
+ f.write(binary)
237
+ return filename
238
+
239
+
240
+ from IPython.display import Image
241
+ try:
242
+ filename = take_photo()
243
+ print('Saved to {}'.format(filename))
244
+
245
+ # Show the image which was just taken.
246
+ display(Image(filename))
247
+ except Exception as err:
248
+ # Errors will be thrown if the user does not have a webcam or if they do not
249
+ # grant the page permission to access it.
250
+ print(str(err))
251
+
252
+