multimodalart HF staff commited on
Commit
79410c2
1 Parent(s): 338c3f7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from io import BytesIO
4
+ from PIL import Image
5
+ import base64
6
+
7
+ blocks = gr.Blocks()
8
+ canvas_html = "<div id='canvas-root'></div>"
9
+ load_js = """
10
+ async () => {
11
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
12
+ fetch(url)
13
+ .then(res => res.text())
14
+ .then(text => {
15
+ const script = document.createElement('script');
16
+ script.type = "module"
17
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
18
+ document.head.appendChild(script);
19
+ });
20
+ }
21
+ """
22
+
23
+ get_js_colors = """
24
+ async (canvasData) => {
25
+ const canvasEl = document.getElementById("canvas-root");
26
+ return [canvasEl._data]
27
+ }
28
+ """
29
+
30
+ set_canvas_size ="""
31
+ async (aspect) => {
32
+ if(aspect ==='square'){
33
+ _updateCanvas(512,512)
34
+ }
35
+ if(aspect ==='horizontal'){
36
+ _updateCanvas(768,512)
37
+ }
38
+ if(aspect ==='vertical'){
39
+ _updateCanvas(512,768)
40
+ }
41
+ }
42
+ """
43
+
44
+ def predict(canvas_data):
45
+ colors = canvas_data['colors']
46
+ base64_img = canvas_data['image']
47
+ image_data = base64.b64decode(base64_img.split(',')[1])
48
+ image = Image.open(BytesIO(image_data))
49
+ return colors, image
50
+
51
+
52
+ with blocks:
53
+ canvas_data = gr.JSON(value={}, visible=False)
54
+ with gr.Row():
55
+ with gr.Column(visible=True) as box_el:
56
+ aspect = gr.Radio(choices=["square", "horizontal", "vertical"])
57
+ canvas = gr.HTML(canvas_html)
58
+ with gr.Column(visible=True) as box_el:
59
+ colors_out = gr.JSON()
60
+ image_out = gr.Image()
61
+
62
+ aspect.change(None, inputs=[aspect], outputs=None, _js = set_canvas_size)
63
+ btn = gr.Button("Run")
64
+ btn.click(fn=predict, inputs=[canvas_data], outputs=[colors_out, image_out], _js=get_js_colors)
65
+ blocks.load(None, None, None, _js=load_js)
66
+
67
+ blocks.launch(debug=True, inline=True,)