Fix token rounding
This commit is contained in:
parent
77a88c093d
commit
a2cc56200c
@ -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):
|
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.
|
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
|
Validates budget based on actual rounded pixel dimensions to avoid float precision errors.
|
||||||
count that satisfies the target while preserving aspect ratio.
|
|
||||||
"""
|
"""
|
||||||
ar = orig_w / orig_h
|
ar = orig_w / orig_h
|
||||||
|
|
||||||
# Case A: Width is the anchor (non-padded)
|
# Case A: Width is the anchor (non-padded)
|
||||||
w_anchor = 1
|
w_anchor = 1
|
||||||
while True:
|
while True:
|
||||||
w = w_anchor * 48
|
w_px = w_anchor * 48
|
||||||
h = w / ar
|
h_px = round(w_px / ar)
|
||||||
hp = math.ceil(h / 48)
|
# Calculate actual tokens based on resulting pixel dimensions
|
||||||
if w_anchor * hp >= target_tokens:
|
tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48)
|
||||||
res_a = {"w": w, "h": round(h), "tokens": w_anchor * hp}
|
if tokens >= target_tokens:
|
||||||
|
res_a = {"w": w_px, "h": h_px, "tokens": tokens}
|
||||||
break
|
break
|
||||||
w_anchor += 1
|
w_anchor += 1
|
||||||
|
|
||||||
# Case B: Height is the anchor (non-padded)
|
# Case B: Height is the anchor (non-padded)
|
||||||
h_anchor = 1
|
h_anchor = 1
|
||||||
while True:
|
while True:
|
||||||
h = h_anchor * 48
|
h_px = h_anchor * 48
|
||||||
w = h * ar
|
w_px = round(h_px * ar)
|
||||||
wp = math.ceil(w / 48)
|
# Calculate actual tokens based on resulting pixel dimensions
|
||||||
if h_anchor * wp >= target_tokens:
|
tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48)
|
||||||
res_b = {"w": round(w), "h": h, "tokens": h_anchor * wp}
|
if tokens >= target_tokens:
|
||||||
|
res_b = {"w": w_px, "h": h_px, "tokens": tokens}
|
||||||
break
|
break
|
||||||
h_anchor += 1
|
h_anchor += 1
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user