mastari commited on
Commit
4d4df77
ยท
1 Parent(s): d3b28dd

Add full diagnostic prints for debugging

Browse files
Files changed (1) hide show
  1. handler.py +88 -35
handler.py CHANGED
@@ -10,7 +10,9 @@ from basicsr.archs.rrdbnet_arch import RRDBNet
10
 
11
  class EndpointHandler:
12
  def __init__(self, path="."):
13
- print("๐Ÿ”น Initializing Real-ESRGAN x4 model...")
 
 
14
 
15
  self.model_url = (
16
  "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/"
@@ -19,13 +21,16 @@ class EndpointHandler:
19
  self.model_path = os.path.join(path, "RealESRGAN_x4plus.pth")
20
 
21
  if not os.path.exists(self.model_path):
22
- print(f"๐Ÿ“ฅ Downloading RealESRGAN_x4plus.pth ...")
23
  r = requests.get(self.model_url)
24
  r.raise_for_status()
25
  with open(self.model_path, "wb") as f:
26
  f.write(r.content)
27
- print(f"โœ… Downloaded model to {self.model_path}")
 
 
28
 
 
29
  model = RRDBNet(
30
  num_in_ch=3,
31
  num_out_ch=3,
@@ -35,69 +40,117 @@ class EndpointHandler:
35
  scale=4,
36
  )
37
 
 
 
 
38
  self.upsampler = RealESRGANer(
39
  scale=4,
40
  model_path=self.model_path,
41
  model=model,
42
  half=False,
43
- device="cuda" if torch.cuda.is_available() else "cpu",
44
  )
45
 
46
- print("โœ… Real-ESRGAN model initialized and ready.")
47
 
48
  # ==========================================================
49
- # Main callable
50
  # ==========================================================
51
  def __call__(self, data):
 
 
 
 
52
  try:
 
53
  image = self.preprocess(data)
 
 
 
54
  output = self.inference(image)
55
- return self.postprocess(output)
 
 
 
 
 
 
56
  except Exception as e:
57
- print("โŒ Error:", str(e))
58
  return {"error": str(e)}
59
 
60
  # ==========================================================
61
- # Steps
62
  # ==========================================================
63
  def preprocess(self, data):
64
- """Accept raw bytes, dicts, or wrapped HF JSON input."""
65
- # Case 1: raw bytes
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  if isinstance(data, (bytes, bytearray)):
 
 
67
  return Image.open(io.BytesIO(data)).convert("RGB")
68
 
69
- # Case 2: HF JSON payload like {"inputs": ...}
70
- if isinstance(data, dict):
71
- img_field = data.get("inputs") or data.get("image") or data
72
- # If bytes-like
73
- if isinstance(img_field, (bytes, bytearray)):
74
- return Image.open(io.BytesIO(img_field)).convert("RGB")
75
- # If base64 string
76
- if isinstance(img_field, str):
77
- try:
78
- decoded = base64.b64decode(img_field)
79
- return Image.open(io.BytesIO(decoded)).convert("RGB")
80
- except Exception:
81
- raise ValueError("Invalid base64 data in 'inputs' field.")
82
-
83
- # Case 3: Hugging Face wraps even raw bytes under a dict with 'inputs' -> list
84
- if isinstance(data, list) and len(data) > 0:
85
- item = data[0]
86
- if isinstance(item, (bytes, bytearray)):
87
- return Image.open(io.BytesIO(item)).convert("RGB")
88
- if isinstance(item, str):
89
- return Image.open(io.BytesIO(base64.b64decode(item))).convert("RGB")
90
-
91
- raise ValueError("Expected raw image bytes or {'inputs': <bytes/base64>}.")
 
92
 
 
 
 
 
 
93
  def inference(self, image):
 
 
94
  output, _ = self.upsampler.enhance(image, outscale=4)
 
95
  return output
96
 
 
 
 
97
  def postprocess(self, output_image):
 
98
  buf = io.BytesIO()
99
  output_image.save(buf, format="PNG")
100
- encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
 
 
 
101
  buf.close()
102
  return {"image": encoded}
103
 
 
10
 
11
  class EndpointHandler:
12
  def __init__(self, path="."):
13
+ print("๐Ÿš€ [INIT] Starting EndpointHandler initialization...")
14
+ print(f"๐Ÿ“‚ Working directory: {os.getcwd()}")
15
+ print(f"๐Ÿ“ Model path root: {path}")
16
 
17
  self.model_url = (
18
  "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/"
 
21
  self.model_path = os.path.join(path, "RealESRGAN_x4plus.pth")
22
 
23
  if not os.path.exists(self.model_path):
24
+ print(f"๐Ÿ“ฅ [DOWNLOAD] Fetching model weights from {self.model_url}")
25
  r = requests.get(self.model_url)
26
  r.raise_for_status()
27
  with open(self.model_path, "wb") as f:
28
  f.write(r.content)
29
+ print(f"โœ… [DOWNLOAD] Saved model to {self.model_path}")
30
+ else:
31
+ print(f"โœ… [CACHE] Model already exists at {self.model_path}")
32
 
33
+ print("๐Ÿง  [MODEL] Building RRDBNet...")
34
  model = RRDBNet(
35
  num_in_ch=3,
36
  num_out_ch=3,
 
40
  scale=4,
41
  )
42
 
43
+ device = "cuda" if torch.cuda.is_available() else "cpu"
44
+ print(f"๐Ÿ’ป [DEVICE] Using device: {device}")
45
+
46
  self.upsampler = RealESRGANer(
47
  scale=4,
48
  model_path=self.model_path,
49
  model=model,
50
  half=False,
51
+ device=device,
52
  )
53
 
54
+ print("โœ… [INIT DONE] Real-ESRGAN model initialized and ready.\n\n")
55
 
56
  # ==========================================================
57
+ # MAIN CALLABLE
58
  # ==========================================================
59
  def __call__(self, data):
60
+ print("๐Ÿ›ฐ๏ธ [CALL] Endpoint invoked!")
61
+ print(f"๐Ÿ“ฆ [CALL] Raw data type: {type(data)}")
62
+ print(f"๐Ÿ” [CALL] Data preview: {str(data)[:300]}...")
63
+
64
  try:
65
+ print("โžก๏ธ [STEP] Preprocessing input...")
66
  image = self.preprocess(data)
67
+ print("โœ… [STEP] Preprocessing complete!")
68
+
69
+ print("โžก๏ธ [STEP] Running inference...")
70
  output = self.inference(image)
71
+ print("โœ… [STEP] Inference complete!")
72
+
73
+ print("โžก๏ธ [STEP] Encoding output image...")
74
+ result = self.postprocess(output)
75
+ print("โœ… [STEP] Postprocessing complete!")
76
+
77
+ return result
78
  except Exception as e:
79
+ print("๐Ÿ’ฅ [ERROR] Exception during inference:", str(e))
80
  return {"error": str(e)}
81
 
82
  # ==========================================================
83
+ # PREPROCESS
84
  # ==========================================================
85
  def preprocess(self, data):
86
+ print(f"๐Ÿ”ง [PREPROCESS] Type received: {type(data)}")
87
+
88
+ # 1๏ธโƒฃ Hugging Face JSON-wrapped dict {"inputs": ...}
89
+ if isinstance(data, dict):
90
+ print("๐Ÿงฉ [PREPROCESS] Detected dict input.")
91
+ if "inputs" in data:
92
+ print("๐Ÿ“จ [PREPROCESS] Found 'inputs' key in dict.")
93
+ data = data["inputs"]
94
+ elif "image" in data:
95
+ print("๐Ÿ“จ [PREPROCESS] Found 'image' key in dict.")
96
+ data = data["image"]
97
+ else:
98
+ print("โš ๏ธ [PREPROCESS] Dict has no 'inputs' or 'image' keys.")
99
+
100
+ # 2๏ธโƒฃ Bytes
101
  if isinstance(data, (bytes, bytearray)):
102
+ print("๐Ÿ–ผ๏ธ [PREPROCESS] Treating input as raw bytes.")
103
+ print(f"๐Ÿงฎ [BYTES] Length: {len(data)}")
104
  return Image.open(io.BytesIO(data)).convert("RGB")
105
 
106
+ # 3๏ธโƒฃ Base64 string
107
+ if isinstance(data, str):
108
+ print("๐Ÿงพ [PREPROCESS] Treating input as base64 string.")
109
+ print(f"๐Ÿงฎ [BASE64] Length: {len(data)}")
110
+ try:
111
+ decoded = base64.b64decode(data)
112
+ print(f"โœ… [BASE64] Successfully decoded base64 -> {len(decoded)} bytes.")
113
+ return Image.open(io.BytesIO(decoded)).convert("RGB")
114
+ except Exception as e:
115
+ print("๐Ÿ’ฅ [BASE64] Decode failed:", str(e))
116
+ raise ValueError("Invalid base64 string in request body.")
117
+
118
+ # 4๏ธโƒฃ List of inputs (some HF payloads wrap inside a list)
119
+ if isinstance(data, list):
120
+ print(f"๐Ÿ“š [PREPROCESS] List input detected with length {len(data)}")
121
+ if len(data) == 0:
122
+ raise ValueError("Empty input list.")
123
+ first = data[0]
124
+ print(f"๐Ÿ”น [PREPROCESS] First element type: {type(first)}")
125
+ if isinstance(first, (bytes, bytearray)):
126
+ return Image.open(io.BytesIO(first)).convert("RGB")
127
+ if isinstance(first, str):
128
+ decoded = base64.b64decode(first)
129
+ return Image.open(io.BytesIO(decoded)).convert("RGB")
130
 
131
+ raise ValueError("Unsupported input type. Expected image bytes or base64 data.")
132
+
133
+ # ==========================================================
134
+ # INFERENCE
135
+ # ==========================================================
136
  def inference(self, image):
137
+ print("๐ŸŽฏ [INFERENCE] Running ESRGAN upscaling...")
138
+ print(f"๐Ÿ“ [INFERENCE] Input image size: {image.size}")
139
  output, _ = self.upsampler.enhance(image, outscale=4)
140
+ print(f"โœ… [INFERENCE] Output image size: {output.size}")
141
  return output
142
 
143
+ # ==========================================================
144
+ # POSTPROCESS
145
+ # ==========================================================
146
  def postprocess(self, output_image):
147
+ print("๐Ÿ“ค [POSTPROCESS] Encoding image to base64...")
148
  buf = io.BytesIO()
149
  output_image.save(buf, format="PNG")
150
+ raw_bytes = buf.getvalue()
151
+ print(f"๐Ÿ“ [POSTPROCESS] Output image byte size: {len(raw_bytes)}")
152
+ encoded = base64.b64encode(raw_bytes).decode("utf-8")
153
+ print(f"โœ… [POSTPROCESS] Base64 encoded length: {len(encoded)}")
154
  buf.close()
155
  return {"image": encoded}
156