Spaces:
Running on Zero

File size: 1,892 Bytes
bf55f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import hashlib
import math
from base64 import b64decode
from io import BytesIO

DEFAULT_DENOISE = 0.6
MAX_REFERENCE_BYTES = 640 * 1024
REFERENCE_EXTENSIONS = {"PNG": "png", "JPEG": "jpg"}


def normalize_denoise(value):
    try:
        value = float(value)
    except (TypeError, ValueError):
        raise ValueError("请填写 0.01 至 1.00 的重绘强度。") from None
    if not math.isfinite(value) or not 0.01 <= value <= 1:
        raise ValueError("重绘强度须在 0.01 至 1.00 之间。")
    return value


def reference_info(data):
    from PIL import Image, UnidentifiedImageError

    if not 0 < len(data) <= MAX_REFERENCE_BYTES:
        raise ValueError("处理后的参考图超过 640 KiB,或文件为空。")
    try:
        with Image.open(BytesIO(data), formats=tuple(REFERENCE_EXTENSIONS)) as image:
            width, height = image.size
            if min(width, height) < 16 or max(width, height) > 2048 or getattr(image, "n_frames", 1) != 1:
                raise ValueError("参考图须为单张静态图片,宽高须在 16 至 2048 像素之间。")
            if image.mode != "RGB":
                raise ValueError("处理后的参考图须为 RGB 图片。")
            image.load()
            extension = REFERENCE_EXTENSIONS[image.format]
    except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
        raise ValueError("无法读取参考图,请重新选择 PNG、JPEG 或 WebP 图片。") from None
    return hashlib.sha256(data).hexdigest(), extension, (width, height)


def decode_reference(payload):
    if not isinstance(payload, str) or len(payload) > 4 * ((MAX_REFERENCE_BYTES + 2) // 3):
        raise ValueError("参考图缺失或超过上传大小限制。")
    try:
        return b64decode(payload, validate=True)
    except ValueError:
        raise ValueError("参考图传输格式无效。") from None