File size: 8,152 Bytes
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
5dc8e48
fe07779
5dc8e48
 
 
 
fe07779
 
 
 
 
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
fe07779
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
 
 
 
 
 
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe07779
 
5dc8e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import argparse
import os
import shutil
from pathlib import Path
from urllib.parse import unquote, urlparse


IMAGE_EXTENSIONS = {".bmp", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".webp"}
DEFAULT_SPACE_ID = "alotofmovingparts/DocRes-Appearance"


def input_paths(image_source):
    source = Path(image_source)
    if source.is_dir():
        return [
            str(path)
            for path in sorted(source.iterdir())
            if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS
        ]
    return [str(source)]


def source_stem(img_path):
    parsed = urlparse(str(img_path))
    source_path = unquote(parsed.path) if parsed.scheme else str(img_path)
    return Path(source_path).stem or "image"


def output_path_for_source(img_path, out_folder, output_suffix=".png"):
    suffix = output_suffix if output_suffix.lower() in IMAGE_EXTENSIONS else ".png"
    return Path(out_folder) / f"{source_stem(img_path)}_appearance{suffix}"


def normalize_space_result_path(result):
    if isinstance(result, (list, tuple)):
        if len(result) != 1:
            raise RuntimeError(f"Expected one Space API result, received {len(result)}")
        result = result[0]

    if isinstance(result, dict):
        result = result.get("path") or result.get("name")
    else:
        result = getattr(result, "path", result)

    if not result:
        raise RuntimeError("Space API did not return an output file path")
    return str(result)


def save_space_result(img_path, out_folder, result):
    result_path = Path(normalize_space_result_path(result))
    if not result_path.exists():
        raise FileNotFoundError(f"Could not read Space API result: {result_path}")

    output_suffix = result_path.suffix or ".png"
    save_path = output_path_for_source(img_path, out_folder, output_suffix)
    save_path.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(result_path, save_path)
    return save_path


def save_results(img_path, out_folder, prompt, restored, save_dtsprompt, strength):
    import cv2
    from inference import blend_with_original

    Path(out_folder).mkdir(parents=True, exist_ok=True)
    path = Path(img_path)
    save_path = Path(out_folder) / f"{path.stem}_appearance{path.suffix}"
    if strength < 1.0:
        original = cv2.imread(str(img_path), cv2.IMREAD_COLOR)
        if original is None:
            raise FileNotFoundError(f"Could not read input image: {img_path}")
        restored = blend_with_original(original, restored, strength)
    if not cv2.imwrite(str(save_path), restored):
        raise RuntimeError(f"Could not write restored image: {save_path}")
    if save_dtsprompt:
        prompt_paths = [
            save_path.with_name(f"{save_path.stem}_prompt1{save_path.suffix}"),
            save_path.with_name(f"{save_path.stem}_prompt2{save_path.suffix}"),
            save_path.with_name(f"{save_path.stem}_prompt3{save_path.suffix}"),
        ]
        for channel, prompt_path in enumerate(prompt_paths):
            if not cv2.imwrite(str(prompt_path), prompt[:, :, channel]):
                raise RuntimeError(f"Could not write prompt image: {prompt_path}")
    return save_path


def predict_space_api(image_path, client, max_size=1280, prompt_size=1024, strength=1.0):
    try:
        from gradio_client import handle_file
    except ImportError as exc:
        raise RuntimeError(
            "The Hugging Face Space API mode requires gradio_client. "
            "Install it with `pip install gradio_client`."
        ) from exc

    return client.predict(
        image=handle_file(str(image_path)),
        max_size=max_size,
        prompt_size=prompt_size,
        strength=strength,
        api_name="/predict",
    )


def run_space_api(args):
    try:
        from gradio_client import Client
    except ImportError as exc:
        raise RuntimeError(
            "The Hugging Face Space API mode requires gradio_client. "
            "Install it with `pip install gradio_client`."
        ) from exc

    client = Client(args.space_id, token=args.hf_token)
    print(f"Using Hugging Face Space API: {args.space_id}")

    for img_path in input_paths(args.im_path):
        result = predict_space_api(
            img_path,
            client,
            args.max_size,
            args.prompt_size,
            args.strength,
        )
        save_path = save_space_result(img_path, args.out_folder, result)
        print(f"Saved: {save_path}")


def run_local(args):
    from inference import load_model, restore_appearance, select_device

    device = select_device(args.device)
    print(f"Using device: {device}")
    model = load_model(args.model_path, device, args.precision)

    for img_path in input_paths(args.im_path):
        prompt, restored = restore_appearance(
            model,
            img_path,
            device,
            args.precision,
            args.max_size,
            args.prompt_size,
        )
        save_path = save_results(
            img_path,
            args.out_folder,
            prompt,
            restored,
            args.save_dtsprompt,
            args.strength,
        )
        print(f"Saved: {save_path}")


def get_args():
    parser = argparse.ArgumentParser(description="Run DocRes appearance restoration.")
    parser.add_argument(
        "--model_path",
        type=str,
        default="./checkpoints/docres.pkl",
        help="Path to the DocRes checkpoint.",
    )
    parser.add_argument("--im_path", type=str, required=True, help="Input image file or folder.")
    parser.add_argument(
        "--out_folder",
        type=str,
        default="./restored/",
        help="Folder for restored output images.",
    )
    parser.add_argument(
        "--save_dtsprompt",
        type=int,
        default=0,
        help="Set to 1 to save the three appearance prompt channels.",
    )
    parser.add_argument(
        "--device",
        choices=["auto", "cuda", "mps", "cpu"],
        default="auto",
        help="Inference device. auto uses CUDA, then MPS, then CPU.",
    )
    parser.add_argument(
        "--precision",
        choices=["auto", "fp16", "fp32"],
        default="auto",
        help="Inference precision. auto uses fp16 on CUDA/MPS and fp32 on CPU.",
    )
    parser.add_argument(
        "--max_size",
        type=int,
        default=1280,
        help="Square model input size for oversized images. Set to 0 for full-resolution model inference.",
    )
    parser.add_argument(
        "--prompt_size",
        type=int,
        default=1024,
        help="Square size for appearance prompt calculation. Set to 0 to use the full input size.",
    )
    parser.add_argument(
        "--strength",
        type=float,
        default=1.0,
        help="Blend amount for the restored result, where 1 keeps the full restoration and 0 keeps the original.",
    )
    parser.add_argument(
        "--space_api",
        action="store_true",
        help="Run inference through the Hugging Face Space API instead of loading the model locally.",
    )
    parser.add_argument(
        "--space_id",
        type=str,
        default=DEFAULT_SPACE_ID,
        help="Hugging Face Space ID to use with --space_api.",
    )
    parser.add_argument(
        "--hf_token",
        type=str,
        default=os.getenv("HF_TOKEN"),
        help="Optional Hugging Face token for private Spaces. Defaults to HF_TOKEN.",
    )
    args = parser.parse_args()
    if args.max_size is not None and args.max_size < 0:
        parser.error("--max_size must be non-negative")
    if args.prompt_size is not None and args.prompt_size < 0:
        parser.error("--prompt_size must be non-negative")
    if not 0.0 <= args.strength <= 1.0:
        parser.error("--strength must be between 0 and 1")
    if args.space_api and args.save_dtsprompt:
        parser.error(
            "--save_dtsprompt is not supported with --space_api because "
            "the Space API returns only the restored image"
        )
    return args


def main():
    args = get_args()
    if args.space_api:
        run_space_api(args)
    else:
        run_local(args)


if __name__ == "__main__":
    main()