Spaces:
Sleeping
Sleeping
Upload 2 files
Browse filesFiles changed (2)
- app/font_engine.py+102-10
- app/main.py+39-11
16 unmodified lines171819202122511 unmodified lines5345355365375385395405415425435445455465475485495505515525534 unmodified lines5585595605615625635647 unmodified lines57257357457557657757857958058158265 unmodified lines64864965016 unmodified linesfrom dataclasses import dataclass, fieldfrom typing import Any, Optionalfrom fontTools.pens.boundsPen import BoundsPenfrom fontTools.pens.recordingPen import DecomposingRecordingPenfrom fontTools.pens.svgPathPen import SVGPathPen511 unmodified linesdef add_glyph_to_font(font: TTFont, glyph_name: str, codepoint: int, contours: list[ContourOps], width: float) -> None:glyph_order = font.getGlyphOrder()if glyph_name not in glyph_order:if len(glyph_order) >= MAX_GLYPHS:raise ValueError(f"Font zaten OpenType formatının izin verdiği azami {MAX_GLYPHS} glyph sınırında "f"({len(glyph_order)} glyph); '{glyph_name}' eklenemiyor. Bu format kısıtı kodla "f"aşılamaz — fontu önce subset ederek kullanılmayan glyph'leri kaldırmanız gerekir.")glyph_order.append(glyph_name)font.setGlyphOrder(glyph_order)bounds = contours_bounds(contours)lsb = int(round(bounds[0])) if bounds else 0if "glyf" in font:pen = TTGlyphPen(font.getGlyphSet())draw_contours(contours, pen)glyph = pen.glyph()4 unmodified linescff = font["CFF "].cfftop_dict = cff.topDictIndex[0]char_strings = top_dict.CharStringsprivate = getattr(top_dict, "Private", None)pen = T2CharStringPen(width, font.getGlyphSet())draw_contours(contours, pen)charstring = pen.getCharString(private=private, globalSubrs=cff.GlobalSubrs)7 unmodified lineschar_strings.charStrings[glyph_name] = charstringif glyph_name not in top_dict.charset:top_dict.charset = list(top_dict.charset) + [glyph_name]else:raise ValueError("Desteklenmeyen font formatı: ne 'glyf' ne 'CFF ' tablosu var.")font["hmtx"][glyph_name] = (int(round(width)), lsb)for table in font["cmap"].tables:if table.isUnicode():table.cmap[codepoint] = glyph_name65 unmodified linesout_bytes = save_font(font)return out_bytes, report16 unmodified lines17181920212223511 unmodified lines5355365375385395405415425435445455465475485495505515525535544 unmodified lines5595605615625635645655665675685695705715725735745755765775785795805815825835845857 unmodified lines59359459559659759859960060160260360460560660760860961061161261361461561665 unmodified lines68268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174216 unmodified linesfrom dataclasses import dataclass, fieldfrom typing import Any, Optionalfrom fontTools import subset as ftsubsetfrom fontTools.pens.boundsPen import BoundsPenfrom fontTools.pens.recordingPen import DecomposingRecordingPenfrom fontTools.pens.svgPathPen import SVGPathPen511 unmodified linesdef add_glyph_to_font(font: TTFont, glyph_name: str, codepoint: int, contours: list[ContourOps], width: float) -> None:glyph_order = font.getGlyphOrder()if len(glyph_order) >= MAX_GLYPHS and glyph_name not in glyph_order:raise ValueError(f"Font zaten OpenType formatının izin verdiği azami {MAX_GLYPHS} glyph sınırında "f"({len(glyph_order)} glyph); '{glyph_name}' eklenemiyor. Bu format kısıtı kodla "f"aşılamaz — fontu önce subset ederek kullanılmayan glyph'leri kaldırmanız gerekir.")bounds = contours_bounds(contours)lsb = int(round(bounds[0])) if bounds else 0if "glyf" in font:if glyph_name not in glyph_order:glyph_order.append(glyph_name)font.setGlyphOrder(glyph_order)pen = TTGlyphPen(font.getGlyphSet())draw_contours(contours, pen)glyph = pen.glyph()4 unmodified linescff = font["CFF "].cfftop_dict = cff.topDictIndex[0]char_strings = top_dict.CharStringsis_cid = hasattr(top_dict, "ROS")if is_cid:# CID-keyed CFF (büyük CJK fontlarında yaygın, ör. Source Han# Sans): glyph adları CFF seviyesinde aslında CID numaralarıdır# ve "cidNNNNN" biçiminde temsil edilir; istenen ada bakılmaksızın# boşta bir CID seçilir. Ayrıca her glyph bir FDArray girdisine# (FDSelect ile) atanmış olmalıdır — hinting açısından önemsiz# olduğundan basitçe ilk FD (0) kullanılır.existing_cids = [int(n[3:]) for n in char_strings.keys() if n.startswith("cid") and n[3:].isdigit()]glyph_name = f"cid{(max(existing_cids) + 1 if existing_cids else 1):05d}"private = top_dict.FDArray[0].Privateelse:private = getattr(top_dict, "Private", None)if glyph_name not in glyph_order:glyph_order.append(glyph_name)font.setGlyphOrder(glyph_order)pen = T2CharStringPen(width, font.getGlyphSet())draw_contours(contours, pen)charstring = pen.getCharString(private=private, globalSubrs=cff.GlobalSubrs)7 unmodified lineschar_strings.charStrings[glyph_name] = charstringif glyph_name not in top_dict.charset:top_dict.charset = list(top_dict.charset) + [glyph_name]if is_cid and hasattr(top_dict, "FDSelect"):top_dict.FDSelect.gidArray.append(0)else:raise ValueError("Desteklenmeyen font formatı: ne 'glyf' ne 'CFF ' tablosu var.")font["hmtx"][glyph_name] = (int(round(width)), lsb)if "vmtx" in font:# Dikey yazı desteği olan fontlarda (çoğu CJK fontu) her glyph'in bir# dikey metrik girdisi de olmak zorunda — yoksa 'vmtx' derlemesi bu# glyph için KeyError verir. Türkçe harfler dikey dizilmeyeceği için# burada makul bir varsayılan (tam em yükseklik, üstten hizalı) yeterli.vhea = font.get("vhea")upm = units_per_em(font)v_advance = int(vhea.ascent - vhea.descent) if vhea is not None else upmtsb = int(round(vhea.ascent - bounds[3])) if (vhea is not None and bounds) else 0font["vmtx"][glyph_name] = (v_advance, tsb)for table in font["cmap"].tables:if table.isUnicode():table.cmap[codepoint] = glyph_name65 unmodified linesout_bytes = save_font(font)return out_bytes, report# --------------------------------------------------------------------------# Subset (glyph sayısını azaltma)# --------------------------------------------------------------------------# Türkçe kompozisyon için gereken her şeyi (temel Latin harfler, standalone# aksan glyph'leri, donor karakterler) kapsayan güvenlik ağı — kullanıcı ne# isterse istesin, subset sonrasında karakter oluşturma hâlâ çalışsın diye# bu blok HER ZAMAN korunur. Boyutu bir CJK fontunda ihmal edilebilir düzeyde.SAFE_KEEP_UNICODES = frozenset(set(range(0x0020, 0x0250)) # ASCII + Latin-1 Supplement + Latin Extended A/B| set(range(0x0300, 0x0370)) # Combining Diacritical Marks)# Kullanıcının isteğe bağlı olarak işaretleyebileceği, yaygın CJK metni için# makul bir varsayılan: temel CJK Unified Ideographs bloğu + CJK# noktalama/tam genişlik biçimleri. Onbinlerce nadir kullanılan glyph'i# (Ext. A/B/C/D/E, dikey/stilistik varyantlar vb.) elerken çoğu kullanım# senaryosunu karşılar.CJK_PRESET_UNICODES = frozenset(set(range(0x4E00, 0xA000)) # CJK Unified Ideographs (+ Ext. A dahil)| set(range(0x3000, 0x3040)) # CJK Symbols and Punctuation| set(range(0xFF00, 0xFFF0)) # Halfwidth and Fullwidth Forms)def subset_font(data: bytes, keep_text: str = "", keep_cjk_preset: bool = False) -> tuple[bytes, dict[str, Any]]:"""Fontu, kullanıcının belirttiği metin/karakterler ile Türkçe kompozisyoniçin gereken temel Latin/aksan glyph'lerini koruyarak küçültür. Glyphsayısı OpenType'ın 65535 sınırına dayanmış büyük (ör. CJK) fontlarda yenikarakterlere yer açmak için kullanılır. GSUB/GPOS kapanışı (closure)fontTools'un subsetter'ı tarafından otomatik olarak korunur."""font = load_font(data)before = len(font.getGlyphOrder())keep_unicodes: set[int] = set(SAFE_KEEP_UNICODES)if keep_cjk_preset:keep_unicodes |= CJK_PRESET_UNICODESkeep_unicodes.update(ord(ch) for ch in keep_text)options = ftsubset.Options()options.glyph_names = Trueoptions.notdef_outline = Trueoptions.recommended_glyphs = Trueoptions.layout_features = ["*"]subsetter = ftsubset.Subsetter(options=options)subsetter.populate(unicodes=keep_unicodes)subsetter.subset(font)after = len(font.getGlyphOrder())out_bytes = save_font(font)info = {"glyphs_before": before,"glyphs_after": after,"glyphs_freed": before - after,}return out_bytes, info
45 unmodified lines46474849505117 unmodified lines697071727374754 unmodified lines808182838485868788899091929394954 unmodified lines10010110210310410545 unmodified linesCHAR_DEFS_BY_CHAR = {c.char: c for c in R.TURKISH_CHAR_DEFS}@app.get("/api/health")def health() -> dict[str, str]:return {"status": "ok"}17 unmodified linessession_id = uuid.uuid4().hexfilename = font.filename or "font"analysis = fe.analyze_font(parsed)with _sessions_lock:_prune_sessions()4 unmodified lines"created": time.time(),}font_info = fe.get_font_info(parsed, filename)font_info["chars_needing_new_glyphs"] = sum(1 for a in analysis if a.recipe.get("mode") in ("compose", "dotless"))return {"session_id": session_id,"font_info": font_info,"chars": [fe.analysis_to_dict(a) for a in analysis],}@app.get("/api/glyphs")4 unmodified linesreturn {"glyphs": names}class PreviewRequest(BaseModel):session_id: strchar: str45 unmodified lines4647484950515253545556575859606162636417 unmodified lines8283848586874 unmodified lines929394959697984 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213345 unmodified linesCHAR_DEFS_BY_CHAR = {c.char: c for c in R.TURKISH_CHAR_DEFS}def _session_response(session_id: str, font: Any, filename: str) -> dict[str, Any]:analysis = fe.analyze_font(font)font_info = fe.get_font_info(font, filename)font_info["chars_needing_new_glyphs"] = sum(1 for a in analysis if a.recipe.get("mode") in ("compose", "dotless"))return {"session_id": session_id,"font_info": font_info,"chars": [fe.analysis_to_dict(a) for a in analysis],}@app.get("/api/health")def health() -> dict[str, str]:return {"status": "ok"}17 unmodified linessession_id = uuid.uuid4().hexfilename = font.filename or "font"with _sessions_lock:_prune_sessions()4 unmodified lines"created": time.time(),}return _session_response(session_id, parsed, filename)@app.get("/api/glyphs")4 unmodified linesreturn {"glyphs": names}class SubsetRequest(BaseModel):session_id: strkeep_text: str = ""keep_cjk_preset: bool = False@app.post("/api/subset")def subset(req: SubsetRequest) -> dict[str, Any]:session = _get_session(req.session_id)try:out_bytes, info = fe.subset_font(session["original_bytes"], req.keep_text, req.keep_cjk_preset)except Exception as exc: # noqa: BLE001raise HTTPException(status_code=400, detail=f"Subset işlemi başarısız: {exc}") from excnew_font = fe.load_font(out_bytes)with _sessions_lock:session["font"] = new_fontsession["original_bytes"] = out_bytessession["created"] = time.time()response = _session_response(req.session_id, new_font, session["filename"])response["subset_info"] = inforeturn responseclass PreviewRequest(BaseModel):session_id: strchar: str
app/font_engine.py+102-10
app/main.py+39-11