Debian Codegraph @

scripts/remove_calt.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 import sys
5 import os
6 import glob
7 import re
8 from fontTools.ttLib import TTFont
9 from fontTools.ttLib.tables import otTables
10 import argparse
11
12 def modify_font_name(font, suffix="-NL"):
13 """
14 Add suffix to font names in the name table and CFF table if present.
15
16 Args:
17 font (TTFont): The font object
18 suffix (str): Base suffix to add to the font names (without spacing)
19 """
20 # Remove the hyphen from the suffix as we'll add proper spacing dynamically
21 base_suffix = suffix.lstrip('-')
22
23 # Get the subfamily name (nameID 2) for use in Full font name modification
24 subfamily_name = None
25 if 'name' in font:
26 for record in font['name'].names:
27 if record.nameID == 2:
28 try:
29 subfamily_name = record.toUnicode()
30 break
31 except:
32 pass
33
34 # Update name table
35 if 'name' in font:
36 # Font name IDs to modify
37 # 1: Font Family name
38 # 2: Font Subfamily name
39 # 3: Unique identifier
40 # 4: Full font name
41 # 6: PostScript name
42 # 16: Typographic family name
43 # 17: Typographic subfamily name
44 # 21: WWS family name
45 name_ids_to_modify = [1, 3, 4, 6, 16, 21]
46
47 for record in font['name'].names:
48 if record.nameID in name_ids_to_modify:
49 # Decode the name string
50 try:
51 name_str = record.toUnicode()
52
53 # Skip if suffix is already applied
54 if name_str.endswith(f"-{base_suffix}") or name_str.endswith(f" {base_suffix}"):
55 continue
56
57 # Determine appropriate suffix format based on naming pattern
58 # Special case for PostScript name (always use hyphen for ID 6)
59 if record.nameID == 6:
60 actual_suffix = f"-{base_suffix}"
61 new_name = name_str + actual_suffix
62 # Special case for Full font name (nameID 4)
63 # Insert suffix before the style name to ensure it starts with Family name
64 # e.g., "0xProto Bold" -> "0xProto NL Bold"
65 elif record.nameID == 4 and subfamily_name:
66 # Find the style name at the end and insert suffix before it
67 if name_str.endswith(f" {subfamily_name}"):
68 base_name = name_str[:-len(f" {subfamily_name}")]
69 new_name = f"{base_name} {base_suffix} {subfamily_name}"
70 else:
71 # Fallback: just append suffix
72 new_name = name_str + f" {base_suffix}"
73 # For other names, check if they use hyphens or spaces
74 elif '-' in name_str and ' ' not in name_str:
75 actual_suffix = f"-{base_suffix}"
76 new_name = name_str + actual_suffix
77 else:
78 actual_suffix = f" {base_suffix}"
79 new_name = name_str + actual_suffix
80
81 # Update the record
82 record.string = new_name.encode(record.getEncoding())
83
84 print(f" - Updated name ID {record.nameID}: {name_str} -> {new_name}")
85 except Exception as e:
86 print(f" - Error updating name ID {record.nameID}: {e}")
87
88 # Update CFF table if present
89 if 'CFF ' in font:
90 cff = font['CFF '].cff
91
92 if len(cff) > 0:
93 cff_font = cff[0]
94
95 # Update CFF font name (equivalent to PostScript name)
96 # PostScript names always use hyphens, no spaces allowed
97 if hasattr(cff_font, 'FontName'):
98 old_name = cff_font.FontName
99 # Convert to string for comparison if it's bytes
100 old_name_str = old_name.decode('ascii', errors='replace') if isinstance(old_name, bytes) else old_name
101
102 # Skip if suffix is already applied
103 if old_name_str.endswith(f"-{base_suffix}"):
104 pass
105 else:
106 # PostScript names always use hyphens
107 actual_suffix = f"-{base_suffix}"
108
109 # Convert suffix to bytes if the original is bytes
110 if isinstance(old_name, bytes):
111 cff_font.FontName = old_name + actual_suffix.encode('ascii')
112 else:
113 cff_font.FontName = old_name + actual_suffix
114
115 print(f" - Updated CFF FontName: {old_name_str} -> {cff_font.FontName.decode('ascii', errors='replace') if isinstance(cff_font.FontName, bytes) else cff_font.FontName}")
116
117 # Update CFF font Full Name
118 if hasattr(cff_font, 'FullName'):
119 old_name = cff_font.FullName
120 # Convert to string for comparison if it's bytes
121 old_name_str = old_name.decode('ascii', errors='replace') if isinstance(old_name, bytes) else old_name
122
123 # Skip if suffix is already applied
124 if old_name_str.endswith(f"-{base_suffix}") or old_name_str.endswith(f" {base_suffix}"):
125 pass
126 else:
127 # Insert suffix before the style name if subfamily is known
128 if subfamily_name and old_name_str.endswith(f" {subfamily_name}"):
129 base_name = old_name_str[:-len(f" {subfamily_name}")]
130 new_name_str = f"{base_name} {base_suffix} {subfamily_name}"
131 else:
132 # Fallback: just append suffix
133 if '-' in old_name_str and ' ' not in old_name_str:
134 new_name_str = old_name_str + f"-{base_suffix}"
135 else:
136 new_name_str = old_name_str + f" {base_suffix}"
137
138 # Convert suffix to bytes if the original is bytes
139 if isinstance(old_name, bytes):
140 cff_font.FullName = new_name_str.encode('ascii')
141 else:
142 cff_font.FullName = new_name_str
143
144 print(f" - Updated CFF FullName: {old_name_str} -> {new_name_str}")
145
146 # Update CFF font Family Name
147 if hasattr(cff_font, 'FamilyName'):
148 old_name = cff_font.FamilyName
149 # Convert to string for comparison if it's bytes
150 old_name_str = old_name.decode('ascii', errors='replace') if isinstance(old_name, bytes) else old_name
151
152 # Skip if suffix is already applied
153 if old_name_str.endswith(f"-{base_suffix}") or old_name_str.endswith(f" {base_suffix}"):
154 pass
155 else:
156 # Determine format based on existing name
157 if '-' in old_name_str and ' ' not in old_name_str:
158 actual_suffix = f"-{base_suffix}"
159 else:
160 actual_suffix = f" {base_suffix}"
161
162 # Convert suffix to bytes if the original is bytes
163 if isinstance(old_name, bytes):
164 cff_font.FamilyName = old_name + actual_suffix.encode('ascii')
165 else:
166 cff_font.FamilyName = old_name + actual_suffix
167
168 print(f" - Updated CFF FamilyName: {old_name_str} -> {cff_font.FamilyName.decode('ascii', errors='replace') if isinstance(cff_font.FamilyName, bytes) else cff_font.FamilyName}")
169
170 def modify_output_path(output_path, suffix="-NL"):
171 """
172 Add suffix to the output filename.
173 Base suffix is applied with a hyphen, regardless of the font name format.
174
175 Args:
176 output_path (str): Original output path
177 suffix (str): Suffix to add to the filename
178
179 Returns:
180 str: Modified output path
181 """
182 # Remove any leading hyphen from suffix for consistency
183 base_suffix = suffix.lstrip('-')
184
185 # Split the path into directory, filename, and extension
186 directory, filename = os.path.split(output_path)
187 name, ext = os.path.splitext(filename)
188
189 # Add suffix to the name if it doesn't already have it
190 if not (name.endswith(f"-{base_suffix}") or name.endswith(f" {base_suffix}")):
191 # For filenames, we always use hyphen format
192 new_name = name + f"-{base_suffix}"
193 new_filename = new_name + ext
194 new_path = os.path.join(directory, new_filename)
195 return new_path
196
197 return output_path
198
199 def remove_calt_feature(input_font_path, output_font_path=None, suffix="-NL"):
200 """
201 Remove the 'calt' OpenType feature from a font file and save as a new font.
202 Also update font names with the given suffix.
203
204 Args:
205 input_font_path (str): Path to the input font file
206 output_font_path (str, optional): Path to save the modified font.
207 If None, will use input name + suffix
208 suffix (str): Suffix to add to the font names
209
210 Returns:
211 str: Path to the output font file
212 """
213 # Remove any leading hyphen from suffix for consistency when determining file paths
214 base_suffix = suffix.lstrip('-')
215
216 # Determine output path if not specified
217 if output_font_path is None:
218 file_name, file_ext = os.path.splitext(input_font_path)
219 output_font_path = f"{file_name}-{base_suffix}{file_ext}"
220 else:
221 # Add suffix to output filename if it doesn't have it already
222 output_font_path = modify_output_path(output_font_path, f"-{base_suffix}")
223
224 # Open the font
225 try:
226 font = TTFont(input_font_path)
227 except Exception as e:
228 print(f"Error opening font file: {e}")
229 return None
230
231 # Check if the font has GSUB table (which contains OpenType features)
232 if 'GSUB' not in font:
233 print(f" - This font does not have a GSUB table (no OpenType layout features)")
234 else:
235 # Get the GSUB table
236 gsub = font['GSUB']
237
238 # Check if there's a feature list
239 if not hasattr(gsub.table, 'FeatureList') or not gsub.table.FeatureList.FeatureRecord:
240 print(f" - No feature records found in GSUB table")
241 else:
242 # Find and remove 'calt' features
243 calt_indices = []
244 for i, feature_record in enumerate(gsub.table.FeatureList.FeatureRecord):
245 if feature_record.FeatureTag == 'calt':
246 calt_indices.append(i)
247
248 if not calt_indices:
249 print(f" - No 'calt' feature found in the font")
250 else:
251 # Remove 'calt' feature references from feature list
252 # We need to process in reverse order to maintain correct indices
253 for index in sorted(calt_indices, reverse=True):
254 print(f" - Removing 'calt' feature at index {index}")
255 del gsub.table.FeatureList.FeatureRecord[index]
256
257 # Now we need to update any script records that might reference the 'calt' feature
258 if hasattr(gsub.table, 'ScriptList') and gsub.table.ScriptList.ScriptRecord:
259 for script_record in gsub.table.ScriptList.ScriptRecord:
260 # Process default language system if present
261 if script_record.Script.DefaultLangSys:
262 remove_feature_indices_from_langsys(script_record.Script.DefaultLangSys, calt_indices)
263
264 # Process other language systems
265 if script_record.Script.LangSysRecord:
266 for lang_sys_record in script_record.Script.LangSysRecord:
267 remove_feature_indices_from_langsys(lang_sys_record.LangSys, calt_indices)
268
269 # Modify font names to add suffix
270 modify_font_name(font, suffix)
271
272 # Save the modified font
273 try:
274 # Ensure the output directory exists
275 os.makedirs(os.path.dirname(output_font_path) or '.', exist_ok=True)
276
277 font.save(output_font_path)
278 print(f" - Modified font saved to: {output_font_path}")
279 return output_font_path
280 except Exception as e:
281 print(f" - Error saving modified font: {e}")
282 return None
283
284 def remove_feature_indices_from_langsys(lang_sys, indices_to_remove):
285 """
286 Remove feature indices from a LangSys object and adjust remaining indices.
287
288 Args:
289 lang_sys: LangSys object from the GSUB table
290 indices_to_remove (list): List of feature indices to remove
291 """
292 if not hasattr(lang_sys, 'FeatureIndex') or not lang_sys.FeatureIndex:
293 return
294
295 # Create a new list of feature indices, excluding the ones to remove
296 # and adjusting the remaining indices for the removed features
297 new_feature_indices = []
298 for idx in lang_sys.FeatureIndex:
299 # Skip indices that should be removed
300 if idx in indices_to_remove:
301 continue
302
303 # Adjust the index based on how many removed indices precede it
304 adjustment = sum(1 for removed_idx in indices_to_remove if removed_idx < idx)
305 new_feature_indices.append(idx - adjustment)
306
307 # Update the feature indices
308 lang_sys.FeatureIndex = new_feature_indices
309
310 def process_directory(input_dir, output_dir, suffix="-NL"):
311 """
312 Process all font files in a directory.
313
314 Args:
315 input_dir (str): Directory containing font files
316 output_dir (str): Directory to save processed fonts
317 suffix (str): Suffix to add to the font names
318
319 Returns:
320 tuple: (success_count, failure_count)
321 """
322 # Normalize paths
323 input_dir = os.path.normpath(input_dir)
324 output_dir = os.path.normpath(output_dir)
325
326 # Create output directory if it doesn't exist
327 os.makedirs(output_dir, exist_ok=True)
328
329 # Find all font files
330 font_files = []
331 for ext in ['.ttf', '.otf']:
332 font_files.extend(glob.glob(os.path.join(input_dir, f'*{ext}')))
333 # Also look in subdirectories
334 font_files.extend(glob.glob(os.path.join(input_dir, f'**/*{ext}'), recursive=True))
335
336 if not font_files:
337 print(f"No font files found in {input_dir}")
338 return 0, 0
339
340 print(f"Found {len(font_files)} font files to process")
341
342 # Process each font file
343 success_count = 0
344 failure_count = 0
345
346 for font_file in font_files:
347 # Calculate relative path from input_dir
348 rel_path = os.path.relpath(font_file, input_dir)
349 output_path = os.path.join(output_dir, rel_path)
350
351 print(f"\nProcessing: {rel_path}")
352
353 # Process the font
354 result = remove_calt_feature(font_file, output_path, suffix)
355
356 if result:
357 success_count += 1
358 else:
359 failure_count += 1
360
361 return success_count, failure_count
362
363 def process_single_file(input_file, output_file=None, suffix="-NL"):
364 """
365 Process a single font file.
366
367 Args:
368 input_file (str): Path to input font file
369 output_file (str, optional): Path to save processed font
370 suffix (str): Suffix to add to the font names
371
372 Returns:
373 bool: True if successful, False otherwise
374 """
375 # Remove any leading hyphen from suffix for consistency
376 base_suffix = suffix.lstrip('-')
377
378 # If output_file is a directory, calculate the output file path
379 if output_file and os.path.isdir(output_file):
380 filename = os.path.basename(input_file)
381 name, ext = os.path.splitext(filename)
382 new_filename = f"{name}-{base_suffix}{ext}"
383 output_file = os.path.join(output_file, new_filename)
384
385 print(f"Processing: {input_file}")
386 result = remove_calt_feature(input_file, output_file, suffix)
387
388 return result is not None
389
390 def main():
391 parser = argparse.ArgumentParser(description="Remove 'calt' OpenType feature from font files and add suffix to font names")
392 parser.add_argument("input_path",
393 help="Path to the input font file or directory containing font files")
394 parser.add_argument("-o", "--output",
395 help="Path to save the modified font or directory for output files (optional)")
396 parser.add_argument("-s", "--suffix", default="-NL",
397 help="Suffix to add to font names (default: -NL)")
398 args = parser.parse_args()
399
400 input_path = args.input_path
401 output_path = args.output
402 suffix = args.suffix
403
404 # Check if input is a directory
405 if os.path.isdir(input_path):
406 # If output is not specified, create a directory next to the input
407 if not output_path:
408 output_path = input_path + suffix
409
410 print(f"Processing directory: {input_path}")
411 print(f"Output directory: {output_path}")
412 print(f"Using suffix: {suffix}")
413
414 success, failure = process_directory(input_path, output_path, suffix)
415
416 print(f"\nProcessing complete!")
417 print(f"Successfully processed: {success} font files")
418 if failure > 0:
419 print(f"Failed to process: {failure} font files")
420 sys.exit(1)
421 else:
422 # Process single file
423 result = process_single_file(input_path, output_path, suffix)
424
425 if result:
426 print(f"Success! Font without 'calt' feature saved with {suffix} suffix.")
427 else:
428 print("Failed to process the font file.")
429 sys.exit(1)
430
431 if __name__ == "__main__":
432 main()