File size: 8,049 Bytes
cfd987c
 
 
 
 
 
 
 
79595b4
 
 
 
 
cfd987c
79595b4
cfd987c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79595b4
cfd987c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79595b4
 
 
 
cfd987c
 
 
 
79595b4
cfd987c
 
 
 
 
 
 
79595b4
cfd987c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79595b4
 
 
 
 
 
cfd987c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import os
import time
import torch
import numpy as np
from PIL import Image


def detect_device():
    """Auto-detect device. Returns CPU on ZeroGPU (GPU not available at startup).

    Always uses fp32 — DAT2 architecture produces NaN in fp16 (attention softmax
    + LayerNorm overflow). 48GB VRAM is more than sufficient for fp32.
    """
    if torch.cuda.is_available():
        return "cuda", torch.float32
    return "cpu", torch.float32


# ---------------------------------------------------------------------------
# HuggingFace Hub 模型下载
# ---------------------------------------------------------------------------
# 默认从 Kim2091/UltraSharpV2 公开仓库下载,可通过环境变量覆盖:
#   MODEL_REPO_ID    - 覆盖默认仓库 ID
#   MODEL_FILENAME   - 覆盖默认文件名
#   HF_ENDPOINT      - 镜像站地址,如 https://hf-mirror.com(国内加速)
#   HF_TOKEN         - 私有仓库的 token(公开仓库无需设置)
# ---------------------------------------------------------------------------

_DEFAULT_REPO_ID = "Kim2091/UltraSharpV2"
_DEFAULT_FILENAME = "4x-UltraSharpV2.pth"

MODEL_CANDIDATES = [
    "4x-UltraSharpV2.pth",
    "4x-UltraSharpV2.safetensors",
    "4x-UltraSharpV2.pt",
]


def _download_from_hub(repo_id: str, filename: str) -> str:
    """从 HuggingFace Hub 下载模型文件(自动缓存,重复调用不重新下载)。"""
    from huggingface_hub import hf_hub_download

    token = os.environ.get("HF_TOKEN")
    endpoint = os.environ.get("HF_ENDPOINT")
    if endpoint:
        print(f"[UltraSharpV2] 使用镜像: {endpoint}")

    print(f"[UltraSharpV2] 从 HF Hub 下载: {repo_id}/{filename}")
    path = hf_hub_download(
        repo_id=repo_id,
        filename=filename,
        token=token,
        endpoint=endpoint,
    )
    print(f"[UltraSharpV2] 下载成功: {path}")
    return path


def _resolve_model_path() -> str:
    """按优先级解析模型路径: 本地文件 > HF Hub(默认 Kim2091/UltraSharpV2)。"""
    # 1) 本地文件优先(存在则直接使用,跳过网络)
    for name in MODEL_CANDIDATES:
        if os.path.exists(name):
            print(f"[UltraSharpV2] 使用本地模型: {name}")
            return name

    # 2) 从 HF Hub 下载
    repo_id = os.environ.get("MODEL_REPO_ID", _DEFAULT_REPO_ID)
    filename = os.environ.get("MODEL_FILENAME", _DEFAULT_FILENAME)
    return _download_from_hub(repo_id, filename)


