[Python] Fonts Made from Python with NanoEmoji Only Create Letters G-Z and Are Different...

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a python script that is meant to create color fonts with nanoemoji. However, it only creates the letters G-Z (sometimes it shows E-Z correctly) correctly and they are different in Chrome and Firefox. Here is a screenshot of the one in Firefox and the one in Chrome. I have checked that the SVG files are not misconfigured or anything and even tested the images for the letters that don't show up for other lettesr and they show up there just fine. But nothing ever seems to show up for the letters A-F (sometimes just A-D).

    I read my files from a CSV file that matches with the letters. I also tried adding a textfile that maps the letters with their unicode, but that didn't help. Here is the script:

    import os
    import shutil
    import pandas as pd
    import subprocess

    # === CONFIGURATION ===
    csv_path = r"C:\pathtocsv.csv"
    build_dir = "build"
    output_dir = r"directory"

    def parse_csv(csv_path):
    df = pd.read_csv(csv_path, header=0)
    font_name = df.iloc[0, 0].strip()
    char_map = {}
    for col in df.columns[1:]:
    char = col.strip()
    if len(char) == 1 and char.isalpha() and char.isupper():
    svg_path = df[col].iloc[0]
    if pd.notna(svg_path) and svg_path.strip():
    cleaned_path = svg_path.strip()
    if os.path.exists(cleaned_path):
    char_map[char] = cleaned_path
    else:
    print(f"❌ File not found for '{char}': {cleaned_path}")
    return font_name, char_map


    def copy_svgs_to_build(char_map):
    os.makedirs(build_dir, exist_ok=True)
    svg_files = []
    debug_map = {}
    for char, src_path in char_map.items():
    hex_code = f"u{ord(char):04X}"
    dest_name = f"{hex_code}-{char}.svg"
    dest_path = os.path.join(build_dir, dest_name)
    shutil.copyfile(src_path, dest_path)
    svg_files.append(dest_path)
    debug_map[char] = src_path # ✅ Log the original file path for the letter
    print(f"✅ {char} → {dest_path}")
    return svg_files, debug_map



    def write_toml(font_name):
    toml_path = os.path.join(build_dir, f"{font_name}.toml")
    with open(toml_path, "w", encoding="utf-8") as f:
    f.write("[build]\n")
    f.write(f'family = "{font_name}"\n')
    f.write('output_format = "woff2"\n') # <- Export WOFF2
    f.write('color_format = "glyf_colr_1"\n') # <- Keep color in WOFF2
    f.write('reuse_tolerance = 0\n')
    # Do NOT add 'add_svg_table = true' for COLRv1
    return toml_path





    def build_font(font_name, svg_files, toml_path, debug_map):
    output_file = os.path.join(output_dir, f"{font_name}.otf")
    glyphmap_path = r"pathtoglyphmap.txt"
    os.makedirs(output_dir, exist_ok=True)

    # Show mapping from Unicode → original CSV path
    print("\n Glyphmap Assignments from CSV:")
    with open(glyphmap_path, "r", encoding="utf-8") as f:
    for line in f:
    parts = line.strip().split()
    if len(parts) == 2:
    codepoint, _ = parts
    path = debug_map.get(codepoint.upper())
    if path:
    print(f"️ {codepoint} → {path}")
    else:
    print(f"⚠️ {codepoint} → (No path found!)")

    # Run Nanoemoji
    cmd = [
    "nanoemoji",
    "--config_file", toml_path,
    "--glyphmap_file", glyphmap_path,
    "--output_file", output_file
    ] + svg_files

    subprocess.run(cmd, check=True)

    # Optional post-process
    maxcolor_cmd = ["maximum_color", output_file]
    subprocess.run(maxcolor_cmd, check=True)

    print(f" Post-processed with maximum_color: {output_file}")



    def main():
    print(" Reading CSV and preparing files...")
    font_name, char_map = parse_csv(csv_path)

    print(f" Building font: {font_name}")
    svg_files, debug_map = copy_svgs_to_build(char_map)

    toml_path = write_toml(font_name)

    print("\n Debug mapping report:")
    for char, original_path in debug_map.items():
    print(f" Letter {char} uses file: {original_path}")

    print("️ Starting build with nanoemoji...")
    build_font(font_name, svg_files, toml_path, debug_map)

    print("✅ Font build complete!")



    if __name__ == "__main__":
    main()

    Continue reading...

Compartilhe esta Página