Files changed (1) hide show
  1. app.py +0 -255
app.py DELETED
@@ -1,255 +0,0 @@
1
- import gradio as gr
2
- from PIL import Image
3
- from urllib.parse import urlparse
4
- import requests
5
- import time
6
- import os
7
-
8
- from utils.gradio_helpers import parse_outputs, process_outputs
9
-
10
- # Function to verify the image file type and resize it if necessary
11
- def preprocess_image(image_path):
12
- # Check if the file exists
13
- if not os.path.exists(image_path):
14
- raise FileNotFoundError(f"No such file: '{image_path}'")
15
-
16
- # Get the file extension and make sure it's a valid image format
17
- valid_extensions = ['jpg', 'jpeg', 'png', 'webp']
18
- file_extension = image_path.split('.')[-1].lower()
19
-
20
- if file_extension not in valid_extensions:
21
- raise ValueError("Invalid file type. Only JPG, PNG, and WEBP are allowed.")
22
-
23
- # Open the image
24
- with Image.open(image_path) as img:
25
- width, height = img.size
26
-
27
- # Check if any dimension exceeds 1024 pixels
28
- if width > 1024 or height > 1024:
29
- # Calculate the new size while maintaining aspect ratio
30
- if width > height:
31
- new_width = 1024
32
- new_height = int((new_width / width) * height)
33
- else:
34
- new_height = 1024
35
- new_width = int((new_height / height) * width)
36
-
37
- # Resize the image
38
- img_resized = img.resize((new_width, new_height), Image.LANCZOS)
39
- print(f"Resized image to {new_width}x{new_height}.")
40
-
41
- # Save the resized image as 'resized_image.jpg'
42
- output_path = 'resized_image.jpg'
43
- img_resized.save(output_path, 'JPEG')
44
- print(f"Resized image saved as {output_path}")
45
- return output_path
46
- else:
47
- print("Image size is within the limit, no resizing needed.")
48
- return image_path
49
-
50
-
51
- def display_uploaded_image(image_in):
52
- return image_in
53
-
54
- def reset_parameters():
55
- return gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0), gr.update(value=0)
56
-
57
- names = ['image', 'rotate_pitch', 'rotate_yaw', 'rotate_roll', 'blink', 'eyebrow', 'wink', 'pupil_x', 'pupil_y', 'aaa', 'eee', 'woo', 'smile', 'src_ratio', 'sample_ratio', 'crop_factor', 'output_format', 'output_quality']
58
-
59
- def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):
60
- headers = {'Content-Type': 'application/json'}
61
-
62
- payload = {"input": {}}
63
-
64
-
65
- base_url = "http://0.0.0.0:7860"
66
- for i, key in enumerate(names):
67
- value = args[i]
68
- if value and (os.path.exists(str(value))):
69
- value = f"{base_url}/gradio_api/file=" + value
70
- if value is not None and value != "":
71
- payload["input"][key] = value
72
-
73
- time.sleep(0.5)
74
- response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)
75
-
76
-
77
- if response.status_code == 201:
78
- time.sleep(0.5)
79
- follow_up_url = response.json()["urls"]["get"]
80
- response = requests.get(follow_up_url, headers=headers)
81
- while response.json()["status"] != "succeeded":
82
- if response.json()["status"] == "failed":
83
- raise gr.Error("The submission failed!")
84
- response = requests.get(follow_up_url, headers=headers)
85
-
86
- if response.status_code == 200:
87
-
88
- json_response = response.json()
89
- #If the output component is JSON return the entire output response
90
- if(outputs[0].get_config()["name"] == "json"):
91
- return json_response["output"]
92
- predict_outputs = parse_outputs(json_response["output"])
93
- processed_outputs = process_outputs(predict_outputs)
94
- print(f"processed_outputs: {processed_outputs}")
95
- return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]
96
- else:
97
- time.sleep(1)
98
- if(response.status_code == 409):
99
- raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")
100
- raise gr.Error(f"The submission failed! Error: {response.status_code}")
101
-
102
-
103
- css = '''
104
- #col-container{max-width: 800px;margin: 0 auto;}
105
- '''
106
- with gr.Blocks(css=css) as demo:
107
- with gr.Column(elem_id="col-container"):
108
- gr.Markdown("# Expression Editor")
109
- gr.Markdown("Demo for expression-editor cog image by fofr")
110
- with gr.Row():
111
- with gr.Column():
112
- image = gr.Image(
113
- label="Input image",
114
- sources=["upload"],
115
- type="filepath",
116
- height=180
117
- )
118
- with gr.Tab("HEAD"):
119
- with gr.Column():
120
- rotate_pitch = gr.Slider(
121
- label="Rotate Up-Down",
122
- value=0,
123
- minimum=-20, maximum=20
124
- )
125
- rotate_yaw = gr.Slider(
126
- label="Rotate Left-Right turn",
127
- value=0,
128
- minimum=-20, maximum=20
129
- )
130
- rotate_roll = gr.Slider(
131
- label="Rotate Left-Right tilt", value=0,
132
- minimum=-20, maximum=20
133
- )
134
- with gr.Tab("EYES"):
135
- with gr.Column():
136
- eyebrow = gr.Slider(
137
- label="Eyebrow", value=0,
138
- minimum=-10, maximum=15
139
- )
140
- with gr.Row():
141
- blink = gr.Slider(
142
- label="Blink", value=0,
143
- minimum=-20, maximum=5
144
- )
145
-
146
- wink = gr.Slider(
147
- label="Wink", value=0,
148
- minimum=0, maximum=25
149
- )
150
- with gr.Row():
151
- pupil_x = gr.Slider(
152
- label="Pupil X", value=0,
153
- minimum=-15, maximum=15
154
- )
155
- pupil_y = gr.Slider(
156
- label="Pupil Y", value=0,
157
- minimum=-15, maximum=15
158
- )
159
- with gr.Tab("MOUTH"):
160
- with gr.Column():
161
- with gr.Row():
162
- aaa = gr.Slider(
163
- label="Aaa", value=0,
164
- minimum=-30, maximum=120
165
- )
166
- eee = gr.Slider(
167
- label="Eee", value=0,
168
- minimum=-20, maximum=15
169
- )
170
- woo = gr.Slider(
171
- label="Woo", value=0,
172
- minimum=-20, maximum=15
173
- )
174
- smile = gr.Slider(
175
- label="Smile", value=0,
176
- minimum=-0.3, maximum=1.3
177
- )
178
- with gr.Tab("More Settings"):
179
- with gr.Column():
180
- src_ratio = gr.Number(
181
- label="Src Ratio", info='''Source ratio''', value=1
182
- )
183
- sample_ratio = gr.Slider(
184
- label="Sample Ratio", info='''Sample ratio''', value=1,
185
- minimum=-0.2, maximum=1.2
186
- )
187
- crop_factor = gr.Slider(
188
- label="Crop Factor", info='''Crop factor''', value=1.7,
189
- minimum=1.5, maximum=2.5
190
- )
191
- output_format = gr.Dropdown(
192
- choices=['webp', 'jpg', 'png'], label="output_format", info='''Format of the output images''', value="webp"
193
- )
194
- output_quality = gr.Number(
195
- label="Output Quality", info='''Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.''', value=95
196
- )
197
- with gr.Row():
198
- reset_btn = gr.Button("Reset")
199
- submit_btn = gr.Button("Submit")
200
- with gr.Column():
201
- result_image = gr.Image(elem_id="top")
202
- gr.HTML("""
203
- <div style="display: flex; flex-direction: column;justify-content: center; align-items: center; text-align: center;">
204
- <p style="display: flex;gap: 6px;">
205
- <a href="https://huggingface.co/spaces/fffiloni/expression-editor?duplicate=true">
206
- <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-lg.svg" alt="Duplicate this Space">
207
- </a>
208
- </p>
209
- <p>to skip the queue and enjoy faster inference on the GPU of your choice </p>
210
- </div>
211
- """)
212
-
213
- inputs = [image, rotate_pitch, rotate_yaw, rotate_roll, blink, eyebrow, wink, pupil_x, pupil_y, aaa, eee, woo, smile, src_ratio, sample_ratio, crop_factor, output_format, output_quality]
214
- outputs = [result_image]
215
-
216
- image.upload(
217
- fn = preprocess_image,
218
- inputs = [image],
219
- outputs = [image],
220
- queue = False
221
- )
222
-
223
- reset_btn.click(
224
- fn = reset_parameters,
225
- inputs = None,
226
- outputs = [rotate_pitch, rotate_yaw, rotate_roll, blink, eyebrow, wink, pupil_x, pupil_y, aaa, eee, woo, smile],
227
- queue = False
228
- ).then(
229
- fn=predict,
230
- inputs=inputs,
231
- outputs=outputs,
232
- show_api=False
233
- )
234
-
235
- submit_btn.click(
236
- fn=predict,
237
- inputs=inputs,
238
- outputs=outputs,
239
- show_api=False
240
- )
241
-
242
- rotate_pitch.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
243
- rotate_yaw.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
244
- rotate_roll.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
245
- blink.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
246
- eyebrow.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
247
- wink.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
248
- pupil_x.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
249
- pupil_y.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
250
- aaa.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
251
- eee.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
252
- woo.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
253
- smile.release(fn=predict, inputs=inputs, outputs=outputs, show_progress="minimal", show_api=False)
254
-
255
- demo.queue(api_open=False).launch(share=False, show_error=True, show_api=False)