class UltraSharpV2:
    def __init__(self, model_path=None, device=None):
        """
        Args:
            model_path: path to model file (auto-resolve from HF Hub or local if None).
            device: "cpu" (ZeroGPU default), "cuda", or None (auto-detect).
        """
        if model_path is None:
            model_path = _resolve_model_path()

        if device is not None:
            self.device = device
            self.dtype = torch.float32
        else:
            self.device, self.dtype = detect_device()

        self._model_path = model_path
        self.model = self._load_model(model_path)
        self.scale = self.model.scale
        print(f"[UltraSharpV2] 设备: {self.device}, 精度: {self.dtype}")
        print(f"[UltraSharpV2] 模型加载完毕, 放大倍率: {self.scale}x")

    def _load_model(self, path):
        from spandrel import ModelLoader

        loader = ModelLoader()
        model = loader.load_from_file(path)
        model.model.to(self.device).to(self.dtype).eval()
        return model

    def to_cuda(self):
        """Move model to CUDA (called inside @spaces.GPU decorated function).

        Keeps fp32 — DAT2 architecture produces NaN in fp16.
        """
        if self.device == "cuda":
            return
        print("[UltraSharpV2] 正在将模型移至 GPU ...")
        self.device = "cuda"
        self.model.model.to(self.device)
        torch.cuda.empty_cache()

    def to_cpu(self):
        """Move model back to CPU to release ZeroGPU memory."""
        if self.device == "cpu":
            return
        print("[UltraSharpV2] 正在将模型移回 CPU ...")
        self.model.model.to("cpu")
        self.device = "cpu"
        torch.cuda.empty_cache()

    def upscale(
        self,
        image: Image.Image,
        tile_size: int = 512,
        tile_overlap: int = 32,
        target_scale: float = 4.0,
    ) -> tuple[Image.Image, float]:
        start = time.time()

        tensor = self._pil_to_tensor(image)
        _, _, h, w = tensor.shape

        if h <= tile_size and w <= tile_size:
            with torch.no_grad():
                output = self.model(tensor.to(self.dtype)).float()
        else:
            output = self._tiled_upscale(tensor, tile_size, tile_overlap)

        result = self._tensor_to_pil(output)

        if target_scale > 0 and abs(target_scale - self.scale) > 0.01:
            dest_w = int(w * target_scale)
            dest_h = int(h * target_scale)
            result = result.resize((dest_w, dest_h), Image.LANCZOS)

        elapsed = time.time() - start
        print(
            f"[UltraSharpV2] 推理完成, 尺寸: {h}x{w} -> {result.width}x{result.height}, 耗时: {elapsed:.2f}s"
        )
        return result, elapsed

    def _pil_to_tensor(self, img: Image.Image) -> torch.Tensor:
        if img.mode != "RGB":
            img = img.convert("RGB")
        arr = np.array(img).astype(np.float32) / 255.0
        tensor = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)
        return tensor.to(self.device)

    def _tensor_to_pil(self, tensor: torch.Tensor) -> Image.Image:
        tensor = tensor.squeeze(0).float()
        if torch.isnan(tensor).any() or torch.isinf(tensor).any():
            raise RuntimeError(
                "模型输出包含 NaN/Inf — 请检查是否使用了 fp16(DAT2 架构不支持 fp16)"
            )
        tensor = tensor.clamp(0, 1)
        arr = (tensor.permute(1, 2, 0).cpu().numpy() * 255).round().astype(np.uint8)
        return Image.fromarray(arr)

    def _tiled_upscale(
        self, tensor: torch.Tensor, tile_size: int, tile_overlap: int
    ) -> torch.Tensor:
        _, c, h, w = tensor.shape
        scale = self.scale
        pad = min(tile_overlap, tile_size // 4)

        padded = torch.nn.functional.pad(
            tensor, (pad, pad, pad, pad), mode="reflect"
        )
        _, _, hp, wp = padded.shape

        out_tile = tile_size * scale
        out_hp = hp * scale
        out_wp = wp * scale
        stride = tile_size - pad * 2

        output = torch.zeros(1, c, out_hp, out_wp, device=self.device, dtype=torch.float32)
        weight = torch.zeros(1, 1, out_hp, out_wp, device=self.device, dtype=torch.float32)

        wy = torch.ones(out_tile, device=self.device)
        wx = torch.ones(out_tile, device=self.device)
        if pad > 0:
            ramp = torch.linspace(0, 1, pad * scale, device=self.device)
            wy[: pad * scale] = ramp
            wy[-pad * scale :] = ramp.flip(0)
            wx[: pad * scale] = ramp
            wx[-pad * scale :] = ramp.flip(0)
        wmap = wy.view(1, 1, -1, 1) * wx.view(1, 1, 1, -1)

        for y in range(0, hp, stride):
            for x in range(0, wp, stride):
                y1 = min(y + tile_size, hp)
                x1 = min(x + tile_size, wp)
                y0 = max(0, y1 - tile_size)
                x0 = max(0, x1 - tile_size)

                tile = padded[:, :, y0:y1, x0:x1]
                with torch.no_grad():
                    out = self.model(tile.to(self.dtype)).float()

                oh, ow = out.shape[2], out.shape[3]
                oy0, ox0 = y0 * scale, x0 * scale
                wc = wmap[:, :, :oh, :ow]

                output[:, :, oy0 : oy0 + oh, ox0 : ox0 + ow] += out * wc
                weight[:, :, oy0 : oy0 + oh, ox0 : ox0 + ow] += wc

        output /= weight.clamp(min=1e-8)

        crop_start = pad * scale
        crop_end_h = crop_start + h * scale
        crop_end_w = crop_start + w * scale
        return output[:, :, crop_start:crop_end_h, crop_start:crop_end_w]