Seth Thompson
add strength parameter
fe07779
Raw History Blame Contribute Delete
8.15 kB
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()