shiue2000 commited on
Commit
3979116
·
verified ·
1 Parent(s): 6f3afe9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -59
app.py CHANGED
@@ -13,7 +13,6 @@ UPLOAD_FOLDER = os.path.join(STATIC_FOLDER, 'uploads')
13
  OUTPUT_FOLDER = os.path.join(STATIC_FOLDER, 'outputs')
14
  MODEL_FOLDER = os.path.join(BASE_DIR, 'model')
15
 
16
- os.makedirs(STATIC_FOLDER, exist_ok=True)
17
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
18
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
19
 
@@ -22,12 +21,15 @@ protoPath = os.path.join(MODEL_FOLDER, 'colorization_deploy_v2.prototxt')
22
  modelPath = os.path.join(MODEL_FOLDER, 'colorization_release_v2.caffemodel')
23
  hullPath = os.path.join(MODEL_FOLDER, 'pts_in_hull.npy')
24
 
25
- assert os.path.exists(protoPath), f"Missing proto file: {protoPath}"
26
- assert os.path.exists(modelPath), f"Missing model file: {modelPath}"
27
- assert os.path.exists(hullPath), f"Missing hull file: {hullPath}"
28
-
29
  COLORIZATION_MODEL_AVAILABLE = False
 
 
 
30
  try:
 
 
 
 
31
  print("Loading colorization model...")
32
  net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
33
  pts_in_hull = np.load(hullPath)
@@ -36,10 +38,8 @@ try:
36
  raise ValueError(f"pts_in_hull shape invalid: {pts_in_hull.shape}")
37
 
38
  pts = pts_in_hull.transpose().reshape(2, 313, 1, 1).astype(np.float32)
39
-
40
  net.getLayer(net.getLayerId('class8_ab')).blobs = [pts]
41
  net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, dtype=np.float32)]
42
-
43
  COLORIZATION_MODEL_AVAILABLE = True
44
  print("Colorization model loaded successfully.")
45
  except Exception as e:
@@ -59,33 +59,28 @@ def adjust_brightness_contrast(img, brightness=0, contrast=20):
59
  return cv2.convertScaleAbs(img, alpha=alpha, beta=brightness)
60
 
61
  def colorize_image_local(input_path, output_path):
62
- print(f"Reading image for colorization: {input_path}")
63
- img = cv2.imread(input_path)
64
- if img is None:
65
- print("ERROR: Could not read input image (file may be corrupt or unreadable by OpenCV).")
66
- return False
67
- else:
68
- print(f"Image loaded successfully, shape: {img.shape}")
69
-
70
  if not COLORIZATION_MODEL_AVAILABLE:
71
  print("Colorization model not available.")
72
  return False
73
 
 
 
 
 
 
74
  img = resize_img(img)
75
  h, w = img.shape[:2]
76
 
77
  img_rgb = img.astype("float32") / 255.0
78
  lab = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2LAB)
79
  L = lab[:, :, 0]
80
-
81
- L_resized = cv2.resize(L, (224, 224))
82
- L_resized -= 50 # mean-centering
83
 
84
  try:
85
  net.setInput(cv2.dnn.blobFromImage(L_resized))
86
  ab = net.forward()[0].transpose(1, 2, 0)
87
  except Exception as e:
88
- print(f"ERROR during DNN forward pass: {e}")
89
  return False
90
 
91
  ab = cv2.resize(ab, (w, h))
@@ -94,56 +89,30 @@ def colorize_image_local(input_path, output_path):
94
  out_bgr = np.clip(out_bgr * 255, 0, 255).astype("uint8")
95
  out_bgr = adjust_brightness_contrast(out_bgr, brightness=-10, contrast=15)
96
  cv2.imwrite(output_path, out_bgr)
97
- print(f"Colorized image saved to {output_path}")
98
  return True
99
 
100
  @app.route('/', methods=['GET', 'POST'])
101
  def index():
102
-
103
- print(f"protoPath: {protoPath}, exists? {os.path.exists(protoPath)}")
104
- print(f"modelPath: {modelPath}, exists? {os.path.exists(modelPath)}")
105
- print(f"hullPath: {hullPath}, exists? {os.path.exists(hullPath)}")
106
- print(f"UPLOAD_FOLDER: {UPLOAD_FOLDER}, exists? {os.path.exists(UPLOAD_FOLDER)}")
107
- print(f"OUTPUT_FOLDER: {OUTPUT_FOLDER}, exists? {os.path.exists(OUTPUT_FOLDER)}")
108
- print(f"COLORIZATION_MODEL_AVAILABLE: {COLORIZATION_MODEL_AVAILABLE}")
109
- print(f"cv2 version: {cv2.__version__}")
110
-
111
  original_url = enhanced_url = None
112
  if request.method == 'POST':
113
  file = request.files.get('image')
