abiabidali commited on
Commit
b448efc
·
verified ·
1 Parent(s): 626ca41

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from RealESRGAN import RealESRGAN
4
+ import gradio as gr
5
+ import numpy as np
6
+ import tempfile
7
+ import time
8
+ import zipfile
9
+ import os
10
+
11
+ # Set the device to CUDA if available, otherwise CPU
12
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
13
+
14
+ def load_model(scale):
15
+ model = RealESRGAN(device, scale=scale)
16
+ weights_path = f'weights/RealESRGAN_x{scale}.pth'
17
+ try:
18
+ model.load_weights(weights_path, download=True)
19
+ print(f"Weights for scale {scale} loaded successfully.")
20
+ except Exception as e:
21
+ print(f"Error loading weights for scale {scale}: {e}")
22
+ model.load_weights(weights_path, download=False)
23
+ return model
24
+
25
+ # Load models for different scales
26
+ model2 = load_model(2)
27
+ model4 = load_model(4)
28
+ model8 = load_model(8)
29
+
30
+ def enhance_image(image, scale):
31
+ try:
32
+ print(f"Enhancing image with scale {scale}...")
33
+ start_time = time.time()
34
+ image_np = np.array(image.convert('RGB'))
35
+ print(f"Image converted to numpy array: shape {image_np.shape}, dtype {image_np.dtype}")
36
+
37
+ if scale == '2x':
38
+ result = model2.predict(image_np)
39
+ elif scale == '4x':
40
+ result = model4.predict(image_np)
41
+ else:
42
+ result = model8.predict(image_np)
43
+
44
+ enhanced_image = Image.fromarray(np.uint8(result))
45
+ print(f"Image enhanced in {time.time() - start_time:.2f} seconds")
46
+ return enhanced_image
47
+ except Exception as e:
48
+ print(f"Error enhancing image: {e}")
49
+ return image
50
+
51
+ def muda_dpi(input_image, dpi):
52
+ dpi_tuple = (dpi, dpi)
53
+ image = Image.fromarray(input_image.astype('uint8'), 'RGB')
54
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
55
+ image.save(temp_file, format='JPEG', dpi=dpi_tuple)
56
+ temp_file.close()
57
+ return Image.open(temp_file.name)
58
+
59
+ def resize_image(input_image, width, height):
60
+ image = Image.fromarray(input_image.astype('uint8'), 'RGB')
61
+ resized_image = image.resize((width, height))
62
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
63
+ resized_image.save(temp_file, format='JPEG')
64
+ temp_file.close()
65
+ return Image.open(temp_file.name)
66
+
67
+ def process_images(image_files, enhance, scale, adjust_dpi, dpi, resize, width, height):
68
+ processed_images = []
69
+ temp_dir = tempfile.mkdtemp()
70
+
71
+ for image_file in image_files:
72
+ input_image = np.array(Image.open(image_file).convert('RGB'))
73
+ original_image = Image.fromarray(input_image.astype('uint8'), 'RGB')
74
+
75
+ if enhance:
76
+ original_image = enhance_image(original_image, scale)
77
+
78
+ if adjust_dpi:
79
+ original_image = muda_dpi(np.array(original_image), dpi)
80
+
81
+ if resize:
82
+ original_image = resize_image(np.array(original_image), width, height)
83
+
84
+ # Save each image as JPEG, preserving the original filename
85
+ file_name = os.path.basename(image_file.name)
86
+ output_path = os.path.join(temp_dir, file_name)
87
+ original_image.save(output_path, format='JPEG')
88
+ processed_images.append(output_path)
89
+
90
+ # Create a ZIP file with all processed images
91
+ zip_path = os.path.join(temp_dir, 'processed_images.zip')
92
+ with zipfile.ZipFile(zip_path, 'w') as zipf:
93
+ for file_path in processed_images:
94
+ zipf.write(file_path, os.path.basename(file_path))
95
+
96
+ # Load images for display in the gallery
97
+ display_images = [Image.open(img_path) for img_path in processed_images]
98
+
99
+ return display_images, zip_path
100
+
101
+ iface = gr.Interface(
102
+ fn=process_images,
103
+ inputs=[
104
+ gr.Files(label="Upload Image Files"), # Use gr.Files for multiple file uploads
105
+ gr.Checkbox(label="Enhance Images (ESRGAN)"),
106
+ gr.Radio(['2x', '4x', '8x'], type="value", value='2x', label='Resolution model'),
107
+ gr.Checkbox(label="Adjust DPI"),
108
+ gr.Number(label="DPI", value=300),
109
+ gr.Checkbox(label="Resize"),
110
+ gr.Number(label="Width", value=512),
111
+ gr.Number(label="Height", value=512)
112
+ ],
113
+ outputs=[
114
+ gr.Gallery(label="Final Images"), # Display the processed images
115
+ gr.File(label="Download Final Images (ZIP)") # Provide a ZIP file for download
116
+ ],
117
+ title="bulk image upscaler",
118
+ description="Upload multiple images (.jpg, .png), enhance using AI, adjust DPI, resize, and download the final results as a ZIP file."
119
+ )
120
+
121
+ iface.launch(debug=True)