Skip to content

Instantly share code, notes, and snippets.

@eliheuer
Forked from m4rc1e/metrics_compatible.py
Created August 10, 2023 16:05
Show Gist options
  • Save eliheuer/ca7c88cc753e29630e88582af7be84a9 to your computer and use it in GitHub Desktop.
Save eliheuer/ca7c88cc753e29630e88582af7be84a9 to your computer and use it in GitHub Desktop.
Check whether two fonts are metrics compatible by testing on random strings
import random
import string
import uharfbuzz as hb
import sys
from fontTools.ttLib import TTFont
def generate_random_string(fp):
f = TTFont(fp)
cmap = f.getBestCmap()
length = random.randint(3, 100)
letters = [chr(c) for c in cmap]
return ''.join(random.choice(letters) for i in range(length))
def string_length(fp, text):
# Create a font object using a TrueType font file
blob = hb.Blob.from_file_path(fp)
face = hb.Face(blob)
font = hb.Font(face)
# Set the string to be rendered
buf = hb.Buffer()
buf.add_str(text)
buf.guess_segment_properties()
hb.shape(font, buf)
pos = buf.glyph_positions
return sum(g.x_advance for g in pos)
while True:
rand_string = generate_random_string(sys.argv[1])
original_length = string_length(sys.argv[1], rand_string)
new_length = string_length(sys.argv[2], rand_string)
if original_length != new_length:
print(f"{rand_string}, {original_length}, {new_length}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment