SandiyoS commited on
Commit
562dce4
Β·
verified Β·
1 Parent(s): 0747d1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -28
app.py CHANGED
@@ -3,32 +3,24 @@
3
  πŸ”₯ Icon Challenge Solver - YOLO Crop + Denoise Display
4
  """
5
 
6
- # ===================== ASYNCIO WARNING FIX =====================
7
- import asyncio
8
-
9
- def _safe_event_loop_del(self):
10
- try:
11
- if not self.is_closed():
12
- self.close()
13
- except (ValueError, OSError, RuntimeError):
14
- pass
15
- except Exception:
16
- pass
17
-
18
- asyncio.BaseEventLoop.__del__ = _safe_event_loop_del
19
 
 
20
  import warnings
21
- warnings.filterwarnings("ignore", category=ResourceWarning)
22
- warnings.filterwarnings("ignore", message="Exception ignored in.*BaseEventLoop.*")
23
  warnings.filterwarnings("ignore")
24
 
25
  # ===================== IMPORTS =====================
26
- import os
27
  import gc
28
  import json
29
  import logging
30
  from pathlib import Path
31
- from typing import List
32
 
33
  import torch
34
  import torch.nn as nn
@@ -36,7 +28,7 @@ import torch.nn.functional as F
36
  import torchvision.transforms as T
37
 
38
  import numpy as np
39
- from PIL import Image, ImageFilter
40
  import cv2
41
 
42
  import gradio as gr
@@ -46,10 +38,6 @@ from ultralytics import YOLO
46
  import open_clip
47
  from peft import PeftModel
48
 
49
- os.environ["PYTHONASYNCIODEBUG"] = "0"
50
- os.environ["GRADIO_ANALYTICS_ENABLED"] = "0"
51
- os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
52
-
53
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
54
  logger = logging.getLogger(__name__)
55
 
@@ -69,7 +57,7 @@ class Config:
69
 
70
  CONFIG = Config()
71
 
72
- # ===================== PREPROCESS (EXACT MATCH) =====================
73
  preprocess = T.Compose([
74
  T.Resize((256, 256), interpolation=T.InterpolationMode.NEAREST),
75
  T.ToTensor(),
@@ -129,7 +117,7 @@ def denoise_and_sharpen(crop_np: np.ndarray) -> np.ndarray:
129
  # 1. Non-local Means Denoising (hilangin pasir/noise)
130
  denoised = cv2.fastNlMeansDenoisingColored(crop_np, None, 10, 10, 7, 21)
131
 
132
- # 2. Bilateral filter (edge-preserving smoothing, hapus sisa noise)
133
  smooth = cv2.bilateralFilter(denoised, d=5, sigmaColor=50, sigmaSpace=50)
134
 
135
  # 3. Unsharp Mask (sharpening)
@@ -137,7 +125,6 @@ def denoise_and_sharpen(crop_np: np.ndarray) -> np.ndarray:
137
  sharpened = cv2.addWeighted(smooth, 1.5, gaussian, -0.5, 0)
138
 
139
  # 4. CLAHE (Contrast Limited Adaptive Histogram Equalization)
140
- # Convert ke LAB, apply CLAHE di channel L, balikin ke RGB
141
  lab = cv2.cvtColor(sharpened, cv2.COLOR_RGB2LAB)
142
  l, a, b = cv2.split(lab)
143
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
@@ -217,7 +204,7 @@ class ModelManager:
217
  logger.info("βœ… All models ready!")
218
 
219
  # --- YOLO: Detect + Crop + Denoise ---
220
- def yolo_detect_and_crop(self, image: Image.Image) -> tuple[Image.Image, Image.Image]:
221
  """
222
  Returns: (raw_crop, denoised_crop)
223
  """
@@ -302,7 +289,7 @@ def solve_gradio(challenge_img, *options):
302
  manager.init()
303
  except Exception as e:
304
  logger.error(f"Init failed: {e}", exc_info=True)
305
- return f"❌ Init failed: {e}", None, None
306
 
307
  try:
308
  if challenge_img is None or any(o is None for o in options):
@@ -358,7 +345,7 @@ def solve_gradio(challenge_img, *options):
358
 
359
  except Exception as e:
360
  logger.error(str(e), exc_info=True)
361
- return f"❌ Error: {str(e)}", None, None
362
 
363
 
364
  # ===================== GRADIO UI =====================
 
3
  πŸ”₯ Icon Challenge Solver - YOLO Crop + Denoise Display
4
  """
5
 
6
+ # ===================== ASYNCIO / UVLOOP FIX =====================
7
+ import os
8
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "0"
9
+ os.environ["PYTHONASYNCIODEBUG"] = "0"
10
+ os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
11
+ # Fix uvloop conflict dengan spaces
12
+ os.environ["UVLOOP"] = "0"
 
 
 
 
 
 
13
 
14
+ import asyncio
15
  import warnings
 
 
16
  warnings.filterwarnings("ignore")
17
 
18
  # ===================== IMPORTS =====================
 
19
  import gc
20
  import json
21
  import logging
22
  from pathlib import Path
23
+ from typing import List, Tuple
24
 
25
  import torch
26
  import torch.nn as nn
 
28
  import torchvision.transforms as T
29
 
30
  import numpy as np
31
+ from PIL import Image
32
  import cv2
33
 
34
  import gradio as gr
 
38
  import open_clip
39
  from peft import PeftModel
40
 
 
 
 
 
41
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
42
  logger = logging.getLogger(__name__)
43
 
 
57
 
58
  CONFIG = Config()
59
 
60
+ # ===================== PREPROCESS (EXACT MATCH REFERENSI) =====================
61
  preprocess = T.Compose([
62
  T.Resize((256, 256), interpolation=T.InterpolationMode.NEAREST),
63
  T.ToTensor(),
 
117
  # 1. Non-local Means Denoising (hilangin pasir/noise)
118
  denoised = cv2.fastNlMeansDenoisingColored(crop_np, None, 10, 10, 7, 21)
119
 
120
+ # 2. Bilateral filter (edge-preserving smoothing)
121
  smooth = cv2.bilateralFilter(denoised, d=5, sigmaColor=50, sigmaSpace=50)
122
 
123
  # 3. Unsharp Mask (sharpening)
 
125
  sharpened = cv2.addWeighted(smooth, 1.5, gaussian, -0.5, 0)
126
 
127
  # 4. CLAHE (Contrast Limited Adaptive Histogram Equalization)
 
128
  lab = cv2.cvtColor(sharpened, cv2.COLOR_RGB2LAB)
129
  l, a, b = cv2.split(lab)
130
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
 
204
  logger.info("βœ… All models ready!")
205
 
206
  # --- YOLO: Detect + Crop + Denoise ---
207
+ def yolo_detect_and_crop(self, image: Image.Image) -> Tuple[Image.Image, Image.Image]:
208
  """
209
  Returns: (raw_crop, denoised_crop)
210
  """
 
289
  manager.init()
290
  except Exception as e:
291
  logger.error(f"Init failed: {e}", exc_info=True)
292
+ return "❌ Init failed: " + str(e), None, None
293
 
294
  try:
295
  if challenge_img is None or any(o is None for o in options):
 
345
 
346
  except Exception as e:
347
  logger.error(str(e), exc_info=True)
348
+ return "❌ Error: " + str(e), None, None
349
 
350
 
351
  # ===================== GRADIO UI =====================