File size: 2,577 Bytes
a027087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Enhance one local input with the genuine Real-ESRGAN model."""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
import time
from pathlib import Path
from typing import cast

BACKEND_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BACKEND_ROOT))

from app.config import settings  # noqa: E402
from app.models.contracts import Scale  # noqa: E402
from app.services.enhancer import ImageEnhancer  # noqa: E402
from app.utils.image_io import encode_image  # noqa: E402


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for chunk in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--input",
        type=Path,
        default=BACKEND_ROOT / "tests" / "fixtures" / "0014.jpg",
        help="Path to one supported local image.",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=BACKEND_ROOT / "outputs" / "0014-enhanced-4x.png",
        help="Path for the full-resolution PNG result.",
    )
    parser.add_argument("--scale", type=int, choices=(2, 4), default=4)
    parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default=None)
    arguments = parser.parse_args()

    if arguments.device is not None:
        settings.device = arguments.device

    started = time.perf_counter()
    enhancer = ImageEnhancer(settings)
    result = enhancer.enhance_path(arguments.input, scale=cast(Scale, arguments.scale))
    dimensions = encode_image(result.image, None, arguments.output, output_format="png")
    report = {
        "input": str(arguments.input.resolve()),
        "output": str(arguments.output.resolve()),
        "input_dimensions": [result.original_width, result.original_height],
        "output_dimensions": list(dimensions),
        "requested_scale": result.scale,
        "model": result.model,
        "device": result.device,
        "precision": enhancer.precision,
        "checkpoint": str(enhancer.weights_path),
        "checkpoint_sha256": _sha256(enhancer.weights_path),
        "elapsed_seconds": round(time.perf_counter() - started, 3),
    }
    print(json.dumps(report, indent=2))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:
        print(f"Real-ESRGAN smoke test failed: {error}", file=sys.stderr)
        raise SystemExit(1) from error