From a2cc56200c61a78b205200842a8989315b6ff187 Mon Sep 17 00:00:00 2001 From: moosecrap Date: Thu, 23 Jul 2026 02:22:30 -0700 Subject: [PATCH] Fix token rounding --- tools/preview_image.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/tools/preview_image.py b/tools/preview_image.py index 283ad0c..7629ccc 100644 --- a/tools/preview_image.py +++ b/tools/preview_image.py @@ -39,30 +39,31 @@ def parse_indices(indices_str: str) -> List[int]: def calculate_patch_dimensions(orig_w: int, orig_h: int, target_tokens: int = 70): """ Calculates optimal pixel dimensions to hit a token budget of at least target_tokens. - The algorithm tries anchoring both Width and Height to find the smallest patch - count that satisfies the target while preserving aspect ratio. + Validates budget based on actual rounded pixel dimensions to avoid float precision errors. """ ar = orig_w / orig_h # Case A: Width is the anchor (non-padded) w_anchor = 1 while True: - w = w_anchor * 48 - h = w / ar - hp = math.ceil(h / 48) - if w_anchor * hp >= target_tokens: - res_a = {"w": w, "h": round(h), "tokens": w_anchor * hp} + w_px = w_anchor * 48 + h_px = round(w_px / ar) + # Calculate actual tokens based on resulting pixel dimensions + tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48) + if tokens >= target_tokens: + res_a = {"w": w_px, "h": h_px, "tokens": tokens} break w_anchor += 1 # Case B: Height is the anchor (non-padded) h_anchor = 1 while True: - h = h_anchor * 48 - w = h * ar - wp = math.ceil(w / 48) - if h_anchor * wp >= target_tokens: - res_b = {"w": round(w), "h": h, "tokens": h_anchor * wp} + h_px = h_anchor * 48 + w_px = round(h_px * ar) + # Calculate actual tokens based on resulting pixel dimensions + tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48) + if tokens >= target_tokens: + res_b = {"w": w_px, "h": h_px, "tokens": tokens} break h_anchor += 1