114
- if file and file.filename:
115
- filename = secure_filename(file.filename)
116
- orig_path = os.path.join(UPLOAD_FOLDER, filename)
117
- print(f"Saving file to {orig_path}")
118
- try:
119
- file.save(orig_path)
120
- print(f"File saved successfully.")
121
- except Exception as e:
122
- print(f"ERROR: Failed to save file: {e}")
123
- return "File save failed", 400
124
-
125
- if os.path.exists(orig_path):
126
- print(f"Saved file size: {os.path.getsize(orig_path)} bytes")
127
- else:
128
- print("ERROR: File does not exist after saving!")
129
- return "File save failed", 400
130
-
131
- output_name = f"output_{filename}"
132
- output_path = os.path.join(OUTPUT_FOLDER, output_name)
133
-
134
-
135
- if not colorize_image_local(orig_path, output_path):
136
- print("Colorization failed inside colorize_image_local")
137
- return "Colorization failed", 400
138
-
139
- original_url = url_for('static', filename=f'uploads/{filename}')
140
- enhanced_url = url_for('static', filename=f'outputs/{output_name}')
141
- else:
142
- print("No file uploaded or empty filename.")
143
  return "No file uploaded", 400
144
 
145
- return render_template('index.html', original_url=original_url, enhanced_url=enhanced_url)
 
 
 
 
 
 
 
 
146
 
 
 
 
 
147
 
148
  if __name__ == '__main__':
149
  port = int(os.environ.get("PORT", 7860))
 
13
  OUTPUT_FOLDER = os.path.join(STATIC_FOLDER, 'outputs')
14
  MODEL_FOLDER = os.path.join(BASE_DIR, 'model')
15
 
 
16
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
17
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
18
 
 
21
  modelPath = os.path.join(MODEL_FOLDER, 'colorization_release_v2.caffemodel')
22
  hullPath = os.path.join(MODEL_FOLDER, 'pts_in_hull.npy')
23
 
 
 
 
 
24
  COLORIZATION_MODEL_AVAILABLE = False
25
+ net = None
26
+
27
+ # --- Load model ---
28
  try:
29
+ assert os.path.exists(protoPath), f"Missing proto file: {protoPath}"
30
+ assert os.path.exists(modelPath), f"Missing model file: {modelPath}"
31
+ assert os.path.exists(hullPath), f"Missing hull file: {hullPath}"
32
+
33
  print("Loading colorization model...")
34
  net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
35
  pts_in_hull = np.load(hullPath)
 
38
  raise ValueError(f"pts_in_hull shape invalid: {pts_in_hull.shape}")
39
 
40
  pts = pts_in_hull.transpose().reshape(2, 313, 1, 1).astype(np.float32)
 
41
  net.getLayer(net.getLayerId('class8_ab')).blobs = [pts]
42
  net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, dtype=np.float32)]
 
43
  COLORIZATION_MODEL_AVAILABLE = True
44
  print("Colorization model loaded successfully.")
45
  except Exception as e:
 
59
  return cv2.convertScaleAbs(img, alpha=alpha, beta=brightness)
60
 
61
  def colorize_image_local(input_path, output_path):
 
 
 
 
 
 
 
 
62
  if not COLORIZATION_MODEL_AVAILABLE:
63
  print("Colorization model not available.")
64
  return False
65
 
66
+ img = cv2.imread(input_path)
67
+ if img is None:
68
+ print(f"Failed to read image: {input_path}")
69
+ return False
70
+
71
  img = resize_img(img)
72
  h, w = img.shape[:2]
73
 
74
  img_rgb = img.astype("float32") / 255.0
75
  lab = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2LAB)
76
  L = lab[:, :, 0]
77
+ L_resized = cv2.resize(L, (224, 224)) - 50 # mean-centering
 
 
78
 
79
  try:
80
  net.setInput(cv2.dnn.blobFromImage(L_resized))
81
  ab = net.forward()[0].transpose(1, 2, 0)
82
  except Exception as e:
83
+ print(f"DNN forward pass failed: {e}")
84
  return False
85
 
86
  ab = cv2.resize(ab, (w, h))
 
89
  out_bgr = np.clip(out_bgr * 255, 0, 255).astype("uint8")
90
  out_bgr = adjust_brightness_contrast(out_bgr, brightness=-10, contrast=15)
91
  cv2.imwrite(output_path, out_bgr)
 
92
  return True
93
 
94
  @app.route('/', methods=['GET', 'POST'])
95
  def index():
 
 
 
 
 
 
 
 
 
96
  original_url = enhanced_url = None
97
  if request.method == 'POST':
98
  file = request.files.get('image')
99
+ if not file or not file.filename:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  return "No file uploaded", 400
101
 
102
+ filename = secure_filename(file.filename)
103
+ orig_path = os.path.join(UPLOAD_FOLDER, filename)
104
+ file.save(orig_path)
105
+
106
+ output_name = f"output_{filename}"
107
+ output_path = os.path.join(OUTPUT_FOLDER, output_name)
108
+
109
+ if not colorize_image_local(orig_path, output_path):
110
+ return "Colorization failed", 400
111
 
112
+ original_url = url_for('static', filename=f'uploads/{filename}')
113
+ enhanced_url = url_for('static', filename=f'outputs/{output_name}')
114
+
115
+ return render_template('index.html', original_url=original_url, enhanced_url=enhanced_url)
116
 
117
  if __name__ == '__main__':
118
  port = int(os.environ.get("PORT", 7860))