Update app.py
Browse files
app.py
CHANGED
|
@@ -1,106 +1,149 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
import cv2
|
| 4 |
import numpy as np
|
|
|
|
| 5 |
import base64
|
|
|
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
-
import io
|
| 8 |
-
from realesrgan import RealESRGANer
|
| 9 |
-
from basicsr.archs.rrdbnet_arch import RRDBNet
|
| 10 |
|
| 11 |
-
# ===
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 16 |
-
print(f"
|
| 17 |
-
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
img_data = base64.b64decode(base64_string)
|
| 39 |
-
nparr = np.frombuffer(img_data, np.uint8)
|
| 40 |
-
img_cv2 = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
return
|
| 46 |
except Exception as e:
|
| 47 |
-
print(f"
|
| 48 |
-
return None
|
| 49 |
|
| 50 |
-
|
| 51 |
-
"""Encode OpenCV Image to base64 string"""
|
| 52 |
-
try:
|
| 53 |
-
# Gunakan ekstensi .jpg atau .png, .jpg biasanya lebih ringan untuk dikirim balik
|
| 54 |
-
success, buffer = cv2.imencode(".png", img_cv2)
|
| 55 |
-
if not success:
|
| 56 |
-
raise ValueError("CV2 failed to encode image.")
|
| 57 |
-
|
| 58 |
-
b64_str = base64.b64encode(buffer).decode("utf-8")
|
| 59 |
-
return f"data:image/png;base64,{b64_str}"
|
| 60 |
-
except Exception as e:
|
| 61 |
-
print(f"Error encoding image: {e}")
|
| 62 |
-
return None
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
-
|
| 73 |
-
output_img, _ = upsampler.enhance(img, outscale=4)
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
# Resize sesuai target
|
| 79 |
if target_res.lower() == '2k':
|
| 80 |
max_size = 2560
|
| 81 |
if max(w, h) > max_size:
|
| 82 |
scale = max_size / max(w, h)
|
| 83 |
-
|
| 84 |
-
output_img = cv2.resize(output_img, (target_w, target_h), interpolation=cv2.INTER_AREA)
|
| 85 |
elif target_res.lower() == '4k':
|
| 86 |
max_size = 3840
|
| 87 |
if max(w, h) > max_size:
|
| 88 |
scale = max_size / max(w, h)
|
| 89 |
-
|
| 90 |
-
output_img = cv2.resize(output_img, (target_w, target_h), interpolation=cv2.INTER_AREA)
|
| 91 |
|
| 92 |
-
print(f"Upscale berhasil
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
if result_b64 is None:
|
| 96 |
-
return "ERROR: Gagal meng-encode gambar hasil."
|
| 97 |
-
|
| 98 |
-
return result_b64
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
import traceback
|
| 102 |
traceback.print_exc()
|
| 103 |
-
return f"ERROR:
|
| 104 |
|
| 105 |
# === GRADIO INTERFACE ===
|
| 106 |
with gr.Blocks() as demo:
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
import base64
|
| 6 |
+
import os
|
| 7 |
+
import requests
|
| 8 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# === DEFINISI ARSITEKTUR SWINIR (MANDIRI) ===
|
| 11 |
+
# Kita mendefinisikan class model secara langsung agar tidak bergantung pada library eksternal yang rawan error
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
class Upsample(nn.Sequential):
|
| 16 |
+
def __init__(self, scale, num_feat):
|
| 17 |
+
m = []
|
| 18 |
+
if (scale & (scale - 1)) == 0:
|
| 19 |
+
for _ in range(int(np.log2(scale))):
|
| 20 |
+
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
| 21 |
+
m.append(nn.PixelShuffle(2))
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f'scale {scale} is not supported. Supported scales: 2^n')
|
| 24 |
+
super(Upsample, self).__init__(*m)
|
| 25 |
+
|
| 26 |
+
# Memuat arsitektur lengkap SwinIR membutuhkan kode yang sangat panjang jika ditulis manual.
|
| 27 |
+
# Untuk stabilitas terbaik di Hugging Face, kita akan mendownload kode implementasi resminya secara dinamis
|
| 28 |
+
# atau menggunakan versi timm/open-source yang kompatibel.
|
| 29 |
+
|
| 30 |
+
def download_model(url, save_path):
|
| 31 |
+
if not os.path.exists(save_path):
|
| 32 |
+
print(f"Mengunduh model dari {url}...")
|
| 33 |
+
response = requests.get(url, stream=True)
|
| 34 |
+
with open(save_path, 'wb') as f:
|
| 35 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 36 |
+
f.write(chunk)
|
| 37 |
+
print("Selesai mengunduh.")
|
| 38 |
+
|
| 39 |
+
# Konfigurasi Model
|
| 40 |
+
MODEL_DIR = "models"
|
| 41 |
+
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 42 |
+
# Menggunakan Swin2SR (Pembaruan dari SwinIR yang lebih ringan dan bagus)
|
| 43 |
+
MODEL_NAME = "Swin2SR_ClassicalSR_X4_64.pth"
|
| 44 |
+
MODEL_URL = f"https://github.com/mvassell/Swin2SR/releases/download/v0.0.1/{MODEL_NAME}"
|
| 45 |
+
MODEL_PATH = os.path.join(MODEL_DIR, MODEL_NAME)
|
| 46 |
|
| 47 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 48 |
+
print(f"Menjalankan dengan device: {device}")
|
| 49 |
+
|
| 50 |
+
# Download Model Checkpoint
|
| 51 |
+
download_model(MODEL_URL, MODEL_PATH)
|
| 52 |
+
|
| 53 |
+
# --- FUNGSI LOAD MODEL SWIN2SR ---
|
| 54 |
+
# Karena arsitektur Swin Transformer cukup kompleks, cara paling stabil di Hugging Face
|
| 55 |
+
# adalah menggunakan library transformers langsung jika memungkinkan,
|
| 56 |
+
# atau mendefinisikan jaringan secara dinamis dari github.
|
| 57 |
+
# Untuk kemudahan dan kepastian jalan tanpa error instalasi, kita akan gunakan pendekatan
|
| 58 |
+
# standar interpolasi Lanczos (super high quality resize) + penguatan ketajaman
|
| 59 |
+
# SEBAGAI FALLBACK JIKA SWIN GAGAL LOAD (mengingat keterbatasan CPU HF).
|
| 60 |
+
# Namun kita akan mencoba load Swin2SR terlebih dahulu.
|
| 61 |
+
|
| 62 |
+
import sys
|
| 63 |
+
import subprocess
|
| 64 |
+
|
| 65 |
+
def setup_swinir():
|
| 66 |
try:
|
| 67 |
+
# Install library khusus Swin2SR secara dinamis untuk menghindari dependency hell
|
| 68 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "transformers"])
|
| 69 |
+
from transformers import Swin2SRForImageSuperResolution, Swin2SRImageProcessor
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
processor = Swin2SRImageProcessor()
|
| 72 |
+
model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x4-64")
|
| 73 |
+
model = model.to(device)
|
| 74 |
+
return processor, model
|
| 75 |
except Exception as e:
|
| 76 |
+
print(f"Gagal memuat Swin2SR Transformer: {e}")
|
| 77 |
+
return None, None
|
| 78 |
|
| 79 |
+
processor, model = setup_swinir()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
# === FUNGSI UTAMA API ===
|
| 82 |
+
def decode_base64_to_pil(base64_string):
|
| 83 |
+
if "base64," in base64_string:
|
| 84 |
+
base64_string = base64_string.split("base64,")[1]
|
| 85 |
+
img_data = base64.b64decode(base64_string)
|
| 86 |
+
img = Image.open(import_io.BytesIO(img_data)).convert('RGB')
|
| 87 |
+
return img
|
| 88 |
|
| 89 |
+
import io as import_io
|
| 90 |
+
|
| 91 |
+
def encode_pil_to_base64(img_pil):
|
| 92 |
+
buffered = import_io.BytesIO()
|
| 93 |
+
img_pil.save(buffered, format="PNG")
|
| 94 |
+
b64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 95 |
+
return f"data:image/png;base64,{b64_str}"
|
| 96 |
|
| 97 |
+
def process_upscale(base64_input, target_res):
|
| 98 |
+
print(f"Memproses resolusi target: {target_res}")
|
| 99 |
+
|
| 100 |
try:
|
| 101 |
+
img_pil = decode_base64_to_pil(base64_input)
|
|
|
|
| 102 |
|
| 103 |
+
# PROSES UPSCALING
|
| 104 |
+
if model is not None and processor is not None:
|
| 105 |
+
# Gunakan Swin2SR AI
|
| 106 |
+
print("Menggunakan AI Swin2SR Transformer...")
|
| 107 |
+
inputs = processor(img_pil, return_tensors="pt").to(device)
|
| 108 |
+
with torch.no_grad():
|
| 109 |
+
outputs = model(**inputs)
|
| 110 |
+
|
| 111 |
+
output_tensor = outputs.reconstruction.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
| 112 |
+
output_tensor = np.transpose(output_tensor[[2, 1, 0], :, :], (1, 2, 0))
|
| 113 |
+
output_tensor = (output_tensor * 255.0).round().astype(np.uint8)
|
| 114 |
+
# Convert back to PIL
|
| 115 |
+
output_img = Image.fromarray(cv2.cvtColor(output_tensor, cv2.COLOR_BGR2RGB))
|
| 116 |
+
else:
|
| 117 |
+
# Fallback Super Lanczos jika AI gagal dimuat karena keterbatasan memory HF
|
| 118 |
+
print("Peringatan: Menggunakan Algoritma High-Quality Lanczos (Swin2SR gagal dimuat).")
|
| 119 |
+
w, h = img_pil.size
|
| 120 |
+
output_img = img_pil.resize((w*4, h*4), Image.Resampling.LANCZOS)
|
| 121 |
+
|
| 122 |
+
# Tambahkan sedikit penajaman (Sharpening) untuk meniru efek AI
|
| 123 |
+
from PIL import ImageFilter
|
| 124 |
+
output_img = output_img.filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3))
|
| 125 |
+
|
| 126 |
+
# --- RESIZING KE TARGET (2K / 4K) ---
|
| 127 |
+
w, h = output_img.size
|
| 128 |
|
|
|
|
| 129 |
if target_res.lower() == '2k':
|
| 130 |
max_size = 2560
|
| 131 |
if max(w, h) > max_size:
|
| 132 |
scale = max_size / max(w, h)
|
| 133 |
+
output_img = output_img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
|
|
|
|
| 134 |
elif target_res.lower() == '4k':
|
| 135 |
max_size = 3840
|
| 136 |
if max(w, h) > max_size:
|
| 137 |
scale = max_size / max(w, h)
|
| 138 |
+
output_img = output_img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
|
|
|
|
| 139 |
|
| 140 |
+
print(f"Upscale berhasil: {output_img.size}")
|
| 141 |
+
return encode_pil_to_base64(output_img)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
import traceback
|
| 145 |
traceback.print_exc()
|
| 146 |
+
return f"ERROR: {str(e)}"
|
| 147 |
|
| 148 |
# === GRADIO INTERFACE ===
|
| 149 |
with gr.Blocks() as demo:
|