AveMujica Martyr1 commited on
Commit
b2048d6
·
verified ·
1 Parent(s): 0b7ba62

Update app.py (#1)

Browse files

- Update app.py (1b807a05f70700e1b5f655a7671e85c2dd947230)


Co-authored-by: Zheheng Li <Martyr1@users.noreply.huggingface.co>

Files changed (1) hide show
  1. app.py +83 -87
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import os
2
  import cv2
3
  import numpy as np
4
  import torch
@@ -9,36 +8,37 @@ import boto3
9
  import uuid
10
  import io
11
  from glob import glob
 
12
  from pipeline.ImgOutlier import detect_outliers
13
  from pipeline.normalization import align_images
14
 
15
- # 检测是否在Hugging Face环境中运行
16
  HF_SPACE = os.environ.get('SPACE_ID') is not None
17
 
18
- # DigitalOcean Spaces上传函数
19
  def upload_mask(image, prefix="mask"):
20
  """
21
- 将分割掩码图像上传到DigitalOcean Spaces
22
-
23
  Args:
24
- image: PIL Image对象
25
- prefix: 文件名前缀
26
 
27
  Returns:
28
- 上传文件的URL
29
  """
30
  try:
31
- # 从环境变量获取凭据
32
  do_key = os.environ.get('DO_SPACES_KEY')
33
  do_secret = os.environ.get('DO_SPACES_SECRET')
34
  do_region = os.environ.get('DO_SPACES_REGION')
35
  do_bucket = os.environ.get('DO_SPACES_BUCKET')
36
 
37
- # 校验凭据是否存在
38
  if not all([do_key, do_secret, do_region, do_bucket]):
39
- return "DigitalOcean凭据未设置"
40
 
41
- # 创建S3客户端
42
  session = boto3.session.Session()
43
  client = session.client('s3',
44
  region_name=do_region,
@@ -46,15 +46,15 @@ def upload_mask(image, prefix="mask"):
46
  aws_access_key_id=do_key,
47
  aws_secret_access_key=do_secret)
48
 
49
- # 生成唯一文件名
50
  filename = f"{prefix}_{uuid.uuid4().hex}.png"
51
 
52
- # 将图像转换为字节流
53
  img_byte_arr = io.BytesIO()
54
  image.save(img_byte_arr, format='PNG')
55
  img_byte_arr.seek(0)
56
 
57
- # 上传到Spaces
58
  client.upload_fileobj(
59
  img_byte_arr,
60
  do_bucket,
@@ -62,13 +62,13 @@ def upload_mask(image, prefix="mask"):
62
  ExtraArgs={'ACL': 'public-read', 'ContentType': 'image/png'}
63
  )
64
 
65
- # 返回公共URL
66
  url = f'https://{do_bucket}.{do_region}.digitaloceanspaces.com/{filename}'
67
  return url
68
 
69
  except Exception as e:
70
- print(f"上传失败: {str(e)}")
71
- return f"上传错误: {str(e)}"
72
 
73
  # Global Configuration
74
  MODEL_PATHS = {
@@ -101,11 +101,11 @@ COLORS = [
101
  # Load model function
102
  def load_model(model_path, device="cuda"):
103
  try:
104
- # 如果在HF环境中,默认使用CPU
105
  if HF_SPACE:
106
- device = "cpu" # HF Space可能没有GPU
107
  elif not torch.cuda.is_available():
108
- device = "cpu" # 本地环境也可能没有GPU
109
 
110
  model = smp.create_model(
111
  "DeepLabV3Plus",
@@ -120,30 +120,30 @@ def load_model(model_path, device="cuda"):
120
  model.load_state_dict(state_dict)
121
  model.to(device)
122
  model.eval()
123
- print(f"模型加载成功: {model_path}")
124
  return model
125
  except Exception as e:
126
- print(f"模型加载失败: {e}")
127
  return None
128
 
129
  # Load reference vector
130
  def load_reference_vector(vector_path):
131
  try:
132
  if not os.path.exists(vector_path):
133
- print(f"参考向量文件不存在: {vector_path}")
134
  return []
135
  ref_vector = np.load(vector_path)
136
- print(f"参考向量加载成功: {vector_path}")
137
  return ref_vector
138
  except Exception as e:
139
- print(f"参考向量加载失败 {vector_path}: {e}")
140
  return []
141
 
142
- # Load reference image
143
  def load_reference_images(ref_dir):
144
  try:
145
  if not os.path.exists(ref_dir):
146
- print(f"参考图像目录不存在: {ref_dir}")
147
  os.makedirs(ref_dir, exist_ok=True)
148
  return []
149
 
@@ -157,10 +157,10 @@ def load_reference_images(ref_dir):
157
  img = cv2.imread(file)
158
  if img is not None:
159
  reference_images.append(img)
160
- print(f" {ref_dir} 加载了 {len(reference_images)} 张图像")
161
  return reference_images
162
  except Exception as e:
163
- print(f"加载图像失败 {ref_dir}: {e}")
164
  return []
165
 
166
  # Preprocess the image
@@ -208,7 +208,6 @@ def create_overlay(image, segmentation_map, alpha=0.5):
208
  if image.shape[:2] != segmentation_map.shape[:2]:
209
  segmentation_map = cv2.resize(segmentation_map, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
210
  return cv2.addWeighted(image, 1-alpha, segmentation_map, alpha, 0)
211
-
212
  # Perform segmentation
213
  def perform_segmentation(model, image_bgr):
214
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
@@ -225,18 +224,18 @@ def perform_segmentation(model, image_bgr):
225
  # Single image processing
226
  def process_coastal_image(location, input_image):
227
  if input_image is None:
228
- return None, None, "请上传一张图片", "未检测", None
229
 
230
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
231
  model = load_model(MODEL_PATHS[location], device)
232
 
233
  if model is None:
234
- return None, None, f"错误:无法加载模型", "未检测", None
235
 
236
  ref_vector = load_reference_vector(REFERENCE_VECTOR_PATHS[location])
237
  ref_images = load_reference_images(REFERENCE_IMAGE_DIRS[location])
238
 
239
- outlier_status = "未检测"
240
  is_outlier = False
241
  image_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
242
 
@@ -247,35 +246,35 @@ def process_coastal_image(location, input_image):
247
  filtered, _ = detect_outliers(ref_images, [image_bgr])
248
  is_outlier = len(filtered) == 0
249
  else:
250
- print("警告:没有参考图像或参考向量可用于异常检测")
251
  is_outlier = False
252
 
253
- outlier_status = "异常检测: <span style='color:red;font-weight:bold'>未通过</span>" if is_outlier else "异常检测: <span style='color:green;font-weight:bold'>通过</span>"
254
  seg_map, overlay, analysis = perform_segmentation(model, image_bgr)
255
 
256
- # 尝试上传到DigitalOcean Spaces
257
- url = "本地存储"
258
  try:
259
  url = upload_mask(Image.fromarray(seg_map), prefix=location.replace(' ', '_'))
260
  except Exception as e:
261
- print(f"上传失败: {e}")
262
- url = f"上传错误: {str(e)}"
263
 
264
  if is_outlier:
265
- analysis = "<div style='color:red;font-weight:bold;margin-bottom:10px'>警告:图像未通过异常检测,结果可能不准确!</div>" + analysis
266
 
267
  return seg_map, overlay, analysis, outlier_status, url
268
 
269
- # Spacial Alignment
270
  def process_with_alignment(location, reference_image, input_image):
271
  if reference_image is None or input_image is None:
272
- return None, None, None, None, "请上传参考图像和需要分析的图像", "未处理", None
273
 
274
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
275
  model = load_model(MODEL_PATHS[location], device)
276
 
277
  if model is None:
278
- return None, None, None, None, "错误:无法加载模型", "未处理", None
279
 
280
  ref_bgr = cv2.cvtColor(np.array(reference_image), cv2.COLOR_RGB2BGR)
281
  tgt_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
@@ -284,20 +283,20 @@ def process_with_alignment(location, reference_image, input_image):
284
  aligned, _ = align_images([ref_bgr, tgt_bgr], [np.zeros_like(ref_bgr), np.zeros_like(tgt_bgr)])
285
  aligned_tgt_bgr = aligned[1]
286
  except Exception as e:
287
- print(f"空间对齐失败: {e}")
288
- return None, None, None, None, f"空间对齐失败: {str(e)}", "处理失败", None
289
 
290
  seg_map, overlay, analysis = perform_segmentation(model, aligned_tgt_bgr)
291
 
292
- # 尝试上传到DigitalOcean Spaces
293
- url = "本地存储"
294
  try:
295
  url = upload_mask(Image.fromarray(seg_map), prefix="aligned_" + location.replace(' ', '_'))
296
  except Exception as e:
297
- print(f"上传失败: {e}")
298
- url = f"上传错误: {str(e)}"
299
 
300
- status = "空间对齐: <span style='color:green;font-weight:bold'>完成</span>"
301
  ref_rgb = cv2.cvtColor(ref_bgr, cv2.COLOR_BGR2RGB)
302
  aligned_tgt_rgb = cv2.cvtColor(aligned_tgt_bgr, cv2.COLOR_BGR2RGB)
303
 
@@ -305,61 +304,59 @@ def process_with_alignment(location, reference_image, input_image):
305
 
306
  # Create the Gradio interface
307
  def create_interface():
308
- # 设置统一的显示尺寸
309
- disp_w, disp_h = 683, 512 # 统一设置宽高比
310
-
311
- with gr.Blocks(title="海岸侵蚀分析系统") as demo:
312
- gr.Markdown("""# 海岸侵蚀分析系统
313
 
314
- 上传海岸照片进行分析,包括分割和空间对齐功能。""")
315
  with gr.Tabs():
316
- with gr.TabItem("单张图像分割"):
317
  with gr.Row():
318
- loc1 = gr.Radio(list(MODEL_PATHS.keys()), label="选择模型", value=list(MODEL_PATHS.keys())[0])
319
  with gr.Row():
320
- # 确保所有图像组件使用相同的尺寸
321
- inp = gr.Image(label="输入图像", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
322
- seg = gr.Image(label="分割图像", type="numpy", height=disp_h, width=disp_w)
323
- ovl = gr.Image(label="叠加图像", type="numpy", height=disp_h, width=disp_w)
324
  with gr.Row():
325
- btn1 = gr.Button("执行分割")
326
- url1 = gr.Text(label="分割图URL")
327
- status1 = gr.HTML(label="异常检测状态")
328
- res1 = gr.HTML(label="分析结果")
329
  btn1.click(fn=process_coastal_image, inputs=[loc1, inp], outputs=[seg, ovl, res1, status1, url1])
330
 
331
- with gr.TabItem("空间对齐分割"):
332
  with gr.Row():
333
- loc2 = gr.Radio(list(MODEL_PATHS.keys()), label="选择模型", value=list(MODEL_PATHS.keys())[0])
334
  with gr.Row():
335
- # 确保所有图像组件使用相同的尺寸
336
- ref_img = gr.Image(label="参考图像", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
337
- tgt_img = gr.Image(label="待分析图像", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
338
  with gr.Row():
339
- btn2 = gr.Button("执行空间对齐分割")
340
  with gr.Row():
341
- orig = gr.Image(label="原始图像", type="numpy", height=disp_h, width=disp_w)
342
- aligned = gr.Image(label="对齐后图像", type="numpy", height=disp_h, width=disp_w)
343
  with gr.Row():
344
- seg2 = gr.Image(label="分割图像", type="numpy", height=disp_h, width=disp_w)
345
- ovl2 = gr.Image(label="叠加图像", type="numpy", height=disp_h, width=disp_w)
346
- url2 = gr.Text(label="分割图URL")
347
- status2 = gr.HTML(label="空间对齐状���")
348
- res2 = gr.HTML(label="分析结果")
349
  btn2.click(fn=process_with_alignment, inputs=[loc2, ref_img, tgt_img], outputs=[orig, aligned, seg2, ovl2, res2, status2, url2])
350
  return demo
351
 
352
  if __name__ == "__main__":
353
- # 创建必要的目录
354
  for path in ["models", "reference_images/MM", "reference_images/SJ"]:
355
  os.makedirs(path, exist_ok=True)
356
 
357
- # 检查模型文件是否存在
358
  for p in MODEL_PATHS.values():
359
  if not os.path.exists(p):
360
- print(f"警告:模型文件 {p} 不存在!")
361
 
362
- # 检查DigitalOcean凭据是否存在
363
  do_creds = [
364
  os.environ.get('DO_SPACES_KEY'),
365
  os.environ.get('DO_SPACES_SECRET'),
@@ -367,11 +364,10 @@ if __name__ == "__main__":
367
  os.environ.get('DO_SPACES_BUCKET')
368
  ]
369
  if not all(do_creds):
370
- print("警告:DigitalOcean Spaces凭据不完整,上传功能可能不可用")
371
 
372
- # 创建并启动界面
373
  demo = create_interface()
374
- # 在HF环境中使用适当的启动配置
375
  if HF_SPACE:
376
  demo.launch()
377
  else:
 
 
1
  import cv2
2
  import numpy as np
3
  import torch
 
8
  import uuid
9
  import io
10
  from glob import glob
11
+ import os
12
  from pipeline.ImgOutlier import detect_outliers
13
  from pipeline.normalization import align_images
14
 
15
+ # Detect if running inside Hugging Face Spaces
16
  HF_SPACE = os.environ.get('SPACE_ID') is not None
17
 
18
+ # DigitalOcean Spaces upload function
19
  def upload_mask(image, prefix="mask"):
20
  """
21
+ Upload segmentation mask image to DigitalOcean Spaces
22
+
23
  Args:
24
+ image: PIL Image object
25
+ prefix: filename prefix
26
 
27
  Returns:
28
+ Public URL of the uploaded file
29
  """
30
  try:
31
+ # Get credentials from environment variables
32
  do_key = os.environ.get('DO_SPACES_KEY')
33
  do_secret = os.environ.get('DO_SPACES_SECRET')
34
  do_region = os.environ.get('DO_SPACES_REGION')
35
  do_bucket = os.environ.get('DO_SPACES_BUCKET')
36
 
37
+ # Check if credentials exist
38
  if not all([do_key, do_secret, do_region, do_bucket]):
39
+ return "DigitalOcean credentials not set"
40
 
41
+ # Create S3 client
42
  session = boto3.session.Session()
43
  client = session.client('s3',
44
  region_name=do_region,
 
46
  aws_access_key_id=do_key,
47
  aws_secret_access_key=do_secret)
48
 
49
+ # Generate unique filename
50
  filename = f"{prefix}_{uuid.uuid4().hex}.png"
51
 
52
+ # Convert image to bytes
53
  img_byte_arr = io.BytesIO()
54
  image.save(img_byte_arr, format='PNG')
55
  img_byte_arr.seek(0)
56
 
57
+ # Upload to Spaces
58
  client.upload_fileobj(
59
  img_byte_arr,
60
  do_bucket,
 
62
  ExtraArgs={'ACL': 'public-read', 'ContentType': 'image/png'}
63
  )
64
 
65
+ # Return public URL
66
  url = f'https://{do_bucket}.{do_region}.digitaloceanspaces.com/{filename}'
67
  return url
68
 
69
  except Exception as e:
70
+ print(f"Upload failed: {str(e)}")
71
+ return f"Upload error: {str(e)}"
72
 
73
  # Global Configuration
74
  MODEL_PATHS = {
 
101
  # Load model function
102
  def load_model(model_path, device="cuda"):
103
  try:
104
+ # If running inside HF Spaces, default to CPU
105
  if HF_SPACE:
106
+ device = "cpu"
107
  elif not torch.cuda.is_available():
108
+ device = "cpu"
109
 
110
  model = smp.create_model(
111
  "DeepLabV3Plus",
 
120
  model.load_state_dict(state_dict)
121
  model.to(device)
122
  model.eval()
123
+ print(f"Model loaded successfully: {model_path}")
124
  return model
125
  except Exception as e:
126
+ print(f"Model loading failed: {e}")
127
  return None
128
 
129
  # Load reference vector
130
  def load_reference_vector(vector_path):
131
  try:
132
  if not os.path.exists(vector_path):
133
+ print(f"Reference vector file not found: {vector_path}")
134
  return []
135
  ref_vector = np.load(vector_path)
136
+ print(f"Reference vector loaded successfully: {vector_path}")
137
  return ref_vector
138
  except Exception as e:
139
+ print(f"Reference vector loading failed {vector_path}: {e}")
140
  return []
141
 
142
+ # Load reference images
143
  def load_reference_images(ref_dir):
144
  try:
145
  if not os.path.exists(ref_dir):
146
+ print(f"Reference image directory not found: {ref_dir}")
147
  os.makedirs(ref_dir, exist_ok=True)
148
  return []
149
 
 
157
  img = cv2.imread(file)
158
  if img is not None:
159
  reference_images.append(img)
160
+ print(f"Loaded {len(reference_images)} images from {ref_dir}")
161
  return reference_images
162
  except Exception as e:
163
+ print(f"Image loading failed {ref_dir}: {e}")
164
  return []
165
 
166
  # Preprocess the image
 
208
  if image.shape[:2] != segmentation_map.shape[:2]:
209
  segmentation_map = cv2.resize(segmentation_map, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
210
  return cv2.addWeighted(image, 1-alpha, segmentation_map, alpha, 0)
 
211
  # Perform segmentation
212
  def perform_segmentation(model, image_bgr):
213
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
 
224
  # Single image processing
225
  def process_coastal_image(location, input_image):
226
  if input_image is None:
227
+ return None, None, "Please upload an image", "Not detected", None
228
 
229
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
230
  model = load_model(MODEL_PATHS[location], device)
231
 
232
  if model is None:
233
+ return None, None, f"Error: Failed to load model", "Not detected", None
234
 
235
  ref_vector = load_reference_vector(REFERENCE_VECTOR_PATHS[location])
236
  ref_images = load_reference_images(REFERENCE_IMAGE_DIRS[location])
237
 
238
+ outlier_status = "Not detected"
239
  is_outlier = False
240
  image_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
241
 
 
246
  filtered, _ = detect_outliers(ref_images, [image_bgr])
247
  is_outlier = len(filtered) == 0
248
  else:
249
+ print("Warning: No reference images or reference vectors available for outlier detection")
250
  is_outlier = False
251
 
252
+ outlier_status = "Outlier Detection: <span style='color:red;font-weight:bold'>Failed</span>" if is_outlier else "Outlier Detection: <span style='color:green;font-weight:bold'>Passed</span>"
253
  seg_map, overlay, analysis = perform_segmentation(model, image_bgr)
254
 
255
+ # Try uploading to DigitalOcean Spaces
256
+ url = "Local Storage"
257
  try:
258
  url = upload_mask(Image.fromarray(seg_map), prefix=location.replace(' ', '_'))
259
  except Exception as e:
260
+ print(f"Upload failed: {e}")
261
+ url = f"Upload error: {str(e)}"
262
 
263
  if is_outlier:
264
+ analysis = "<div style='color:red;font-weight:bold;margin-bottom:10px'>Warning: The image failed outlier detection, the result may be inaccurate!</div>" + analysis
265
 
266
  return seg_map, overlay, analysis, outlier_status, url
267
 
268
+ # Spatial Alignment
269
  def process_with_alignment(location, reference_image, input_image):
270
  if reference_image is None or input_image is None:
271
+ return None, None, None, None, "Please upload both reference and target images", "Not processed", None
272
 
273
  device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
274
  model = load_model(MODEL_PATHS[location], device)
275
 
276
  if model is None:
277
+ return None, None, None, None, "Error: Failed to load model", "Not processed", None
278
 
279
  ref_bgr = cv2.cvtColor(np.array(reference_image), cv2.COLOR_RGB2BGR)
280
  tgt_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
 
283
  aligned, _ = align_images([ref_bgr, tgt_bgr], [np.zeros_like(ref_bgr), np.zeros_like(tgt_bgr)])
284
  aligned_tgt_bgr = aligned[1]
285
  except Exception as e:
286
+ print(f"Spatial alignment failed: {e}")
287
+ return None, None, None, None, f"Spatial alignment failed: {str(e)}", "Processing failed", None
288
 
289
  seg_map, overlay, analysis = perform_segmentation(model, aligned_tgt_bgr)
290
 
291
+ # Try uploading to DigitalOcean Spaces
292
+ url = "Local Storage"
293
  try:
294
  url = upload_mask(Image.fromarray(seg_map), prefix="aligned_" + location.replace(' ', '_'))
295
  except Exception as e:
296
+ print(f"Upload failed: {e}")
297
+ url = f"Upload error: {str(e)}"
298
 
299
+ status = "Spatial Alignment: <span style='color:green;font-weight:bold'>Completed</span>"
300
  ref_rgb = cv2.cvtColor(ref_bgr, cv2.COLOR_BGR2RGB)
301
  aligned_tgt_rgb = cv2.cvtColor(aligned_tgt_bgr, cv2.COLOR_BGR2RGB)
302
 
 
304
 
305
  # Create the Gradio interface
306
  def create_interface():
307
+ # Set unified display size
308
+ disp_w, disp_h = 683, 512 # Maintain aspect ratio
309
+
310
+ with gr.Blocks(title="Coastal Erosion Analysis System") as demo:
311
+ gr.Markdown("""# Coastal Erosion Analysis System
312
 
313
+ Upload coastal images for analysis, including segmentation and spatial alignment.""")
314
  with gr.Tabs():
315
+ with gr.TabItem("Single Image Segmentation"):
316
  with gr.Row():
317
+ loc1 = gr.Radio(list(MODEL_PATHS.keys()), label="Select Model", value=list(MODEL_PATHS.keys())[0])
318
  with gr.Row():
319
+ inp = gr.Image(label="Input Image", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
320
+ seg = gr.Image(label="Segmentation Map", type="numpy", height=disp_h, width=disp_w)
321
+ ovl = gr.Image(label="Overlay Image", type="numpy", height=disp_h, width=disp_w)
 
322
  with gr.Row():
323
+ btn1 = gr.Button("Run Segmentation")
324
+ url1 = gr.Text(label="Segmentation Image URL")
325
+ status1 = gr.HTML(label="Outlier Detection Status")
326
+ res1 = gr.HTML(label="Analysis Result")
327
  btn1.click(fn=process_coastal_image, inputs=[loc1, inp], outputs=[seg, ovl, res1, status1, url1])
328
 
329
+ with gr.TabItem("Spatial Alignment Segmentation"):
330
  with gr.Row():
331
+ loc2 = gr.Radio(list(MODEL_PATHS.keys()), label="Select Model", value=list(MODEL_PATHS.keys())[0])
332
  with gr.Row():
333
+ ref_img = gr.Image(label="Reference Image", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
334
+ tgt_img = gr.Image(label="Target Image", type="numpy", image_mode="RGB", height=disp_h, width=disp_w)
 
335
  with gr.Row():
336
+ btn2 = gr.Button("Run Spatial Alignment and Segmentation")
337
  with gr.Row():
338
+ orig = gr.Image(label="Original Image", type="numpy", height=disp_h, width=disp_w)
339
+ aligned = gr.Image(label="Aligned Image", type="numpy", height=disp_h, width=disp_w)
340
  with gr.Row():
341
+ seg2 = gr.Image(label="Segmentation Map", type="numpy", height=disp_h, width=disp_w)
342
+ ovl2 = gr.Image(label="Overlay Image", type="numpy", height=disp_h, width=disp_w)
343
+ url2 = gr.Text(label="Segmentation Image URL")
344
+ status2 = gr.HTML(label="Alignment Status")
345
+ res2 = gr.HTML(label="Analysis Result")
346
  btn2.click(fn=process_with_alignment, inputs=[loc2, ref_img, tgt_img], outputs=[orig, aligned, seg2, ovl2, res2, status2, url2])
347
  return demo
348
 
349
  if __name__ == "__main__":
350
+ # Create necessary directories
351
  for path in ["models", "reference_images/MM", "reference_images/SJ"]:
352
  os.makedirs(path, exist_ok=True)
353
 
354
+ # Check if model files exist
355
  for p in MODEL_PATHS.values():
356
  if not os.path.exists(p):
357
+ print(f"Warning: Model file {p} does not exist!")
358
 
359
+ # Check if DigitalOcean credentials exist
360
  do_creds = [
361
  os.environ.get('DO_SPACES_KEY'),
362
  os.environ.get('DO_SPACES_SECRET'),
 
364
  os.environ.get('DO_SPACES_BUCKET')
365
  ]
366
  if not all(do_creds):
367
+ print("Warning: Incomplete DigitalOcean Spaces credentials, upload functionality may not work")
368
 
369
+ # Create and launch the interface
370
  demo = create_interface()
 
371
  if HF_SPACE:
372
  demo.launch()
373
  else: