fffiloni commited on
Commit
71ba5f1
1 Parent(s): 2fb017a

preprocess image input

Browse files
Files changed (1) hide show
  1. app.py +44 -2
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import gradio as gr
 
2
  from urllib.parse import urlparse
3
  import requests
4
  import time
@@ -6,6 +7,47 @@ import os
6
 
7
  from utils.gradio_helpers import parse_outputs, process_outputs
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  def display_uploaded_image(image_in):
10
  return image_in
11
 
@@ -170,9 +212,9 @@ with gr.Blocks(css=css) as demo:
170
  outputs = [result_image]
171
 
172
  image.upload(
173
- fn = display_uploaded_image,
174
  inputs = [image],
175
- outputs = [result_image],
176
  queue = False
177
  )
178
 
 
1
  import gradio as gr
2
+ from PIL import Image
3
  from urllib.parse import urlparse
4
  import requests
5
  import time
 
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.ANTIALIAS)
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
 
 
212
  outputs = [result_image]
213
 
214
  image.upload(
215
+ fn = preprocess_image,
216
  inputs = [image],
217
+ outputs = [image],
218
  queue = False
219
  )
220