import os import re # Directory with the font files directory = './' # Get list of font files font_files = os.listdir(directory) # Initialize an empty list for the typefaces typefaces = [] # Loop over the font files for file in font_files: # Strip the file extension name_weight, extension = os.path.splitext(file) # Only process .ttf, .otf, .woff and .woff2 files if extension.lower() not in ['.ttf', '.otf', '.woff', '.woff2']: continue # Split the name and weight match = re.match(r'(.*)_(\d+)(I)?', name_weight) if match: name, weight, is_italic = match.groups() else: name = name_weight weight = "400" is_italic = None # Check if the typeface is already in the list for typeface in typefaces: if typeface['name'] == name: break else: # If the typeface is not in the list, add a new one typeface = { "name": name, "fonts" : [], "tags" : ["sans-serif"], } typefaces.append(typeface) font_descriptor = weight + ('i' if is_italic else '') typeface['fonts'].append(font_descriptor) # Convert the typefaces list to a JavaScript object string typefaces_js = '[\n' + ',\n'.join( f' {typeface["name"].lower()} : ' + '{\n' + f' "name": "{typeface["name"]}",\n' + ' "fonts" : [\n' + ',\n'.join( f' "{font_descriptor}"' for font_descriptor in typeface['fonts'] ) + '\n ],\n' + ' "tags" : ["sans-serif"],\n' + ' "link" : "",\n' + ' }' for typeface in typefaces ) + '\n]' # Write the JavaScript string to a .js file with open('00_typefaces.js', 'w') as f: f.write('var typeFaces = ' + typefaces_js + ';')