yappertar4's picture
add Python source: model, tokenizer, checkpoint, data, train, train_more, infer + config
dfeab58 verified
Raw History Blame Contribute Delete
3.04 kB
import argparse
from typing import Optional
import numpy as np
import torch
from PIL import Image
from checkpoint import MODEL_DIR, load_bundle
from model import DigitGPT
from tokenizer import DigitTokenizer
def preprocess_image(image_path: str, img_h: int, img_w: int) -> torch.Tensor:
arr = np.asarray(Image.open(image_path).convert("L"), dtype=np.float32)
h, w = arr.shape
scale = min(img_h / h, img_w / w)
new_h, new_w = max(1, round(h * scale)), max(1, round(w * scale))
if (new_h, new_w) != (h, w):
resample = Image.LANCZOS if scale < 1.0 else Image.BICUBIC
arr = np.asarray(
Image.fromarray(arr.astype(np.uint8)).resize((new_w, new_h), resample), dtype=np.float32
)
canvas = np.zeros((img_h, img_w), dtype=np.float32)
top = (img_h - new_h) // 2
canvas[top : top + new_h, 0:new_w] = arr / 255.0
return torch.from_numpy(canvas).unsqueeze(0).unsqueeze(0)
def predict_tensor(
model: DigitGPT,
tokenizer: DigitTokenizer,
image: torch.Tensor,
device: torch.device,
max_digits: int,
max_len: Optional[int] = None,
temperature: float = 1.0,
greedy: bool = True,
) -> str:
with torch.no_grad():
seq = model.generate(
image.to(device),
max_len=max_len or (max_digits + 1),
temperature=temperature,
greedy=greedy,
)
return tokenizer.decode(seq[0].tolist()) or "?"
def main():
parser = argparse.ArgumentParser(description="Predict digits from an image using ./model")
parser.add_argument("image", help="path to image (any size, will be resized)")
parser.add_argument("-m", "--model-dir", default=MODEL_DIR, help=f"model bundle dir (default: {MODEL_DIR})")
parser.add_argument("--device", default="cpu")
parser.add_argument("--temperature", type=float, default=None, help="override generation temperature")
parser.add_argument("--sampling", action="store_true", help="sample instead of greedy decode")
parser.add_argument("--show-input", action="store_true", help="save the preprocessed 28x140 tensor as png")
args = parser.parse_args()
model, tokenizer, manifest = load_bundle(args.model_dir, device=args.device)
data, generation = manifest["data"], manifest.get("generation", {})
tensor = preprocess_image(args.image, data["img_h"], data["img_w"])
if args.show_input:
Image.fromarray((tensor[0, 0].numpy() * 255).astype(np.uint8)).save("preprocessed.png")
print(f"preprocessed.png ({data['img_h']}x{data['img_w']})")
temperature = args.temperature if args.temperature is not None else float(generation.get("temperature", 1.0))
pred = predict_tensor(
model,
tokenizer,
tensor,
torch.device(args.device),
max_digits=data["max_digits"],
max_len=generation.get("max_len"),
temperature=temperature,
greedy=not args.sampling and bool(generation.get("greedy", True)),
)
print(pred)
if __name__ == "__main__":
main()