import os
from pathlib import Path
import gradio as gr
import numpy as np
import torch
from huggingface_hub import hf_hub_download
try:
import spaces
except ImportError:
class _SpacesFallback:
@staticmethod
def GPU(*args, **kwargs):
if args and callable(args[0]) and len(args) == 1 and not kwargs:
return args[0]
def decorator(fn):
return fn
return decorator
spaces = _SpacesFallback()
from inference import (
blend_with_original,
load_model,
normalize_positive_int,
restore_appearance_array,
select_device,
)
MODEL_REPO_ID = os.getenv("DOCRES_MODEL_REPO_ID", "qubvel-hf/documents-restoration")
MODEL_REPO_TYPE = os.getenv("DOCRES_MODEL_REPO_TYPE", "space")
MODEL_FILENAME = os.getenv("DOCRES_MODEL_FILENAME", "checkpoints/docres.pkl")
MODEL_PATH = os.getenv("DOCRES_MODEL_PATH", MODEL_FILENAME)
DEVICE = select_device(os.getenv("DOCRES_DEVICE", "auto"))
PRECISION = os.getenv("DOCRES_PRECISION", "auto")
HEADER = """
"""
def resolve_model_path():
local_path = Path(MODEL_PATH)
if local_path.exists():
return str(local_path)
return hf_hub_download(
repo_id=MODEL_REPO_ID,
filename=MODEL_FILENAME,
repo_type=MODEL_REPO_TYPE,
)
MODEL = load_model(resolve_model_path(), DEVICE, PRECISION)
@spaces.GPU(duration=60)
def run_appearance(image, max_size, prompt_size, strength):
if image is None:
raise gr.Error("Upload a document image first.")
bgr_image = image[..., ::-1].copy()
_, bgr_restored = restore_appearance_array(
MODEL,
bgr_image,
DEVICE,
PRECISION,
max_size=normalize_positive_int(max_size),
prompt_size=normalize_positive_int(prompt_size),
)
bgr_restored = blend_with_original(bgr_image, bgr_restored, strength)
return np.ascontiguousarray(bgr_restored[..., ::-1])
with gr.Blocks() as demo:
gr.Markdown(HEADER)
with gr.Row():
input_image = gr.Image(label="Input", type="numpy")
output_image = gr.Image(label="Restored Appearance", type="numpy")
with gr.Accordion("Advanced", open=False):
max_size = gr.Slider(
label="Model correction size",
minimum=0,
maximum=4096,
step=64,
value=1280,
info="1280 keeps inference bounded while preserving the original output size. 0 runs the model at the full input size.",
)
prompt_size = gr.Slider(
label="Appearance prompt size",
minimum=0,
maximum=4096,
step=64,
value=1024,
info="1024 gives a stable appearance estimate. 0 uses the full input size.",
)
strength = gr.Slider(
label="Restoration strength",
minimum=0,
maximum=1,
step=0.01,
value=1,
info="1 applies the full restoration. Lower values blend more of the original image back in.",
)
button = gr.Button("Run", variant="primary")
button.click(
run_appearance,
inputs=[input_image, max_size, prompt_size, strength],
outputs=output_image,
api_name="predict",
)
if __name__ == "__main__":
demo.queue().launch()