Spaces:
Running on Zero
Running on Zero
| # -*- coding: utf-8 -*- | |
| import os, io, re, random, string, tempfile | |
| import spaces | |
| import gradio as gr | |
| from gradio import Server | |
| from gradio.data_classes import FileData | |
| from fastapi.responses import HTMLResponse | |
| from PIL import Image | |
| # --- CONSTANTS --- | |
| POTRACE_BIN = 'potrace' | |
| UPM = 1000 | |
| CROP = 8 | |
| SIDEBEARING = 20 | |
| GLYPH_SCALE = 0.112 | |
| PRECISION = 1 | |
| HF_TOKEN = os.environ.get("HF_TOKEN", "") | |
| DEFAULT_IMG_PROMPT = "Design a custom typeface that takes direct inspiration on the attached control image. The font should faithfully replicate the unique style of the reference." | |
| # --- 6x6 MAPPINGS --- | |
| MAP_UC = [['A','B','C','D','E','F'],['G','H','I','J','K','L'],['M','N','O','P','Q','R'],['S','T','U','V','W','X'],['Y','Z','Æ','Œ','Ø','ß'],['Ç','.',',',';','?','!']] | |
| MAP_LC = [['a','b','c','d','e','f'],['g','h','i','j','k','l'],['m','n','o','p','q','r'],['s','t','u','v','w','x'],['y','z','æ','œ','ø','Ð'],['ç',':',"'",'"','«','<']] | |
| MAP_PUNC = [['1','2','3','4','5','6'],['7','8','9','0','#','%'],['(','[','{','$','€','£'],['&','@','_','+','-','='],['*','/','^','°','→','—'],['`','´','ˆ','¨','˜','•']] | |
| # --- PER-GRID BASELINE REFERENCES --- | |
| BASELINE_REFS = { | |
| 0: ['H', 'I', 'E', 'A', 'B', 'D', 'F', 'L', 'M', 'N', 'P', 'R', 'T', 'U', 'V', 'X', 'Y', 'Z'], | |
| 1: ['n', 'm', 'u', 'x', 'h', 'i', 'l', 'k', 'r', 'v', 'w', 'z', 'a', 'e', 'o'], | |
| 2: ['1', '0', '2', '4', '7', '8', '9', '#', '%', '$', '£', '&', '@', '+', '='], | |
| } | |
| # --- SVG PROCESSING --- | |
| def simplify_svg_path(d): | |
| from fontTools.pens.recordingPen import RecordingPen | |
| from fontTools.pens.svgPathPen import SVGPathPen | |
| from fontTools.svgLib.path import parse_path | |
| rec = RecordingPen() | |
| parse_path(d, rec) | |
| svg = SVGPathPen(None) | |
| rec.replay(svg) | |
| return re.sub(r"(\d+\.\d+)", lambda m: f"{float(m.group(1)):.{PRECISION}f}", svg.getCommands()) | |
| def get_char_path_rdp(pil_img, upscale=2): | |
| import tempfile, subprocess | |
| import cv2, numpy as np | |
| rgb = np.array(pil_img.convert("RGB")) | |
| black_mask = ( | |
| (rgb[:,:,0] < 80) & | |
| (rgb[:,:,1] < 80) & | |
| (rgb[:,:,2] < 80) | |
| ).astype(np.uint8) * 255 | |
| h, w = black_mask.shape | |
| up = cv2.resize(black_mask, (w*upscale, h*upscale), interpolation=cv2.INTER_NEAREST) | |
| with tempfile.NamedTemporaryFile(suffix='.pbm', delete=False) as f: | |
| pbm = f.name | |
| with tempfile.NamedTemporaryFile(suffix='.svg', delete=False) as f: | |
| svg = f.name | |
| Image.fromarray(cv2.flip(255-up, 0)).convert('1').save(pbm) | |
| try: | |
| subprocess.run([POTRACE_BIN, pbm, '-s', '-o', svg, '--alphamax', '0.9', '--opttolerance', '0.5', '--turdsize', '30'], check=True, capture_output=True) | |
| except: | |
| return "" | |
| finally: | |
| if os.path.exists(pbm): | |
| os.unlink(pbm) | |
| if not os.path.exists(svg): | |
| return "" | |
| with open(svg) as f: | |
| content = f.read() | |
| os.unlink(svg) | |
| paths = re.findall(r'd="([^"]+)"', content) | |
| return ' '.join(simplify_svg_path(p) for p in paths).strip() if paths else "" | |
| # --- OTF CONSTRUCTION --- | |
| MIRROR_MAP = {')': '(', ']': '[', '}': '{'} | |
| ACCENT_MAP = { | |
| 'à':('a','`'),'è':('e','`'),'ì':('i','`'),'ò':('o','`'),'ù':('u','`'), | |
| 'À':('A','`'),'È':('E','`'),'Ì':('I','`'),'Ò':('O','`'),'Ù':('U','`'), | |
| 'á':('a','´'),'é':('e','´'),'í':('i','´'),'ó':('o','´'),'ú':('u','´'), | |
| 'Á':('A','´'),'É':('E','´'),'Í':('I','´'),'Ó':('O','´'),'Ú':('U','´'), | |
| 'â':('a','ˆ'),'ê':('e','ˆ'),'î':('i','ˆ'),'ô':('o','ˆ'),'û':('u','ˆ'), | |
| 'Â':('A','ˆ'),'Ê':('E','ˆ'),'Î':('I','ˆ'),'Ô':('O','ˆ'),'Û':('U','ˆ'), | |
| 'ä':('a','¨'),'ë':('e','¨'),'ï':('i','¨'),'ö':('o','¨'),'ü':('u','¨'), | |
| 'Ä':('A','¨'),'Ë':('E','¨'),'Ï':('I','¨'),'Ö':('O','¨'),'Ü':('U','¨'), | |
| 'ã':('a','˜'),'õ':('o','˜'),'ñ':('n','˜'), | |
| 'Ã':('A','˜'),'Õ':('O','˜'),'Ñ':('N','˜'), | |
| } | |
| def build_otf(images, font_name): | |
| from fontTools.fontBuilder import FontBuilder | |
| from fontTools.pens.t2CharStringPen import T2CharStringPen | |
| from fontTools.pens.boundsPen import BoundsPen | |
| from fontTools.pens.transformPen import TransformPen | |
| from fontTools.pens.recordingPen import RecordingPen | |
| from fontTools.misc.transform import Identity | |
| from fontTools.svgLib.path import parse_path | |
| from fontTools.cffLib import PrivateDict | |
| from fontTools.ttLib import newTable | |
| from fontTools.ttLib.tables import _k_e_r_n as _kern | |
| import tempfile, subprocess, cv2, numpy as np | |
| from PIL import Image, ImageDraw | |
| all_maps = [MAP_UC, MAP_LC, MAP_PUNC] | |
| glyph_data = {} | |
| for idx, img in enumerate(images): | |
| w, h = img.size | |
| arr = np.array(img.convert("RGB")) | |
| arr_up = cv2.resize(arr, (w*2, h*2), interpolation=cv2.INTER_CUBIC) | |
| img_up = Image.fromarray(arr_up) | |
| w2, h2 = img_up.size | |
| cw, ch = w2//6, h2//6 | |
| scale = 800/ch | |
| current_map = all_maps[idx] | |
| for r in range(6): | |
| for c in range(6): | |
| char = current_map[r][c] | |
| box = (c*cw, r*ch, (c+1)*cw, (r+1)*ch) | |
| d = get_char_path_rdp(img_up.crop(box), upscale=1) | |
| if not d: | |
| continue | |
| bp = BoundsPen(None) | |
| try: | |
| parse_path(d, bp) | |
| except: | |
| continue | |
| if bp.bounds: | |
| glyph_data[char] = {'d': d, 'b': bp.bounds, 'scale': scale, 'grid': idx} | |
| # Computed baseline | |
| baseline_per_grid = {} | |
| for grid_idx in range(len(all_maps)): | |
| chosen_ref = None | |
| for ref_char in BASELINE_REFS.get(grid_idx, []): | |
| if ref_char in glyph_data and glyph_data[ref_char].get('grid') == grid_idx: | |
| gd = glyph_data[ref_char] | |
| baseline_per_grid[grid_idx] = gd['b'][3] * gd['scale'] * GLYPH_SCALE | |
| chosen_ref = ref_char | |
| break | |
| if chosen_ref is None: | |
| baseline_per_grid[grid_idx] = baseline_per_grid.get(0, 0) | |
| print(f"⚠️ Grid {grid_idx}: no reference glyph found, fallback = {baseline_per_grid[grid_idx]:.1f}") | |
| else: | |
| print(f"📐 Grid {grid_idx}: baseline = {baseline_per_grid[grid_idx]:.1f} (ref '{chosen_ref}')") | |
| def get_baseline(char): | |
| if char in glyph_data: | |
| return baseline_per_grid.get(glyph_data[char]['grid'], baseline_per_grid.get(0, 0)) | |
| return baseline_per_grid.get(0, 0) | |
| dummy = PrivateDict() | |
| dummy.nominalWidthX = 0 | |
| cs = {".notdef": T2CharStringPen(600, None).getCharString(private=dummy)} | |
| metrics = {".notdef": (600, 0)} | |
| cmap, order = {}, [".notdef"] | |
| cs["space"] = T2CharStringPen(300, None).getCharString(private=dummy) | |
| metrics["space"] = (300, 0) | |
| order.append("space") | |
| cmap[32] = "space" | |
| font_recordings = {} | |
| font_bounds = {} | |
| font_widths = {} | |
| font_centers = {} | |
| for char, data in glyph_data.items(): | |
| if len(char) != 1: | |
| continue | |
| b, s = data['b'], data['scale'] | |
| width = round((b[2]-b[0]) * s * GLYPH_SCALE + SIDEBEARING * 2) | |
| tx = SIDEBEARING - b[0] * s * GLYPH_SCALE | |
| ty = get_baseline(char) | |
| transform = Identity.translate(tx, ty).scale(s * GLYPH_SCALE, -s * GLYPH_SCALE) | |
| rec = RecordingPen() | |
| parse_path(data['d'], TransformPen(rec, transform)) | |
| font_recordings[char] = rec.value | |
| font_widths[char] = width | |
| bp2 = BoundsPen(None) | |
| rec2 = RecordingPen() | |
| rec2.value = rec.value | |
| rec2.replay(bp2) | |
| bounds = bp2.bounds or (0, 0, width, 800) | |
| font_bounds[char] = bounds | |
| font_centers[char] = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) | |
| pen = T2CharStringPen(width, None) | |
| rec3 = RecordingPen() | |
| rec3.value = rec.value | |
| rec3.replay(pen) | |
| glyph_name = f"glyph{ord(char)}" | |
| cs[glyph_name] = pen.getCharString(private=dummy) | |
| order.append(glyph_name) | |
| cmap[ord(char)] = glyph_name | |
| metrics[glyph_name] = (width, 0) | |
| # Mirrors | |
| for dst_char, src_char in MIRROR_MAP.items(): | |
| if src_char not in font_recordings: | |
| continue | |
| w = font_widths[src_char] | |
| pen = T2CharStringPen(w, None) | |
| flip = TransformPen(pen, (-1, 0, 0, 1, w, 0)) | |
| rec = RecordingPen() | |
| rec.value = font_recordings[src_char] | |
| rec.replay(flip) | |
| gn = f"glyph{ord(dst_char)}" | |
| cs[gn] = pen.getCharString(private=dummy) | |
| order.append(gn) | |
| cmap[ord(dst_char)] = gn | |
| metrics[gn] = (w, 0) | |
| if src_char in font_centers: | |
| cx, cy = font_centers[src_char] | |
| font_centers[dst_char] = (w - cx, cy) | |
| # Accented | |
| for dst_char, (base_char, accent_char) in ACCENT_MAP.items(): | |
| if base_char not in font_recordings or accent_char not in font_recordings: | |
| continue | |
| w = font_widths[base_char] | |
| bb = font_bounds[base_char] | |
| ab = font_bounds[accent_char] | |
| dx = ((bb[0]+bb[2]) - (ab[0]+ab[2])) / 2 | |
| dy = bb[3] - ab[1] + 40 | |
| pen = T2CharStringPen(w, None) | |
| rec1 = RecordingPen() | |
| rec1.value = font_recordings[base_char] | |
| rec1.replay(pen) | |
| rec2 = RecordingPen() | |
| rec2.value = font_recordings[accent_char] | |
| rec2.replay(TransformPen(pen, (1, 0, 0, 1, dx, dy))) | |
| gn = f"glyph{ord(dst_char)}" | |
| cs[gn] = pen.getCharString(private=dummy) | |
| order.append(gn) | |
| cmap[ord(dst_char)] = gn | |
| metrics[gn] = (w, 0) | |
| if base_char in font_centers and accent_char in font_centers: | |
| bx, by = font_centers[base_char] | |
| ax, ay = font_centers[accent_char] | |
| font_centers[dst_char] = (bx + dx, by + dy) | |
| # Bracket mirrors | |
| MIRROR_PAIRS = {'(': ')', '[': ']', '{': '}'} | |
| for src_char, dst_char in MIRROR_PAIRS.items(): | |
| if src_char not in glyph_data: | |
| continue | |
| data = glyph_data[src_char] | |
| b, s = data['b'], data['scale'] | |
| width = round((b[2]-b[0]) * s * GLYPH_SCALE + SIDEBEARING * 2) | |
| pen = T2CharStringPen(width, None) | |
| tx = SIDEBEARING + b[2] * s * GLYPH_SCALE | |
| ty = get_baseline(src_char) | |
| transform = Identity.translate(tx, ty).scale(-s * GLYPH_SCALE, -s * GLYPH_SCALE) | |
| parse_path(data['d'], TransformPen(pen, transform)) | |
| glyph_name = f"glyph{ord(dst_char)}" | |
| if glyph_name not in cs: | |
| cs[glyph_name] = pen.getCharString(private=dummy) | |
| order.append(glyph_name) | |
| cmap[ord(dst_char)] = glyph_name | |
| metrics[glyph_name] = (width, 0) | |
| if src_char in font_centers: | |
| cx, cy = font_centers[src_char] | |
| font_centers[dst_char] = (width - cx, cy) | |
| # Combining-accent aliases | |
| ACCENT_ALIASES = { | |
| '`': [0x0060, 0x0300], '´': [0x00B4, 0x0301], | |
| 'ˆ': [0x02C6, 0x0302], '¨': [0x00A8, 0x0308], '˜': [0x02DC, 0x0303], | |
| } | |
| for base_char, codepoints in ACCENT_ALIASES.items(): | |
| if base_char not in glyph_data: | |
| continue | |
| existing_glyph_name = f"glyph{ord(base_char)}" | |
| if existing_glyph_name in cs: | |
| for cp in codepoints[1:]: | |
| if cp not in cmap: | |
| cmap[cp] = existing_glyph_name | |
| fb = FontBuilder(UPM, isTTF=False) | |
| fb.setupGlyphOrder(order) | |
| fb.setupCharacterMap(cmap) | |
| fb.setupCFF( | |
| font_name, | |
| {"FullName": font_name, "FamilyName": font_name, "Weight": "Regular"}, | |
| cs, | |
| {font_name: dummy} | |
| ) | |
| fb.setupHorizontalMetrics(metrics) | |
| fb.setupHorizontalHeader(ascent=REF["asc"], descent=REF["dsc"]) | |
| fb.setupNameTable({ | |
| "familyName": font_name, | |
| "styleName": "Regular", | |
| "uniqueFontIdentifier": f"{font_name}:Version 1.000", | |
| "fullName": font_name, | |
| "version": "Version 1.000", | |
| "psName": font_name | |
| }) | |
| fb.setupOS2( | |
| sTypoAscender=REF["tAsc"], | |
| sTypoDescender=REF["tDsc"], | |
| sTypoLineGap=REF["tGap"], | |
| usWinAscent=REF["wAsc"], | |
| usWinDescent=REF["wDsc"], | |
| sxHeight=REF["xH"], | |
| sCapHeight=REF["cH"], | |
| fsType=4, | |
| fsSelection=64 | |
| ) | |
| fb.setupPost(italicAngle=0, underlinePosition=REF["ulP"], underlineThickness=REF["ulT"]) | |
| # ------------------------------------------------------------------------- | |
| # BUBBLE KERNING — pure vector, written to GPOS (no pair-count limit) | |
| # ------------------------------------------------------------------------- | |
| try: | |
| import numpy as np | |
| from fontTools.otlLib.builder import buildValue, buildPairPosGlyphs | |
| from fontTools.ttLib import newTable | |
| from fontTools.ttLib.tables import otTables | |
| # --- Parameters --- | |
| BUBBLE_RADIUS = 10 # bubble radius in UPM, must be < SIDEBEARING (20) | |
| N_SAMPLES = 300 # sampled points per contour | |
| KERN_THRESHOLD = -2 # pairs with kern >= threshold are skipped (sub-UPM noise) | |
| KERN_CAP = -280 # anti-collision floor | |
| def sample_contour(recording, n=N_SAMPLES): | |
| pts = [] | |
| def add_line(p0, p1): | |
| d = ((p1[0]-p0[0])**2 + (p1[1]-p0[1])**2) ** 0.5 | |
| steps = max(1, int(d / 8)) | |
| for i in range(steps + 1): | |
| t = i / steps | |
| pts.append((p0[0] + t*(p1[0]-p0[0]), | |
| p0[1] + t*(p1[1]-p0[1]))) | |
| def add_cubic(p0, p1, p2, p3): | |
| d = ((p3[0]-p0[0])**2 + (p3[1]-p0[1])**2) ** 0.5 | |
| steps = max(4, int(d * 1.5 / 8)) | |
| for i in range(steps + 1): | |
| t = i / steps | |
| mt = 1.0 - t | |
| bx = mt**3*p0[0] + 3*mt**2*t*p1[0] + 3*mt*t**2*p2[0] + t**3*p3[0] | |
| by = mt**3*p0[1] + 3*mt**2*t*p1[1] + 3*mt*t**2*p2[1] + t**3*p3[1] | |
| pts.append((bx, by)) | |
| cur = (0.0, 0.0) | |
| start = (0.0, 0.0) | |
| for op, args in recording: | |
| if op == 'moveTo': | |
| cur = args[0]; start = cur | |
| elif op == 'lineTo': | |
| add_line(cur, args[0]); cur = args[0] | |
| elif op == 'curveTo': | |
| add_cubic(cur, args[0], args[1], args[2]); cur = args[2] | |
| elif op in ('endPath', 'closePath'): | |
| if cur != start: | |
| add_line(cur, start) | |
| cur = start | |
| if not pts: | |
| return None | |
| arr = np.array(pts, dtype=np.float32) | |
| if len(arr) > n: | |
| idx = np.round(np.linspace(0, len(arr)-1, n)).astype(int) | |
| arr = arr[idx] | |
| return arr | |
| # Sampling | |
| chars_available = [c for c in font_recordings if len(c) == 1] | |
| contour_points = {} | |
| for char in chars_available: | |
| pts = sample_contour(font_recordings[char]) | |
| if pts is not None and len(pts) >= 2: | |
| contour_points[char] = pts | |
| print(f"📐 Contours sampled: {len(contour_points)} glyphs") | |
| # All-to-all computation | |
| diameter = BUBBLE_RADIUS * 2.0 | |
| gpos_pairs = {} # (glyph_name_L, glyph_name_R) -> kern_upm | |
| for l_char in contour_points: | |
| pts_L = contour_points[l_char] | |
| adv_L = float(font_widths[l_char]) | |
| lg = f"glyph{ord(l_char)}" | |
| if lg not in metrics: | |
| continue | |
| for r_char in contour_points: | |
| rg = f"glyph{ord(r_char)}" | |
| if rg not in metrics: | |
| continue | |
| pts_R_shifted = contour_points[r_char] + np.array([adv_L, 0.0], dtype=np.float32) | |
| diff = pts_L[:, np.newaxis, :] - pts_R_shifted[np.newaxis, :, :] | |
| min_dist = float(np.sqrt((diff**2).sum(axis=2)).min()) | |
| kern_upm = int(round(diameter - min_dist)) | |
| if l_char in ('A','V','W') and r_char in ('A','V','W'): | |
| print(f" {l_char}->{r_char} : min_dist={min_dist:.1f} kern={kern_upm}") | |
| if kern_upm < KERN_THRESHOLD: | |
| gpos_pairs[(lg, rg)] = max(kern_upm, KERN_CAP) | |
| print(f"✅ Bubble Kerning (vector): {len(gpos_pairs)} pairs") | |
| if gpos_pairs: | |
| val0 = buildValue({}) | |
| pairs_for_builder = { | |
| (lg, rg): (buildValue({"XAdvance": kern}), val0) | |
| for (lg, rg), kern in gpos_pairs.items() | |
| } | |
| glyph_map = fb.font.getReverseGlyphMap() | |
| subtables = buildPairPosGlyphs(pairs_for_builder, glyph_map) | |
| lookup = otTables.Lookup() | |
| lookup.LookupType = 2 | |
| lookup.LookupFlag = 0 | |
| lookup.SubTableCount = len(subtables) | |
| lookup.SubTable = subtables | |
| lookup_list = otTables.LookupList() | |
| lookup_list.Lookup = [lookup] | |
| lookup_list.LookupCount = 1 | |
| feature_record = otTables.FeatureRecord() | |
| feature_record.FeatureTag = "kern" | |
| feature = otTables.Feature() | |
| feature.LookupListIndex = [0] | |
| feature.LookupCount = 1 | |
| feature_record.Feature = feature | |
| lang_sys = otTables.DefaultLangSys() | |
| lang_sys.ReqFeatureIndex = 0xFFFF | |
| lang_sys.FeatureIndex = [0] | |
| lang_sys.FeatureCount = 1 | |
| lang_sys.LookupOrderOffset = 0 | |
| script = otTables.Script() | |
| script.DefaultLangSys = lang_sys | |
| script.LangSysCount = 0 | |
| script.LangSysRecord = [] | |
| script_record = otTables.ScriptRecord() | |
| script_record.ScriptTag = "DFLT" | |
| script_record.Script = script | |
| script_list = otTables.ScriptList() | |
| script_list.ScriptRecord = [script_record] | |
| script_list.ScriptCount = 1 | |
| feature_list = otTables.FeatureList() | |
| feature_list.FeatureRecord = [feature_record] | |
| feature_list.FeatureCount = 1 | |
| gpos_table = otTables.GPOS() | |
| gpos_table.Version = 0x00010000 | |
| gpos_table.ScriptList = script_list | |
| gpos_table.FeatureList = feature_list | |
| gpos_table.LookupList = lookup_list | |
| gpos = newTable("GPOS") | |
| gpos.table = gpos_table | |
| fb.font["GPOS"] = gpos | |
| print(f"✅ GPOS written: {len(gpos_pairs)} kern pairs") | |
| except Exception as e: | |
| print(f"⚠️ Bubble Kerning failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| # --- Final OTF save --- | |
| tmp_otf = f"/tmp/{font_name}.otf" | |
| fb.save(tmp_otf) | |
| with open(tmp_otf, "rb") as f: | |
| data = f.read() | |
| os.remove(tmp_otf) | |
| return data | |
| # --- REFERENCE METRICS (Helvetica LT Std Regular) --- | |
| REF = { | |
| "asc": 718, "dsc": -282, "tAsc": 718, "tDsc": -282, "tGap": 200, | |
| "wAsc": 931, "wDsc": 225, "xH": 524, "cH": 718, "ulP": -75, "ulT": 50 | |
| } | |
| # ============================================================================= | |
| # MODEL LOADING (module scope, once at Space startup) | |
| # ZeroGPU: .to("cuda") here is fine, the real CUDA init is deferred by `spaces`. | |
| # ============================================================================= | |
| import torch | |
| from diffusers import Flux2KleinPipeline | |
| from huggingface_hub import login | |
| if HF_TOKEN: | |
| login(token=HF_TOKEN) | |
| print("🚀 Loading Flux.2-klein + LoRAs ...") | |
| pipe = Flux2KleinPipeline.from_pretrained( | |
| "black-forest-labs/FLUX.2-klein-base-4B", | |
| torch_dtype=torch.bfloat16, | |
| ) | |
| pipe.load_lora_weights("ChevalierJoseph/TYPOTOPIA_APP", weight_name="typotopiaMAJ.safetensors", adapter_name="uc") | |
| pipe.load_lora_weights("ChevalierJoseph/TYPOTOPIA_APP", weight_name="typotopiaMIN.safetensors", adapter_name="lc") | |
| pipe.load_lora_weights("ChevalierJoseph/TYPOTOPIA_APP", weight_name="typotopiaPONCT.safetensors", adapter_name="punc") | |
| pipe.to("cuda") | |
| print("✅ Model ready!") | |
| # ============================================================================= | |
| # GPU INFERENCE — only the 3 FLUX passes run under @spaces.GPU | |
| # duration = max GPU allocation per request (counts against the ZeroGPU quota). | |
| # ============================================================================= | |
| def run_pipeline(enhanced, input_img, seed): | |
| gen = torch.Generator("cuda").manual_seed(int(seed)) | |
| pipe.set_adapters("uc") | |
| img1 = pipe( | |
| prompt=f"[typotopiaMAJ], {enhanced}", | |
| image=input_img, | |
| num_inference_steps=5, | |
| guidance_scale=7 if input_img else 3.5, | |
| height=1536, width=1536, | |
| generator=gen, | |
| ).images[0] | |
| pipe.set_adapters("lc") | |
| img2 = pipe( | |
| prompt="[typotopiaMIN], Design a custom lowercase typeface inspired by the attached control image.", | |
| image=img1, | |
| num_inference_steps=5, | |
| guidance_scale=7, | |
| height=1536, width=1536, | |
| generator=gen, | |
| ).images[0] | |
| pipe.set_adapters("punc") | |
| img3 = pipe( | |
| prompt="[typotopiaPONCT], Design a custom punctuation typeface inspired by the attached control image.", | |
| image=img1, | |
| num_inference_steps=5, | |
| guidance_scale=7, | |
| height=1536, width=1536, | |
| generator=gen, | |
| ).images[0] | |
| return img1, img2, img3 | |
| # ============================================================================= | |
| # PREVIEW RENDER (CPU) | |
| # ============================================================================= | |
| def _render_preview(otf_path, font_name): | |
| try: | |
| from PIL import Image, ImageDraw, ImageFont | |
| sample = f"{font_name}\nAa Bb Cc 123\nThe quick brown fox jumps over the lazy dog." | |
| font_size = 180 | |
| spacing = 36 | |
| pad = 70 | |
| font = ImageFont.truetype(otf_path, font_size) | |
| # measure first on a throwaway canvas so the text never clips | |
| meas = ImageDraw.Draw(Image.new("RGB", (10, 10))) | |
| bbox = meas.multiline_textbbox((0, 0), sample, font=font, spacing=spacing) | |
| w = (bbox[2] - bbox[0]) + pad * 2 | |
| h = (bbox[3] - bbox[1]) + pad * 2 | |
| img = Image.new("RGB", (w, h), "white") | |
| draw = ImageDraw.Draw(img) | |
| # offset by bbox origin (handles negative side-bearings / descenders) | |
| draw.multiline_text((pad - bbox[0], pad - bbox[1]), | |
| sample, font=font, fill="black", spacing=spacing) | |
| return img | |
| except Exception as e: | |
| print(f"⚠️ Preview failed: {e}") | |
| return None | |
| # ============================================================================= | |
| # OPTIONAL CUSTOM TITLE FONT | |
| # Drop your own font in the repo as one of these names and the hero wordmark | |
| # will use it (otherwise it falls back to the Helvetica/Archivo stack): | |
| # title.otf / title.ttf / title.woff2 / title.woff (or under assets/) | |
| # ============================================================================= | |
| def _load_title_font(): | |
| import base64 | |
| fmt = {"otf": "opentype", "ttf": "truetype", "woff": "woff", "woff2": "woff2"} | |
| mime = {"otf": "font/otf", "ttf": "font/ttf", "woff": "font/woff", "woff2": "font/woff2"} | |
| candidates = [ | |
| "title.otf", "title.ttf", "title.woff2", "title.woff", | |
| "assets/title.otf", "assets/title.ttf", "assets/title.woff2", "assets/title.woff", | |
| ] | |
| for path in candidates: | |
| if os.path.exists(path): | |
| ext = path.rsplit(".", 1)[-1].lower() | |
| with open(path, "rb") as fh: | |
| b64 = base64.b64encode(fh.read()).decode() | |
| print(f"🔤 Title font: {path}") | |
| face = ( | |
| "@font-face {" | |
| "font-family: 'TitleFont';" | |
| f"src: url(data:{mime[ext]};base64,{b64}) format('{fmt[ext]}');" | |
| "font-weight: 100 900; font-style: normal; font-display: swap;}" | |
| ) | |
| return face, "'TitleFont', 'Helvetica Neue', Helvetica, 'Archivo', Arial, sans-serif" | |
| return "", "'Helvetica Neue', Helvetica, 'Archivo', Arial, sans-serif" | |
| TITLE_FONT_FACE, TITLE_FAMILY = _load_title_font() | |
| # ============================================================================= | |
| # BACKEND SERVER (gradio.Server == FastAPI + Gradio's queue / ZeroGPU engine) | |
| # ============================================================================= | |
| app = Server() | |
| def generate( | |
| prompt: str = "", | |
| control_image: FileData | None = None, | |
| ) -> tuple[FileData, FileData, FileData, FileData, FileData, str]: | |
| """ | |
| Returns a positional tuple -> arrives on the JS client as result.data: | |
| data[0] uppercase grid (FileData .url) | |
| data[1] lowercase grid (FileData .url) | |
| data[2] punctuation grid (FileData .url) | |
| data[3] specimen preview (FileData .url) | |
| data[4] .otf file (FileData .url) | |
| data[5] font name (str) | |
| """ | |
| seed = random.randint(0, 2**32 - 1) | |
| input_img = None | |
| prefixes = ["Vex","Aur","Kyr","Lux","Nox","Arc","Sol","Vel","Fen","Zor","Cal","Dex","Ora","Pax","Rux"] | |
| suffixes = ["ra","is","on","us","ia","el","an","ix","em","or","al","en","ax","um","yr"] | |
| font_name = random.choice(prefixes) + random.choice(suffixes) | |
| if control_image is not None: | |
| input_img = Image.open(control_image["path"]).convert("RGB").resize((1536, 1536)) | |
| enhanced = DEFAULT_IMG_PROMPT | |
| else: | |
| if not (prompt and prompt.strip()): | |
| raise gr.Error("Provide a prompt OR a control image.") | |
| enhanced = prompt # raw user input, no refinement | |
| # --- GPU: 3 FLUX passes --- | |
| img1, img2, img3 = run_pipeline(enhanced, input_img, seed) | |
| if not font_name: | |
| font_name = "Font" + "".join(random.choices(string.ascii_uppercase, k=3)) | |
| # --- CPU: potrace vectorization + OTF build --- | |
| otf_bytes = build_otf([img1, img2, img3], font_name) | |
| out_dir = tempfile.mkdtemp() | |
| otf_path = os.path.join(out_dir, f"{font_name}.otf") | |
| with open(otf_path, "wb") as f: | |
| f.write(otf_bytes) | |
| uc_path = os.path.join(out_dir, "uppercase.png"); img1.save(uc_path) | |
| lc_path = os.path.join(out_dir, "lowercase.png"); img2.save(lc_path) | |
| pn_path = os.path.join(out_dir, "punctuation.png"); img3.save(pn_path) | |
| preview = _render_preview(otf_path, font_name) | |
| prev_path = os.path.join(out_dir, "preview.png") | |
| if preview is not None: | |
| preview.save(prev_path) | |
| else: | |
| Image.new("RGB", (1200, 300), "white").save(prev_path) | |
| return ( | |
| FileData(path=uc_path), | |
| FileData(path=lc_path), | |
| FileData(path=pn_path), | |
| FileData(path=prev_path), | |
| FileData(path=otf_path), | |
| font_name, | |
| ) | |
| # ============================================================================= | |
| # FRONTEND — React (CDN + in-browser Babel, no build step), served inline. | |
| # Talks to the backend through the Gradio JS client so requests go through the | |
| # queue and ZeroGPU auth headers are forwarded (a raw fetch() would break it). | |
| # ============================================================================= | |
| FRONTEND_HTML = r"""<!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1" /> | |
| <title>Typotopia</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet"> | |
| <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script> | |
| <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> | |
| <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> | |
| <style> | |
| /*__TITLE_FONT_FACE__*/ | |
| :root{ | |
| --ink:#000; --paper:#fff; --bg:#ECECEC; --accent:#5F2EEA; | |
| --grey:#6B6B6B; --hairline:#D8D8D8; | |
| --grotesk:'Helvetica Neue',Helvetica,'Archivo',Arial,sans-serif; | |
| --mono:'JetBrains Mono',ui-monospace,monospace; | |
| --title:__TITLE_FAMILY__; | |
| --r:14px; --r-sm:9px; | |
| } | |
| *{box-sizing:border-box;margin:0;padding:0;} | |
| html,body{background:var(--bg);color:var(--ink);font-family:var(--grotesk);-webkit-font-smoothing:antialiased;} | |
| ::selection{background:var(--accent);color:#fff;} | |
| a{color:inherit;} | |
| .wrap{max-width:1500px;margin:0 auto;padding:clamp(20px,4vw,56px) clamp(20px,5vw,72px) 80px;} | |
| /* ---- masthead ---- */ | |
| .masthead{display:flex;justify-content:space-between;align-items:flex-end;gap:32px;flex-wrap:wrap; | |
| padding-bottom:2px;} | |
| .wordmark{font-family:var(--title);font-weight:800;line-height:.8;letter-spacing:-.05em; | |
| font-size:clamp(48px,9vw,124px);} | |
| .wordmark .stop{color:var(--accent);} | |
| .meta{font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:.12em; | |
| min-width:300px;flex:0 1 360px;} | |
| .meta .row{display:flex;justify-content:space-between;gap:24px;padding:7px 0;border-top:1px solid var(--ink);} | |
| .meta .row:first-child{border-top:none;} | |
| .meta .k{color:var(--grey);} | |
| .meta .v{text-align:right;} | |
| /* ---- working grid ---- */ | |
| .work{display:grid;grid-template-columns:0.92fr 1.18fr;gap:0;margin-top:28px;border:1px solid var(--ink); | |
| border-radius:var(--r);overflow:hidden;} | |
| .col{padding:clamp(18px,2.4vw,34px);} | |
| .col.left{border-right:1px solid var(--ink);background:var(--paper);} | |
| .col.right{background:var(--paper);} | |
| @media(max-width:880px){.work{grid-template-columns:1fr;}.col.left{border-right:none;border-bottom:1px solid var(--ink);}} | |
| .label{font-family:var(--mono);font-size:10px;font-weight:600;text-transform:uppercase; | |
| letter-spacing:.16em;color:var(--ink);display:block;margin-bottom:10px;} | |
| .sub{color:var(--grey);} | |
| textarea{width:100%;min-height:120px;resize:vertical;border:1px solid var(--ink);background:var(--paper); | |
| font-family:var(--grotesk);font-size:15px;line-height:1.45;padding:14px;outline:none;color:var(--ink); | |
| border-radius:var(--r-sm);} | |
| textarea:focus{border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent);} | |
| textarea::placeholder{color:var(--grey);} | |
| .dz{margin-top:22px;border:1px dashed var(--ink);background:var(--paper);min-height:120px; | |
| display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative; | |
| border-radius:var(--r-sm);overflow:hidden; | |
| transition:border-color .12s,background .12s;} | |
| .dz:hover,.dz.over{border-color:var(--accent);background:#FAF8FF;} | |
| .dz .dzhint{font-family:var(--mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--grey);} | |
| .dz img{max-width:100%;max-height:200px;display:block;} | |
| .dz .clear{position:absolute;top:6px;right:6px;width:26px;height:26px;border:1px solid var(--ink); | |
| background:var(--paper);font-family:var(--mono);font-size:13px;line-height:1;cursor:pointer;border-radius:6px; | |
| display:flex;align-items:center;justify-content:center;} | |
| .dz .clear:hover{background:var(--ink);color:var(--paper);} | |
| .go{margin-top:24px;width:100%;min-height:54px;border:none;background:var(--accent);color:#fff; | |
| font-family:var(--grotesk);font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:.22em; | |
| cursor:pointer;border-radius:var(--r-sm);transition:background .12s;} | |
| .go:hover{background:var(--ink);} | |
| .go:disabled{background:var(--grey);cursor:not-allowed;} | |
| .err{margin-top:14px;font-family:var(--mono);font-size:12px;color:#B00020;letter-spacing:.04em;} | |
| /* ---- output ---- */ | |
| .placeholder{height:100%;min-height:280px;display:flex;align-items:center;justify-content:center; | |
| font-family:var(--mono);font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--hairline);} | |
| .specimen{border:1px solid var(--ink);background:var(--paper);overflow:hidden;border-radius:var(--r);} | |
| .specimen .bar{display:flex;justify-content:space-between;align-items:baseline; | |
| padding:10px 14px;border-bottom:1px solid var(--ink);} | |
| .specimen .name{font-family:var(--title);font-weight:800;font-size:22px;letter-spacing:-.02em;} | |
| .specimen .tag{font-family:var(--mono);font-size:10px;letter-spacing:.16em;text-transform:uppercase;color:var(--grey);} | |
| .specimen .canvas{padding:18px 14px;display:flex;align-items:center;justify-content:center;background:var(--paper);} | |
| .specimen .canvas img{width:100%;height:auto;display:block;} | |
| .dl{margin-top:18px;display:flex;align-items:stretch;border:1px solid var(--ink);background:var(--paper); | |
| border-radius:var(--r-sm);overflow:hidden;} | |
| .dl .info{flex:1;padding:12px 16px;} | |
| .dl .info .fn{font-family:var(--mono);font-size:14px;font-weight:600;letter-spacing:.02em;} | |
| .dl .info .ft{font-family:var(--mono);font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--grey);margin-top:3px;} | |
| .dl a.btn{display:flex;align-items:center;padding:0 26px;background:var(--ink);color:#fff; | |
| text-decoration:none;font-family:var(--grotesk);font-weight:700;font-size:12px; | |
| text-transform:uppercase;letter-spacing:.18em;transition:background .12s;} | |
| .dl a.btn:hover{background:var(--accent);} | |
| .grids{margin-top:18px;display:grid;grid-template-columns:repeat(3,1fr);gap:12px;} | |
| .gridcard{border:1px solid var(--ink);background:var(--paper);border-radius:var(--r-sm);overflow:hidden;} | |
| .gridcard .gl{font-family:var(--mono);font-size:9px;letter-spacing:.16em;text-transform:uppercase; | |
| padding:7px 9px;border-bottom:1px solid var(--ink);color:var(--grey);} | |
| .gridcard img{width:100%;height:auto;display:block;} | |
| @media(max-width:540px){.grids{grid-template-columns:1fr;}} | |
| /* ---- loading ---- */ | |
| .loading{height:100%;min-height:300px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;} | |
| .scan{width:64px;height:64px;border:2px solid var(--ink);position:relative;overflow:hidden;border-radius:var(--r-sm);} | |
| .scan::after{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--accent); | |
| animation:scan 1.1s ease-in-out infinite;} | |
| @keyframes scan{0%{top:0}50%{top:calc(100% - 2px)}100%{top:0}} | |
| .lmsg{font-family:var(--mono);font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--ink);} | |
| .lsub{font-family:var(--mono);font-size:10px;letter-spacing:.12em;color:var(--grey);} | |
| .foot{margin-top:40px;font-family:var(--mono);font-size:10px;letter-spacing:.14em; | |
| text-transform:uppercase;color:var(--grey);display:flex;justify-content:space-between;flex-wrap:wrap;gap:12px;} | |
| @media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important;}} | |
| </style> | |
| </head> | |
| <body> | |
| <div id="root"></div> | |
| <script type="text/babel" data-type="module" data-presets="react"> | |
| import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"; | |
| const { useState, useRef, useEffect, useCallback } = React; | |
| const STAGES = [ | |
| "Generating uppercase", | |
| "Generating lowercase", | |
| "Generating punctuation", | |
| "Vectorizing contours", | |
| "Computing bubble kerning", | |
| "Assembling OpenType", | |
| ]; | |
| let clientPromise = null; | |
| function getClient(){ | |
| if(!clientPromise) clientPromise = Client.connect(window.location.origin); | |
| return clientPromise; | |
| } | |
| function App(){ | |
| const [prompt,setPrompt] = useState(""); | |
| const [file,setFile] = useState(null); | |
| const [fileUrl,setFileUrl] = useState(null); | |
| const [over,setOver] = useState(false); | |
| const [loading,setLoading] = useState(false); | |
| const [stage,setStage] = useState(0); | |
| const [err,setErr] = useState(""); | |
| const [res,setRes] = useState(null); | |
| const inputRef = useRef(null); | |
| useEffect(()=>{ | |
| if(!loading) return; | |
| setStage(0); | |
| const id = setInterval(()=>setStage(s=>Math.min(s+1, STAGES.length-1)), 12000); | |
| return ()=>clearInterval(id); | |
| },[loading]); | |
| const pickFile = (f)=>{ | |
| if(!f) return; | |
| setFile(f); | |
| if(fileUrl) URL.revokeObjectURL(fileUrl); | |
| setFileUrl(URL.createObjectURL(f)); | |
| }; | |
| const clearFile = (e)=>{ | |
| e.stopPropagation(); | |
| setFile(null); | |
| if(fileUrl) URL.revokeObjectURL(fileUrl); | |
| setFileUrl(null); | |
| if(inputRef.current) inputRef.current.value = ""; | |
| }; | |
| const onDrop = useCallback((e)=>{ | |
| e.preventDefault(); setOver(false); | |
| const f = e.dataTransfer.files && e.dataTransfer.files[0]; | |
| if(f && f.type.startsWith("image/")) pickFile(f); | |
| },[fileUrl]); | |
| const run = async ()=>{ | |
| setErr(""); | |
| if(!file && !prompt.trim()){ | |
| setErr("Provide a prompt or a control image."); | |
| return; | |
| } | |
| setLoading(true); setRes(null); | |
| try{ | |
| const client = await getClient(); | |
| const payload = { prompt: prompt }; | |
| if(file) payload.control_image = handle_file(file); | |
| const result = await client.predict("/generate", payload); | |
| const d = result.data; | |
| setRes({ | |
| uc: d[0].url, | |
| lc: d[1].url, | |
| punc: d[2].url, | |
| preview: d[3].url, | |
| otf: d[4].url, | |
| name: d[5], | |
| }); | |
| }catch(ex){ | |
| console.error(ex); | |
| const msg = (ex && (ex.message || (ex.detail && (ex.detail.message||ex.detail)))) || "Generation failed."; | |
| setErr(String(msg)); | |
| }finally{ | |
| setLoading(false); | |
| } | |
| }; | |
| return ( | |
| <div className="wrap"> | |
| <header className="masthead"> | |
| <div className="wordmark">Typotopia<span className="stop">.</span></div> | |
| <div className="meta"> | |
| <div className="row"><span className="k">Input</span><span className="v">Prompt / Control image</span></div> | |
| <div className="row"><span className="k">Model</span><span className="v">FLUX.2-klein · 3× LoRA</span></div> | |
| <div className="row"><span className="k">Output</span><span className="v">OpenType · GPOS kerning</span></div> | |
| </div> | |
| </header> | |
| <div className="work"> | |
| <section className="col left"> | |
| <label className="label">Prompt <span className="sub">/ describe the typeface</span></label> | |
| <textarea | |
| value={prompt} | |
| onChange={e=>setPrompt(e.target.value)} | |
| placeholder="e.g. a bold geometric sans inspired by brutalist concrete signage" | |
| /> | |
| <label className="label" style={{marginTop:22}}>Control image <span className="sub">/ optional</span></label> | |
| <div | |
| className={"dz"+(over?" over":"")} | |
| onClick={()=>inputRef.current && inputRef.current.click()} | |
| onDragOver={e=>{e.preventDefault();setOver(true);}} | |
| onDragLeave={()=>setOver(false)} | |
| onDrop={onDrop} | |
| > | |
| {fileUrl | |
| ? (<React.Fragment><img src={fileUrl} alt="control" /><button className="clear" onClick={clearFile} title="Remove">×</button></React.Fragment>) | |
| : (<span className="dzhint">Drop image · or click</span>)} | |
| <input ref={inputRef} type="file" accept="image/*" hidden | |
| onChange={e=>pickFile(e.target.files && e.target.files[0])} /> | |
| </div> | |
| <button className="go" onClick={run} disabled={loading}> | |
| {loading ? "Generating…" : "Generate font"} | |
| </button> | |
| {err && <div className="err">{err}</div>} | |
| </section> | |
| <section className="col right"> | |
| {loading ? ( | |
| <div className="loading"> | |
| <div className="scan"></div> | |
| <div className="lmsg">{STAGES[stage]}…</div> | |
| <div className="lsub">This takes ~1–2 min on ZeroGPU</div> | |
| </div> | |
| ) : res ? ( | |
| <React.Fragment> | |
| <div className="specimen"> | |
| <div className="bar"> | |
| <span className="name">{res.name}</span> | |
| <span className="tag">Specimen · Regular</span> | |
| </div> | |
| <div className="canvas"><img src={res.preview} alt="specimen" /></div> | |
| </div> | |
| <div className="dl"> | |
| <div className="info"> | |
| <div className="fn">{res.name}.otf</div> | |
| <div className="ft">OpenType · CFF · GPOS</div> | |
| </div> | |
| <a className="btn" href={res.otf} download={res.name + ".otf"}>Download</a> | |
| </div> | |
| <div className="grids"> | |
| <div className="gridcard"><div className="gl">Uppercase</div><img src={res.uc} alt="uppercase" /></div> | |
| <div className="gridcard"><div className="gl">Lowercase</div><img src={res.lc} alt="lowercase" /></div> | |
| <div className="gridcard"><div className="gl">Punctuation</div><img src={res.punc} alt="punctuation" /></div> | |
| </div> | |
| </React.Fragment> | |
| ) : ( | |
| <div className="placeholder">Output appears here</div> | |
| )} | |
| </section> | |
| </div> | |
| <div className="foot"> | |
| <span>Typotopia — generative type foundry</span> | |
| <span>FLUX.2-klein · fontTools · potrace</span> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| ReactDOM.createRoot(document.getElementById("root")).render(<App />); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| FRONTEND_HTML = ( | |
| FRONTEND_HTML | |
| .replace("__TITLE_FAMILY__", TITLE_FAMILY) | |
| .replace("/*__TITLE_FONT_FACE__*/", TITLE_FONT_FACE) | |
| ) | |
| async def homepage(): | |
| return FRONTEND_HTML | |
| app.launch(show_error=True) | |