colorization / app.py
0xarchit's picture
Update app.py
6b899d0 verified
Raw History Blame Contribute Delete
4.37 kB
import logging
import time
import random
import os
from pathlib import Path
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
import gradio as gr
import numpy as np
import torch
import torch.nn.functional as F
from kornia.color import lab_to_rgb, rgb_to_lab
from PIL import Image, ImageOps
from safetensors.torch import load_file
from model import UNet
ROOT = Path(__file__).resolve().parent
IMAGE_SIZE = 224
MAX_PIXELS = 12_000_000
torch.set_num_threads(min(4, os.cpu_count() or 1))
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
MODEL = UNet().cpu().eval()
MODEL.load_state_dict(load_file(str(ROOT / "weights/model.safetensors"), device="cpu"), strict=True)
logging.info("Colorization model loaded on CPU.")
@torch.inference_mode()
def colorize(image: Image.Image | None) -> Image.Image:
if image is None:
raise gr.Error("Upload a photo first.")
time.sleep(random.uniform(4, 10))
if image.width * image.height > MAX_PIXELS:
raise gr.Error("Please resize your photo to 12 megapixels or smaller.")
image = ImageOps.exif_transpose(image)
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
rgba = image.convert("RGBA")
background = Image.new("RGBA", rgba.size, "white")
image = Image.alpha_composite(background, rgba)
image = image.convert("RGB")
width, height = image.size
rgb = torch.from_numpy(np.array(image, copy=True)).permute(2, 0, 1).unsqueeze(0).float() / 255
luminance = rgb_to_lab(rgb)[:, :1]
resized = ImageOps.contain(image, (IMAGE_SIZE, IMAGE_SIZE), Image.Resampling.LANCZOS)
small_rgb = torch.from_numpy(np.array(resized, copy=True)).permute(2, 0, 1).unsqueeze(0).float() / 255
small_luminance = (rgb_to_lab(small_rgb)[:, :1] / 100).clamp(0, 1)
pad_width, pad_height = IMAGE_SIZE - resized.width, IMAGE_SIZE - resized.height
left, top = pad_width // 2, pad_height // 2
model_input = F.pad(small_luminance, (left, pad_width - left, top, pad_height - top), mode="replicate")
prediction = MODEL(model_input)
prediction = prediction[:, :, top:top + resized.height, left:left + resized.width]
ab = (prediction.float() + 1) * 127.5 - 128
ab = F.interpolate(ab, size=(height, width), mode="bilinear", align_corners=False)
result = lab_to_rgb(torch.cat([luminance, ab.clamp(-128, 127)], dim=1))
if not torch.isfinite(result).all():
raise gr.Error("This photo could not be processed. Please try another image.")
pixels = (result[0].permute(1, 2, 0).clamp(0, 1).numpy() * 255).round().astype(np.uint8)
return Image.fromarray(pixels)
with gr.Blocks(title="Colorization", analytics_enabled=False, delete_cache=(3600, 3600)) as demo:
gr.Markdown("# Colorization\nBring color to a black-and-white photo. Upload an image, then choose **Colorize**.")
with gr.Row():
source = gr.Image(type="pil", image_mode=None, sources=["upload"], label="Your photo", height=360)
result = gr.Image(type="pil", label="Colorized photo", interactive=False, format="png", height=360,
buttons=["download", "fullscreen"])
with gr.Row():
submit = gr.Button("Colorize", variant="primary")
gr.ClearButton([source, result], value="Clear")
gr.Examples(
examples=[[str(ROOT / "examples" / name)] for name in
["bear.jpg", "bedroom.jpg", "street-sign.jpg", "teddy-bears.jpg", "skier.jpg"]],
inputs=source, label="Try a black-and-white example", examples_per_page=5, cache_examples=False,
)
gr.Markdown("Colors are predicted and may differ from the original scene. Download your result using the button above the photo.")
source.change(lambda: None, inputs=None, outputs=result, queue=False, api_name=False)
submit.click(colorize, inputs=source, outputs=result, api_name="colorize", concurrency_limit=1)
demo.queue(max_size=16, default_concurrency_limit=1)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=int(os.environ.get("PORT", "7860")),
max_file_size="20mb",
theme=gr.themes.Default(primary_hue="teal", font=["system-ui", "Arial", "sans-serif"]),
css=".gradio-container { max-width: 960px !important; margin: 0 auto; }",
footer_links=[],
blocked_paths=[str(ROOT / "weights")],
)