Skip to content

Commit 16c5040

Browse files
committed
Optimize: Switch to 100% In-Memory processing (no disk I/O)
1 parent d1ee48e commit 16c5040

1 file changed

Lines changed: 10 additions & 10 deletions

File tree

rp_handler.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
import sys
33
import base64
4-
import tempfile
54
import urllib.request
65

76
import cv2
@@ -186,14 +185,14 @@ def handler(job):
186185
model_name = "x4plus"
187186

188187
# Process input image
189-
tmp_dir = tempfile.mkdtemp()
190-
input_path = os.path.join(tmp_dir, "input_img.png")
188+
img = None
191189

192190
if isinstance(image_source, str) and (image_source.startswith("http://") or image_source.startswith("https://")):
193191
print(f"📥 [Web Fetch] Downloading image from URL: {image_source}")
194192
try:
195-
urllib.request.urlretrieve(image_source, input_path)
196-
img = cv2.imread(input_path, cv2.IMREAD_COLOR)
193+
with urllib.request.urlopen(image_source) as response:
194+
img_array = np.frombuffer(response.read(), np.uint8)
195+
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
197196
except Exception as e:
198197
return {"error": f"Failed to download image from URL: {str(e)}"}
199198
elif isinstance(image_source, str) and os.path.exists(image_source):
@@ -236,11 +235,12 @@ def handler(job):
236235
else:
237236
output, _ = upsampler.enhance(img, outscale=s)
238237

239-
out_path = os.path.join(tmp_dir, "output.jpg")
240-
cv2.imwrite(out_path, output, [cv2.IMWRITE_JPEG_QUALITY, 95])
241-
242-
with open(out_path, "rb") as f:
243-
b64 = base64.b64encode(f.read()).decode("utf-8")
238+
# Encode output directly to Base64 in-memory
239+
success, encoded_img = cv2.imencode(".jpg", output, [cv2.IMWRITE_JPEG_QUALITY, 95])
240+
if not success:
241+
return {"error": "Failed to encode output image"}
242+
243+
b64 = base64.b64encode(encoded_img).decode("utf-8")
244244

245245
h, w = img.shape[:2]
246246
oh, ow = output.shape[:2]

0 commit comments

Comments
 (0)