Skip to content

Instantly share code, notes, and snippets.

@m4rc1e
Created April 14, 2023 10:08
Show Gist options
  • Save m4rc1e/bc8c5582abd9e99f1052b4574d31f587 to your computer and use it in GitHub Desktop.
Save m4rc1e/bc8c5582abd9e99f1052b4574d31f587 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}")
@twardoch
Copy link

The above is optimized a bit for execution, and also only takes the intersection of the two fonts’ cmaps minus a disallowed set (plus nbspace which we don’t test for)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment