dkescape commited on
Commit
46625ac
·
verified ·
1 Parent(s): d8668a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -46
app.py CHANGED
@@ -1,64 +1,218 @@
1
  import os
2
- import uuid
3
  import cv2
4
- import numpy as np
 
 
5
  import gradio as gr
 
 
 
6
  from modelscope.pipelines import pipeline
7
  from modelscope.utils.constant import Tasks
8
- from modelscope.outputs import OutputKeys
9
- from gradio_imageslider import ImageSlider
10
 
11
- # Initialize the image colorization pipeline with a specified model revision
12
  img_colorization = pipeline(
13
- task=Tasks.image_colorization,
14
- model='iic/cv_ddcolor_image-colorization',
15
- model_revision='v1.02' # Specify the model revision to avoid warnings
16
  )
17
 
18
- def colorize_image(input_image):
19
- """
20
- Colorizes a grayscale image using the DDColor model.
 
21
 
22
- Args:
23
- input_image (numpy.ndarray): Grayscale input image.
 
 
24
 
25
- Returns:
26
- tuple: Original and colorized images.
27
- """
28
- # Convert RGB to BGR for OpenCV compatibility
29
- bgr_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR)
 
 
30
 
31
- # Perform colorization
32
- output = img_colorization(bgr_image)
33
- colorized_bgr = output[OutputKeys.OUTPUT_IMG].astype(np.uint8)
 
 
 
 
34
 
35
- # Convert BGR back to RGB for display
36
- colorized_rgb = cv2.cvtColor(colorized_bgr, cv2.COLOR_BGR2RGB)
 
 
37
 
38
- return input_image, colorized_rgb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- # Define the Gradio interface
41
- title = "DDColor: Photo-Realistic Image Colorization"
42
- description = (
43
- "Upload a black & white image to colorize it using the DDColor model. "
44
- "This application utilizes a dual-decoder architecture to produce vivid and natural colorizations."
45
- )
46
 
47
- # Example images (ensure these paths are correct or adjust accordingly)
48
- examples = [['./input.jpg']]
49
-
50
- # Create the Gradio interface
51
- demo = gr.Interface(
52
- fn=colorize_image,
53
- inputs=gr.Image(label="Upload Grayscale Image"),
54
- outputs=ImageSlider(position=0.5, label='Colorization Comparison'),
55
- examples=examples,
56
- title=title,
57
- description=description,
58
- allow_flagging="never"
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
 
61
  if __name__ == "__main__":
62
- # Launch the Gradio app with production settings
63
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
64
-
 
1
  import os
 
2
  import cv2
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
  import gradio as gr
7
+ import numpy as np
8
+ from PIL import Image, ImageEnhance, ImageFilter
9
+ from modelscope.outputs import OutputKeys
10
  from modelscope.pipelines import pipeline
11
  from modelscope.utils.constant import Tasks
 
 
12
 
13
+ # Load the colorization model at startup
14
  img_colorization = pipeline(
15
+ Tasks.image_colorization,
16
+ model="iic/cv_ddcolor_image-colorization"
 
17
  )
18
 
19
+ def colorize_image(img_path: str) -> str:
20
+ image = cv2.imread(str(img_path))
21
+ output = img_colorization(image[..., ::-1])
22
+ result = output[OutputKeys.OUTPUT_IMG].astype(np.uint8)
23
 
24
+ temp_dir = tempfile.mkdtemp()
25
+ out_path = os.path.join(temp_dir, "colorized.png")
26
+ cv2.imwrite(out_path, result)
27
+ return out_path
28
 
29
+ def enhance_image(
30
+ img_path: str,
31
+ brightness: float = 1.0,
32
+ contrast: float = 1.0,
33
+ edge_enhance: bool = False
34
+ ) -> str:
35
+ image = Image.open(img_path)
36
 
37
+ # Brightness adjustment
38
+ image = ImageEnhance.Brightness(image).enhance(brightness)
39
+ # Contrast adjustment
40
+ image = ImageEnhance.Contrast(image).enhance(contrast)
41
+ # Optional edge enhancement
42
+ if edge_enhance:
43
+ image = image.filter(ImageFilter.EDGE_ENHANCE)
44
 
45
+ temp_dir = tempfile.mkdtemp()
46
+ enhanced_path = os.path.join(temp_dir, "enhanced.png")
47
+ image.save(enhanced_path)
48
+ return enhanced_path
49
 
50
+ def process_image(
51
+ img_path: str,
52
+ brightness: float,
53
+ contrast: float,
54
+ edge_enhance: bool,
55
+ output_format: str
56
+ ):
57
+ # Step 1: Colorize
58
+ colorized_path = colorize_image(img_path)
59
+ # Step 2: Enhance (brightness/contrast/edge)
60
+ enhanced_path = enhance_image(colorized_path, brightness, contrast, edge_enhance)
61
+ # Step 3: Convert to chosen format
62
+ img = Image.open(enhanced_path)
63
+ temp_dir = tempfile.mkdtemp()
64
+ filename = f"colorized_image.{output_format.lower()}"
65
+ output_path = os.path.join(temp_dir, filename)
66
+ img.save(output_path, format=output_format.upper())
67
 
68
+ # Return side-by-side (original, enhanced) and the downloadable file
69
+ return ([img_path, enhanced_path], output_path)
 
 
 
 
70
 
71
+ # CSS to give a modern, centered layout with a colored header and clean panels
72
+ custom_css = """
73
+ /* Overall background */
74
+ body {
75
+ background-color: #f0f2f5;
76
+ }
77
+
78
+ /* Center the Gradio container and give it a max width */
79
+ .gradio-container {
80
+ max-width: 900px !important;
81
+ margin: auto !important;
82
+ }
83
+
84
+ /* Header styling */
85
+ #header {
86
+ background-color: #4CAF50;
87
+ padding: 20px;
88
+ border-radius: 8px;
89
+ text-align: center;
90
+ margin-bottom: 20px;
91
+ }
92
+ #header h2 {
93
+ color: white;
94
+ margin: 0;
95
+ font-size: 2rem;
96
+ }
97
+ #header p {
98
+ color: white;
99
+ margin: 5px 0 0 0;
100
+ font-size: 1rem;
101
+ }
102
+
103
+ /* White panel for controls */
104
+ #control-panel {
105
+ background-color: white;
106
+ padding: 20px;
107
+ border-radius: 8px;
108
+ box-shadow: 0px 2px 8px rgba(0,0,0,0.1);
109
+ margin-bottom: 20px;
110
+ }
111
+
112
+ /* Style the “Colorize” button */
113
+ #submit-btn {
114
+ background-color: #4CAF50 !important;
115
+ color: white !important;
116
+ border-radius: 8px !important;
117
+ font-weight: bold;
118
+ padding: 10px 20px !important;
119
+ margin-top: 10px !important;
120
+ }
121
+
122
+ /* Add some spacing around sliders and checkbox */
123
+ #control-panel .gr-row {
124
+ gap: 15px;
125
+ }
126
+ .gr-slider, .gr-checkbox, .gr-dropdown {
127
+ margin-top: 10px;
128
+ }
129
+
130
+ /* Gallery panel styling */
131
+ #comparison_gallery {
132
+ background-color: white;
133
+ padding: 10px;
134
+ border-radius: 8px;
135
+ box-shadow: 0px 2px 8px rgba(0,0,0,0.1);
136
+ }
137
+
138
+ /* Download button spacing */
139
+ #download-btn {
140
+ margin-top: 15px !important;
141
+ }
142
+ """
143
+
144
+ TITLE = "🌈 Color Restorization Model"
145
+ DESCRIPTION = "Bring your old black & white photos back to life—upload, adjust, and download in vivid color."
146
+
147
+ with gr.Blocks(title=TITLE, css=custom_css) as app:
148
+ # Header section
149
+ gr.HTML(
150
+ """
151
+ <div id="header">
152
+ <h2>🌈 Color Restorization Model</h2>
153
+ <p>Bring your old black & white photos back to life—upload, adjust, and download in vivid color.</p>
154
+ </div>
155
+ """
156
+ )
157
+
158
+ # Main control panel: white box with rounded corners
159
+ with gr.Column(elem_id="control-panel"):
160
+ with gr.Row():
161
+ # Left column: inputs and controls
162
+ with gr.Column():
163
+ input_image = gr.Image(
164
+ type="filepath",
165
+ label="Upload B&W Image",
166
+ tool="editor", # Enables zoom/pan
167
+ interactive=True
168
+ )
169
+ brightness_slider = gr.Slider(
170
+ minimum=0.5, maximum=2.0, value=1.0,
171
+ label="Brightness"
172
+ )
173
+ contrast_slider = gr.Slider(
174
+ minimum=0.5, maximum=2.0, value=1.0,
175
+ label="Contrast"
176
+ )
177
+ edge_enhance_checkbox = gr.Checkbox(
178
+ label="Apply Edge Enhancement"
179
+ )
180
+ output_format_dropdown = gr.Dropdown(
181
+ choices=["PNG", "JPEG", "TIFF"],
182
+ value="PNG",
183
+ label="Output Format"
184
+ )
185
+ submit_btn = gr.Button(
186
+ "Colorize",
187
+ elem_id="submit-btn"
188
+ )
189
+
190
+ # Right column: results gallery & download
191
+ with gr.Column():
192
+ comparison_gallery = gr.Gallery(
193
+ label="Original vs. Colorized",
194
+ columns=2,
195
+ elem_id="comparison_gallery",
196
+ height="auto"
197
+ )
198
+ download_btn = gr.File(
199
+ label="Download Colorized Image",
200
+ elem_id="download-btn"
201
+ )
202
+
203
+ submit_btn.click(
204
+ fn=process_image,
205
+ inputs=[
206
+ input_image,
207
+ brightness_slider,
208
+ contrast_slider,
209
+ edge_enhance_checkbox,
210
+ output_format_dropdown
211
+ ],
212
+ outputs=[comparison_gallery, download_btn]
213
+ )
214
 
215
+ # “Production” launch: bind to 0.0.0.0 and use PORT env var if provided
216
  if __name__ == "__main__":
217
+ port = int(os.environ.get("PORT", 7860))
218
+ app.queue().launch(server_name="0.0.0.0", server_port=port)