code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def elementwise_flop_counter(input_scale: float = 1, output_scale: float = 0) -> Handle: """ Count flops by input_tensor.numel() * input_scale + output_tensor.numel() * output_scale Args: input_scale: scale of the input tensor (first argument) output_scale: scale of the output tensor (first element in outputs) """ def elementwise_flop(inputs: List[Any], outputs: List[Any]) -> Number: ret = 0 if input_scale != 0: shape = get_shape(inputs[0]) ret += input_scale * prod(shape) if output_scale != 0: shape = get_shape(outputs[0]) ret += output_scale * prod(shape) flop_counter = Counter({"elementwise": ret}) return flop_counter return elementwise_flop
Count flops by input_tensor.numel() * input_scale + output_tensor.numel() * output_scale Args: input_scale: scale of the input tensor (first argument) output_scale: scale of the output tensor (first element in outputs)
elementwise_flop_counter
python
IDEA-Research/DINO
tools/benchmark.py
https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py
Apache-2.0
def flop_count( model: nn.Module, inputs: typing.Tuple[object, ...], whitelist: typing.Union[typing.List[str], None] = None, customized_ops: typing.Union[typing.Dict[str, typing.Callable], None] = None, ) -> typing.DefaultDict[str, float]: """ Given a model and an input to the model, compute the Gflops of the given model. Note the input should have a batch size of 1. Args: model (nn.Module): The model to compute flop counts. inputs (tuple): Inputs that are passed to `model` to count flops. Inputs need to be in a tuple. whitelist (list(str)): Whitelist of operations that will be counted. It needs to be a subset of _SUPPORTED_OPS. By default, the function computes flops for all supported operations. customized_ops (dict(str,Callable)) : A dictionary contains customized operations and their flop handles. If customized_ops contains an operation in _SUPPORTED_OPS, then the default handle in _SUPPORTED_OPS will be overwritten. Returns: defaultdict: A dictionary that records the number of gflops for each operation. """ # Copy _SUPPORTED_OPS to flop_count_ops. # If customized_ops is provided, update _SUPPORTED_OPS. flop_count_ops = _SUPPORTED_OPS.copy() if customized_ops: flop_count_ops.update(customized_ops) # If whitelist is None, count flops for all suported operations. if whitelist is None: whitelist_set = set(flop_count_ops.keys()) else: whitelist_set = set(whitelist) # Torch script does not support parallell torch models. if isinstance( model, (nn.parallel.distributed.DistributedDataParallel, nn.DataParallel), ): model = model.module # pyre-ignore assert set(whitelist_set).issubset( flop_count_ops ), "whitelist needs to be a subset of _SUPPORTED_OPS and customized_ops." assert isinstance(inputs, tuple), "Inputs need to be in a tuple." # Compatibility with torch.jit. if hasattr(torch.jit, "get_trace_graph"): trace, _ = torch.jit.get_trace_graph(model, inputs) trace_nodes = trace.graph().nodes() else: trace, _ = torch.jit._get_trace_graph(model, inputs) trace_nodes = trace.nodes() skipped_ops = Counter() total_flop_counter = Counter() for node in trace_nodes: kind = node.kind() if kind not in whitelist_set: # If the operation is not in _IGNORED_OPS, count skipped operations. if kind not in _IGNORED_OPS: skipped_ops[kind] += 1 continue handle_count = flop_count_ops.get(kind, None) if handle_count is None: continue inputs, outputs = list(node.inputs()), list(node.outputs()) flops_counter = handle_count(inputs, outputs) total_flop_counter += flops_counter global _HAS_ALREADY_SKIPPED if len(skipped_ops) > 0 and not _HAS_ALREADY_SKIPPED: _HAS_ALREADY_SKIPPED = True for op, freq in skipped_ops.items(): logging.warning("Skipped operation {} {} time(s)".format(op, freq)) # Convert flop count to gigaflops. final_count = defaultdict(float) for op in total_flop_counter: final_count[op] = total_flop_counter[op] / 1e9 return final_count
Given a model and an input to the model, compute the Gflops of the given model. Note the input should have a batch size of 1. Args: model (nn.Module): The model to compute flop counts. inputs (tuple): Inputs that are passed to `model` to count flops. Inputs need to be in a tuple. whitelist (list(str)): Whitelist of operations that will be counted. It needs to be a subset of _SUPPORTED_OPS. By default, the function computes flops for all supported operations. customized_ops (dict(str,Callable)) : A dictionary contains customized operations and their flop handles. If customized_ops contains an operation in _SUPPORTED_OPS, then the default handle in _SUPPORTED_OPS will be overwritten. Returns: defaultdict: A dictionary that records the number of gflops for each operation.
flop_count
python
IDEA-Research/DINO
tools/benchmark.py
https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py
Apache-2.0
def get_dataset(coco_path): """ Gets the COCO dataset used for computing the flops on """ class DummyArgs: pass args = DummyArgs() args.dataset_file = "coco" args.coco_path = coco_path args.masks = False dataset = build_dataset(image_set="val", args=args) return dataset
Gets the COCO dataset used for computing the flops on
get_dataset
python
IDEA-Research/DINO
tools/benchmark.py
https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py
Apache-2.0
def generalized_box_iou(boxes1, boxes2): """ Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) """ # degenerate boxes gives inf / nan results # so do an early check assert (boxes1[:, 2:] >= boxes1[:, :2]).all() assert (boxes2[:, 2:] >= boxes2[:, :2]).all() iou, union = box_iou(boxes1, boxes2) lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) wh = (rb - lt).clamp(min=0) # [N,M,2] area = wh[:, :, 0] * wh[:, :, 1] return iou - (area - union) / (area + 1e-6)
Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
generalized_box_iou
python
IDEA-Research/DINO
util/box_ops.py
https://github.com/IDEA-Research/DINO/blob/master/util/box_ops.py
Apache-2.0
def generalized_box_iou_pairwise(boxes1, boxes2): """ Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4 """ # degenerate boxes gives inf / nan results # so do an early check assert (boxes1[:, 2:] >= boxes1[:, :2]).all() assert (boxes2[:, 2:] >= boxes2[:, :2]).all() assert boxes1.shape == boxes2.shape iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4 lt = torch.min(boxes1[:, :2], boxes2[:, :2]) rb = torch.max(boxes1[:, 2:], boxes2[:, 2:]) wh = (rb - lt).clamp(min=0) # [N,2] area = wh[:, 0] * wh[:, 1] return iou - (area - union) / area
Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4
generalized_box_iou_pairwise
python
IDEA-Research/DINO
util/box_ops.py
https://github.com/IDEA-Research/DINO/blob/master/util/box_ops.py
Apache-2.0
def masks_to_boxes(masks): """Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format """ if masks.numel() == 0: return torch.zeros((0, 4), device=masks.device) h, w = masks.shape[-2:] y = torch.arange(0, h, dtype=torch.float) x = torch.arange(0, w, dtype=torch.float) y, x = torch.meshgrid(y, x) x_mask = (masks * x.unsqueeze(0)) x_max = x_mask.flatten(1).max(-1)[0] x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] y_mask = (masks * y.unsqueeze(0)) y_max = y_mask.flatten(1).max(-1)[0] y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] return torch.stack([x_min, y_min, x_max, y_max], 1)
Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format
masks_to_boxes
python
IDEA-Research/DINO
util/box_ops.py
https://github.com/IDEA-Research/DINO/blob/master/util/box_ops.py
Apache-2.0
def setup_logger( output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None ): """ Initialize the detectron2 logger and set its verbosity level to "INFO". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logger Returns: logging.Logger: a logger """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False if abbrev_name is None: abbrev_name = name plain_formatter = logging.Formatter( '[%(asctime)s.%(msecs)03d]: %(message)s', datefmt='%m/%d %H:%M:%S' ) # stdout logging: master only if distributed_rank == 0: ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) if color: formatter = _ColorfulFormatter( colored("[%(asctime)s.%(msecs)03d]: ", "green") + "%(message)s", datefmt="%m/%d %H:%M:%S", root_name=name, abbrev_name=str(abbrev_name), ) else: formatter = plain_formatter ch.setFormatter(formatter) logger.addHandler(ch) # file logging: all workers if output is not None: if output.endswith(".txt") or output.endswith(".log"): filename = output else: filename = os.path.join(output, "log.txt") if distributed_rank > 0: filename = filename + f".rank{distributed_rank}" os.makedirs(os.path.dirname(filename), exist_ok=True) fh = logging.StreamHandler(_cached_log_stream(filename)) fh.setLevel(logging.DEBUG) fh.setFormatter(plain_formatter) logger.addHandler(fh) return logger
Initialize the detectron2 logger and set its verbosity level to "INFO". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logger Returns: logging.Logger: a logger
setup_logger
python
IDEA-Research/DINO
util/logger.py
https://github.com/IDEA-Research/DINO/blob/master/util/logger.py
Apache-2.0
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # serialized to a Tensor buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to("cuda") # obtain Tensor size of each rank local_size = torch.tensor([tensor.numel()], device="cuda") size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # receiving Tensor from all ranks # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes tensor_list = [] for _ in size_list: tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) if local_size != max_size: padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
all_gather
python
IDEA-Research/DINO
util/misc.py
https://github.com/IDEA-Research/DINO/blob/master/util/misc.py
Apache-2.0
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that all processes have the averaged results. Returns a dict with the same fields as input_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return input_dict with torch.no_grad(): names = [] values = [] # sort the keys so that they are consistent across processes for k in sorted(input_dict.keys()): names.append(k) values.append(input_dict[k]) values = torch.stack(values, dim=0) dist.all_reduce(values) if average: values /= world_size reduced_dict = {k: v for k, v in zip(names, values)} return reduced_dict
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that all processes have the averaged results. Returns a dict with the same fields as input_dict, after reduction.
reduce_dict
python
IDEA-Research/DINO
util/misc.py
https://github.com/IDEA-Research/DINO/blob/master/util/misc.py
Apache-2.0
def to_img_list(self): """remove the padding and convert to img list Returns: [type]: [description] """ if self.tensors.dim() == 3: return self.to_img_list_single(self.tensors, self.mask) else: res = [] for i in range(self.tensors.shape[0]): tensor_i = self.tensors[i] mask_i = self.mask[i] res.append(self.to_img_list_single(tensor_i, mask_i)) return res
remove the padding and convert to img list Returns: [type]: [description]
to_img_list
python
IDEA-Research/DINO
util/misc.py
https://github.com/IDEA-Research/DINO/blob/master/util/misc.py
Apache-2.0
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" if target.numel() == 0: return [torch.zeros([], device=output.device)] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
Computes the precision@k for the specified values of k
accuracy
python
IDEA-Research/DINO
util/misc.py
https://github.com/IDEA-Research/DINO/blob/master/util/misc.py
Apache-2.0
def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor """ Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away. """ if __torchvision_need_compat_flag < 0.7: if input.numel() > 0: return torch.nn.functional.interpolate( input, size, scale_factor, mode, align_corners ) output_shape = _output_size(2, input, size, scale_factor) output_shape = list(input.shape[:-2]) + list(output_shape) return _new_empty_tensor(input, output_shape) else: return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away.
interpolate
python
IDEA-Research/DINO
util/misc.py
https://github.com/IDEA-Research/DINO/blob/master/util/misc.py
Apache-2.0
def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): ''' Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results. ''' func_name = "plot_utils.py::plot_logs" # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path, # convert single Path to list to avoid 'not iterable' error if not isinstance(logs, list): if isinstance(logs, PurePath): logs = [logs] print(f"{func_name} info: logs param expects a list argument, converted to list[Path].") else: raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \ Expect list[Path] or single Path obj, received {type(logs)}") # Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir for i, dir in enumerate(logs): if not isinstance(dir, PurePath): raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}") if not dir.exists(): raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}") # verify log_name exists fn = Path(dir / log_name) if not fn.exists(): print(f"-> missing {log_name}. Have you gotten to Epoch 1 in training?") print(f"--> full path of missing log file: {fn}") return # load log file(s) and plot dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs] fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5)) for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))): for j, field in enumerate(fields): if field == 'mAP': coco_eval = pd.DataFrame( np.stack(df.test_coco_eval_bbox.dropna().values)[:, 1] ).ewm(com=ewm_col).mean() axs[j].plot(coco_eval, c=color) else: df.interpolate().ewm(com=ewm_col).mean().plot( y=[f'train_{field}', f'test_{field}'], ax=axs[j], color=[color] * 2, style=['-', '--'] ) for ax, field in zip(axs, fields): if field == 'mAP': ax.legend([Path(p).name for p in logs]) ax.set_title(field) else: ax.legend([f'train', f'test']) ax.set_title(field) return fig, axs
Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results.
plot_logs
python
IDEA-Research/DINO
util/plot_utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/plot_utils.py
Apache-2.0
def _merge_a_into_b(a, b): """merge dict `a` into dict `b` (non-inplace). values in `a` will overwrite `b`. copy first to avoid inplace modification Args: a ([type]): [description] b ([type]): [description] Returns: [dict]: [description] """ if not isinstance(a, dict): return a b = b.copy() for k, v in a.items(): if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False): if not isinstance(b[k], dict) and not isinstance(b[k], list): # if : raise TypeError( f'{k}={v} in child config cannot inherit from base ' f'because {k} is a dict in the child config but is of ' f'type {type(b[k])} in base config. You may set ' f'`{DELETE_KEY}=True` to ignore the base config') b[k] = SLConfig._merge_a_into_b(v, b[k]) elif isinstance(b, list): try: _ = int(k) except: raise TypeError( f'b is a list, ' f'index {k} should be an int when input but {type(k)}' ) b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)]) else: b[k] = v return b
merge dict `a` into dict `b` (non-inplace). values in `a` will overwrite `b`. copy first to avoid inplace modification Args: a ([type]): [description] b ([type]): [description] Returns: [dict]: [description]
_merge_a_into_b
python
IDEA-Research/DINO
util/slconfig.py
https://github.com/IDEA-Research/DINO/blob/master/util/slconfig.py
Apache-2.0
def merge_from_dict(self, options): """Merge list into cfg_dict Merge the dict parsed by MultipleKVAction into this cfg. Examples: >>> options = {'model.backbone.depth': 50, ... 'model.backbone.with_cp':True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict( ... model=dict(backbone=dict(depth=50, with_cp=True))) Args: options (dict): dict of configs to merge from. """ option_cfg_dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split('.') for subkey in key_list[:-1]: d.setdefault(subkey, ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super(SLConfig, self).__getattribute__('_cfg_dict') super(SLConfig, self).__setattr__( '_cfg_dict', SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict))
Merge list into cfg_dict Merge the dict parsed by MultipleKVAction into this cfg. Examples: >>> options = {'model.backbone.depth': 50, ... 'model.backbone.with_cp':True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict( ... model=dict(backbone=dict(depth=50, with_cp=True))) Args: options (dict): dict of configs to merge from.
merge_from_dict
python
IDEA-Research/DINO
util/slconfig.py
https://github.com/IDEA-Research/DINO/blob/master/util/slconfig.py
Apache-2.0
def slload(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file. """ if isinstance(file, Path): file = str(file) if file_format is None and is_str(file): file_format = file.split('.')[-1] if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') handler = file_handlers[file_format] if is_str(file): obj = handler.load_from_path(file, **kwargs) elif hasattr(file, 'read'): obj = handler.load_from_fileobj(file, **kwargs) else: raise TypeError('"file" must be a filepath str or a file-object') return obj
Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file.
slload
python
IDEA-Research/DINO
util/slio.py
https://github.com/IDEA-Research/DINO/blob/master/util/slio.py
Apache-2.0
def sldump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dump to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. Returns: bool: True for success, False otherwise. """ if isinstance(file, Path): file = str(file) if file_format is None: if is_str(file): file_format = file.split('.')[-1] elif file is None: raise ValueError( 'file_format must be specified since file is None') if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') handler = file_handlers[file_format] if file is None: return handler.dump_to_str(obj, **kwargs) elif is_str(file): handler.dump_to_path(obj, file, **kwargs) elif hasattr(file, 'write'): handler.dump_to_fileobj(obj, file, **kwargs) else: raise TypeError('"file" must be a filename str or a file-object')
Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dump to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. Returns: bool: True for success, False otherwise.
sldump
python
IDEA-Research/DINO
util/slio.py
https://github.com/IDEA-Research/DINO/blob/master/util/slio.py
Apache-2.0
def get_gaussian_mean(x, axis, other_axis, softmax=True): """ Args: x (float): Input images(BxCxHxW) axis (int): The index for weighted mean other_axis (int): The other index Returns: weighted index for axis, BxC """ mat2line = torch.sum(x, axis=other_axis) # mat2line = mat2line / mat2line.mean() * 10 if softmax: u = torch.softmax(mat2line, axis=2) else: u = mat2line / (mat2line.sum(2, keepdim=True) + 1e-6) size = x.shape[axis] ind = torch.linspace(0, 1, size).to(x.device) batch = x.shape[0] channel = x.shape[1] index = ind.repeat([batch, channel, 1]) mean_position = torch.sum(index * u, dim=2) return mean_position
Args: x (float): Input images(BxCxHxW) axis (int): The index for weighted mean other_axis (int): The other index Returns: weighted index for axis, BxC
get_gaussian_mean
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def get_expected_points_from_map(hm, softmax=True): """get_gaussian_map_from_points B,C,H,W -> B,N,2 float(0, 1) float(0, 1) softargmax function Args: hm (float): Input images(BxCxHxW) Returns: weighted index for axis, BxCx2. float between 0 and 1. """ # hm = 10*hm B,C,H,W = hm.shape y_mean = get_gaussian_mean(hm, 2, 3, softmax=softmax) # B,C x_mean = get_gaussian_mean(hm, 3, 2, softmax=softmax) # B,C # return torch.cat((x_mean.unsqueeze(-1), y_mean.unsqueeze(-1)), 2) return torch.stack([x_mean, y_mean], dim=2)
get_gaussian_map_from_points B,C,H,W -> B,N,2 float(0, 1) float(0, 1) softargmax function Args: hm (float): Input images(BxCxHxW) Returns: weighted index for axis, BxCx2. float between 0 and 1.
get_expected_points_from_map
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def get_raw_dict(args): """ return the dicf contained in args. e.g: >>> with open(path, 'w') as f: json.dump(get_raw_dict(args), f, indent=2) """ if isinstance(args, argparse.Namespace): return vars(args) elif isinstance(args, dict): return args elif isinstance(args, SLConfig): return args._cfg_dict else: raise NotImplementedError("Unknown type {}".format(type(args)))
return the dicf contained in args. e.g: >>> with open(path, 'w') as f: json.dump(get_raw_dict(args), f, indent=2)
get_raw_dict
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def __nice__(self): """str: a "nice" summary string describing this module""" if hasattr(self, '__len__'): # It is a common pattern for objects to use __len__ in __nice__ # As a convenience we define a default __nice__ for these objects return str(len(self)) else: # In all other cases force the subclass to overload __nice__ raise NotImplementedError( f'Define the __nice__ method for {self.__class__!r}')
str: a "nice" summary string describing this module
__nice__
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def __repr__(self): """str: the string of the module""" try: nice = self.__nice__() classname = self.__class__.__name__ return f'<{classname}({nice}) at {hex(id(self))}>' except NotImplementedError as ex: warnings.warn(str(ex), category=RuntimeWarning) return object.__repr__(self)
str: the string of the module
__repr__
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def __str__(self): """str: the string of the module""" try: classname = self.__class__.__name__ nice = self.__nice__() return f'<{classname}({nice})>' except NotImplementedError as ex: warnings.warn(str(ex), category=RuntimeWarning) return object.__repr__(self)
str: the string of the module
__str__
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def ensure_rng(rng=None): """Coerces input into a random number generator. If the input is None, then a global random state is returned. If the input is a numeric value, then that is used as a seed to construct a random state. Otherwise the input is returned as-is. Adapted from [1]_. Args: rng (int | numpy.random.RandomState | None): if None, then defaults to the global rng. Otherwise this can be an integer or a RandomState class Returns: (numpy.random.RandomState) : rng - a numpy random number generator References: .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501 """ if rng is None: rng = np.random.mtrand._rand elif isinstance(rng, int): rng = np.random.RandomState(rng) else: rng = rng return rng
Coerces input into a random number generator. If the input is None, then a global random state is returned. If the input is a numeric value, then that is used as a seed to construct a random state. Otherwise the input is returned as-is. Adapted from [1]_. Args: rng (int | numpy.random.RandomState | None): if None, then defaults to the global rng. Otherwise this can be an integer or a RandomState class Returns: (numpy.random.RandomState) : rng - a numpy random number generator References: .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501
ensure_rng
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def random_boxes(num=1, scale=1, rng=None): """Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor([[280.9925, 278.9802, 308.6148, 366.1769], [216.9113, 330.6978, 224.0446, 456.5878], [405.3632, 196.3221, 493.3953, 270.7942]]) """ rng = ensure_rng(rng) tlbr = rng.rand(num, 4).astype(np.float32) tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2]) tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3]) br_x = np.maximum(tlbr[:, 0], tlbr[:, 2]) br_y = np.maximum(tlbr[:, 1], tlbr[:, 3]) tlbr[:, 0] = tl_x * scale tlbr[:, 1] = tl_y * scale tlbr[:, 2] = br_x * scale tlbr[:, 3] = br_y * scale boxes = torch.from_numpy(tlbr) return boxes
Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor([[280.9925, 278.9802, 308.6148, 366.1769], [216.9113, 330.6978, 224.0446, 456.5878], [405.3632, 196.3221, 493.3953, 270.7942]])
random_boxes
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def update(self, new_res, epoch, is_ema=False): """ return if the results is the best. """ if not self.use_ema: return self.best_all.update(new_res, epoch) else: if is_ema: self.best_ema.update(new_res, epoch) return self.best_all.update(new_res, epoch) else: self.best_regular.update(new_res, epoch) return self.best_all.update(new_res, epoch)
return if the results is the best.
update
python
IDEA-Research/DINO
util/utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/utils.py
Apache-2.0
def visualize(self, img, tgt, caption=None, dpi=120, savedir=None, show_in_console=True): """ img: tensor(3, H, W) tgt: make sure they are all on cpu. must have items: 'image_id', 'boxes', 'size' """ plt.figure(dpi=dpi) plt.rcParams['font.size'] = '5' ax = plt.gca() img = renorm(img).permute(1, 2, 0) ax.imshow(img) self.addtgt(tgt) if show_in_console: plt.show() if savedir is not None: if caption is None: savename = '{}/{}-{}.png'.format(savedir, int(tgt['image_id']), str(datetime.datetime.now()).replace(' ', '-')) else: savename = '{}/{}-{}-{}.png'.format(savedir, caption, int(tgt['image_id']), str(datetime.datetime.now()).replace(' ', '-')) print("savename: {}".format(savename)) os.makedirs(os.path.dirname(savename), exist_ok=True) plt.savefig(savename) plt.close()
img: tensor(3, H, W) tgt: make sure they are all on cpu. must have items: 'image_id', 'boxes', 'size'
visualize
python
IDEA-Research/DINO
util/visualizer.py
https://github.com/IDEA-Research/DINO/blob/master/util/visualizer.py
Apache-2.0
def add_box_to_img(img, boxes, colorlist, brands=None): """[summary] Args: img ([type]): np.array, H,W,3 boxes ([type]): list of list(4) colorlist: list of colors. brands: text. Return: img: np.array. H,W,3. """ H, W = img.shape[:2] for _i, (box, color) in enumerate(zip(boxes, colorlist)): x, y, w, h = box[0] * W, box[1] * H, box[2] * W, box[3] * H img = cv2.rectangle(img.copy(), (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), color, 2) if brands is not None: brand = brands[_i] org = (int(x-w/2), int(y+h/2)) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.5 thickness = 1 img = cv2.putText(img.copy(), str(brand), org, font, fontScale, color, thickness, cv2.LINE_AA) return img
[summary] Args: img ([type]): np.array, H,W,3 boxes ([type]): list of list(4) colorlist: list of colors. brands: text. Return: img: np.array. H,W,3.
add_box_to_img
python
IDEA-Research/DINO
util/vis_utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py
Apache-2.0
def plot_dual_img(img, boxes, labels, idxs, probs=None): """[summary] Args: img ([type]): 3,H,W. tensor. boxes (): tensor(Kx4) or list of tensor(1x4). labels ([type]): list of ints. idxs ([type]): list of ints. probs (optional): listof floats. Returns: img_classcolor: np.array. H,W,3. img with class-wise label. img_seqcolor: np.array. H,W,3. img with seq-wise label. """ boxes = [i.cpu().tolist() for i in boxes] img = (renorm(img.cpu()).permute(1,2,0).numpy() * 255).astype(np.uint8) # plot with class class_colors = [_color_getter(i) for i in labels] if probs is not None: brands = ["{},{:.2f}".format(j,k) for j,k in zip(labels, probs)] else: brands = labels img_classcolor = add_box_to_img(img, boxes, class_colors, brands=brands) # plot with seq seq_colors = [_color_getter((i * 11) % 100) for i in idxs] img_seqcolor = add_box_to_img(img, boxes, seq_colors, brands=idxs) return img_classcolor, img_seqcolor
[summary] Args: img ([type]): 3,H,W. tensor. boxes (): tensor(Kx4) or list of tensor(1x4). labels ([type]): list of ints. idxs ([type]): list of ints. probs (optional): listof floats. Returns: img_classcolor: np.array. H,W,3. img with class-wise label. img_seqcolor: np.array. H,W,3. img with seq-wise label.
plot_dual_img
python
IDEA-Research/DINO
util/vis_utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py
Apache-2.0
def plot_raw_img(img, boxes, labels): """[summary] Args: img ([type]): 3,H,W. tensor. boxes ([type]): Kx4. tensor labels ([type]): K. tensor. return: img: np.array. H,W,3. img with bbox annos. """ img = (renorm(img.cpu()).permute(1,2,0).numpy() * 255).astype(np.uint8) H, W = img.shape[:2] for box, label in zip(boxes.tolist(), labels.tolist()): x, y, w, h = box[0] * W, box[1] * H, box[2] * W, box[3] * H img = cv2.rectangle(img.copy(), (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), _color_getter(label), 2) # add text org = (int(x-w/2), int(y+h/2)) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 1 thickness = 1 img = cv2.putText(img.copy(), str(label), org, font, fontScale, _color_getter(label), thickness, cv2.LINE_AA) return img
[summary] Args: img ([type]): 3,H,W. tensor. boxes ([type]): Kx4. tensor labels ([type]): K. tensor. return: img: np.array. H,W,3. img with bbox annos.
plot_raw_img
python
IDEA-Research/DINO
util/vis_utils.py
https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py
Apache-2.0
def capture_logger(name): """Context manager to capture a logger output with a StringIO stream.""" import logging logger = logging.getLogger(name) try: import StringIO stream = StringIO.StringIO() except ImportError: stream = io.StringIO() handler = logging.StreamHandler(stream) logger.addHandler(handler) try: yield stream finally: logger.removeHandler(handler)
Context manager to capture a logger output with a StringIO stream.
capture_logger
python
fonttools/fonttools
setup.py
https://github.com/fonttools/fonttools/blob/master/setup.py
MIT
def git_tag(self, version, message, sign=False): """Create annotated git tag with given 'version' and 'message'. Optionally 'sign' the tag with the user's GPG key. """ log.info( "creating %s git tag '%s'" % ("signed" if sign else "annotated", version) ) if self.dry_run: return # create an annotated (or signed) tag from the new version tag_opt = "-s" if sign else "-a" tag_name = self.tag_name.format(new_version=version) proc = sp.Popen(["git", "tag", tag_opt, "-F", "-", tag_name], stdin=sp.PIPE) # use the latest changes from the changelog file as the tag message tag_message = "%s\n\n%s" % (tag_name, message) proc.communicate(tag_message.encode("utf-8")) if proc.returncode != 0: sys.exit(proc.returncode)
Create annotated git tag with given 'version' and 'message'. Optionally 'sign' the tag with the user's GPG key.
git_tag
python
fonttools/fonttools
setup.py
https://github.com/fonttools/fonttools/blob/master/setup.py
MIT
def bumpversion(self, part, commit=False, message=None, allow_dirty=None): """Run bumpversion.main() with the specified arguments, and return the new computed version string (cf. 'bumpversion --help' for more info) """ import bumpversion.cli args = ( (["--verbose"] if self.verbose > 1 else []) + (["--dry-run"] if self.dry_run else []) + (["--allow-dirty"] if (allow_dirty or self.allow_dirty) else []) + (["--commit"] if commit else ["--no-commit"]) + (["--message", message] if message is not None else []) + ["--list", part] ) log.debug("$ bumpversion %s" % " ".join(a.replace(" ", "\\ ") for a in args)) with capture_logger("bumpversion.list") as out: bumpversion.cli.main(args) last_line = out.getvalue().splitlines()[-1] new_version = last_line.replace("new_version=", "") return new_version
Run bumpversion.main() with the specified arguments, and return the new computed version string (cf. 'bumpversion --help' for more info)
bumpversion
python
fonttools/fonttools
setup.py
https://github.com/fonttools/fonttools/blob/master/setup.py
MIT
def format_changelog(self, version): """Write new header at beginning of changelog file with the specified 'version' and the current date. Return the changelog content for the current release. """ from datetime import datetime log.info("formatting changelog") changes = [] with io.open(self.changelog_name, "r+", encoding="utf-8") as f: for ln in f: if self.version_RE.match(ln): break else: changes.append(ln) if not self.dry_run: f.seek(0) content = f.read() date = datetime.today().strftime(self.date_fmt) f.seek(0) header = self.header_fmt % (version, date) f.write(header + "\n" + "-" * len(header) + "\n\n" + content) return "".join(changes)
Write new header at beginning of changelog file with the specified 'version' and the current date. Return the changelog content for the current release.
format_changelog
python
fonttools/fonttools
setup.py
https://github.com/fonttools/fonttools/blob/master/setup.py
MIT
def __init__(self, path=None): """AFM file reader. Instantiating an object with a path name will cause the file to be opened, read, and parsed. Alternatively the path can be left unspecified, and a file can be parsed later with the :meth:`read` method.""" self._attrs = {} self._chars = {} self._kerning = {} self._index = {} self._comments = [] self._composites = {} if path is not None: self.read(path)
AFM file reader. Instantiating an object with a path name will cause the file to be opened, read, and parsed. Alternatively the path can be left unspecified, and a file can be parsed later with the :meth:`read` method.
__init__
python
fonttools/fonttools
Lib/fontTools/afmLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py
MIT
def write(self, path, sep="\r"): """Writes out an AFM font to the given path.""" import time lines = [ "StartFontMetrics 2.0", "Comment Generated by afmLib; at %s" % (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))), ] # write comments, assuming (possibly wrongly!) they should # all appear at the top for comment in self._comments: lines.append("Comment " + comment) # write attributes, first the ones we know about, in # a preferred order attrs = self._attrs for attr in preferredAttributeOrder: if attr in attrs: value = attrs[attr] if attr == "FontBBox": value = "%s %s %s %s" % value lines.append(attr + " " + str(value)) # then write the attributes we don't know about, # in alphabetical order items = sorted(attrs.items()) for attr, value in items: if attr in preferredAttributeOrder: continue lines.append(attr + " " + str(value)) # write char metrics lines.append("StartCharMetrics " + repr(len(self._chars))) items = [ (charnum, (charname, width, box)) for charname, (charnum, width, box) in self._chars.items() ] def myKey(a): """Custom key function to make sure unencoded chars (-1) end up at the end of the list after sorting.""" if a[0] == -1: a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number return a items.sort(key=myKey) for charnum, (charname, width, (l, b, r, t)) in items: lines.append( "C %d ; WX %d ; N %s ; B %d %d %d %d ;" % (charnum, width, charname, l, b, r, t) ) lines.append("EndCharMetrics") # write kerning info lines.append("StartKernData") lines.append("StartKernPairs " + repr(len(self._kerning))) items = sorted(self._kerning.items()) for (leftchar, rightchar), value in items: lines.append("KPX %s %s %d" % (leftchar, rightchar, value)) lines.append("EndKernPairs") lines.append("EndKernData") if self._composites: composites = sorted(self._composites.items()) lines.append("StartComposites %s" % len(self._composites)) for charname, components in composites: line = "CC %s %s ;" % (charname, len(components)) for basechar, xoffset, yoffset in components: line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset) lines.append(line) lines.append("EndComposites") lines.append("EndFontMetrics") writelines(path, lines, sep)
Writes out an AFM font to the given path.
write
python
fonttools/fonttools
Lib/fontTools/afmLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py
MIT
def myKey(a): """Custom key function to make sure unencoded chars (-1) end up at the end of the list after sorting.""" if a[0] == -1: a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number return a
Custom key function to make sure unencoded chars (-1) end up at the end of the list after sorting.
myKey
python
fonttools/fonttools
Lib/fontTools/afmLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py
MIT
def _uniToUnicode(component): """Helper for toUnicode() to handle "uniABCD" components.""" match = _re_uni.match(component) if match is None: return None digits = match.group(1) if len(digits) % 4 != 0: return None chars = [int(digits[i : i + 4], 16) for i in range(0, len(digits), 4)] if any(c >= 0xD800 and c <= 0xDFFF for c in chars): # The AGL specification explicitly excluded surrogate pairs. return None return "".join([chr(c) for c in chars])
Helper for toUnicode() to handle "uniABCD" components.
_uniToUnicode
python
fonttools/fonttools
Lib/fontTools/agl.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/agl.py
MIT
def _uToUnicode(component): """Helper for toUnicode() to handle "u1ABCD" components.""" match = _re_u.match(component) if match is None: return None digits = match.group(1) try: value = int(digits, 16) except ValueError: return None if (value >= 0x0000 and value <= 0xD7FF) or (value >= 0xE000 and value <= 0x10FFFF): return chr(value) return None
Helper for toUnicode() to handle "u1ABCD" components.
_uToUnicode
python
fonttools/fonttools
Lib/fontTools/agl.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/agl.py
MIT
def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0): """Initialize a FontBuilder instance. If the `font` argument is not given, a new `TTFont` will be constructed, and `unitsPerEm` must be given. If `isTTF` is True, the font will be a glyf-based TTF; if `isTTF` is False it will be a CFF-based OTF. The `glyphDataFormat` argument corresponds to the `head` table field that defines the format of the TrueType `glyf` table (default=0). TrueType glyphs historically can only contain quadratic splines and static components, but there's a proposal to add support for cubic Bezier curves as well as variable composites/components at https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md You can experiment with the new features by setting `glyphDataFormat` to 1. A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added that contain cubic splines or varcomposites. This is to prevent accidentally creating fonts that are incompatible with existing TrueType implementations. If `font` is given, it must be a `TTFont` instance and `unitsPerEm` must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored. """ if font is None: self.font = TTFont(recalcTimestamp=False) self.isTTF = isTTF now = timestampNow() assert unitsPerEm is not None self.setupHead( unitsPerEm=unitsPerEm, created=now, modified=now, glyphDataFormat=glyphDataFormat, ) self.setupMaxp() else: assert unitsPerEm is None self.font = font self.isTTF = "glyf" in font
Initialize a FontBuilder instance. If the `font` argument is not given, a new `TTFont` will be constructed, and `unitsPerEm` must be given. If `isTTF` is True, the font will be a glyf-based TTF; if `isTTF` is False it will be a CFF-based OTF. The `glyphDataFormat` argument corresponds to the `head` table field that defines the format of the TrueType `glyf` table (default=0). TrueType glyphs historically can only contain quadratic splines and static components, but there's a proposal to add support for cubic Bezier curves as well as variable composites/components at https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md You can experiment with the new features by setting `glyphDataFormat` to 1. A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added that contain cubic splines or varcomposites. This is to prevent accidentally creating fonts that are incompatible with existing TrueType implementations. If `font` is given, it must be a `TTFont` instance and `unitsPerEm` must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored.
__init__
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False): """Build the `cmap` table for the font. The `cmapping` argument should be a dict mapping unicode code points as integers to glyph names. The `uvs` argument, when passed, must be a list of tuples, describing Unicode Variation Sequences. These tuples have three elements: (unicodeValue, variationSelector, glyphName) `unicodeValue` and `variationSelector` are integer code points. `glyphName` may be None, to indicate this is the default variation. Text processors will then use the cmap to find the glyph name. Each Unicode Variation Sequence should be an officially supported sequence, but this is not policed. """ subTables = [] highestUnicode = max(cmapping) if cmapping else 0 if highestUnicode > 0xFFFF: cmapping_3_1 = dict((k, v) for k, v in cmapping.items() if k < 0x10000) subTable_3_10 = buildCmapSubTable(cmapping, 12, 3, 10) subTables.append(subTable_3_10) else: cmapping_3_1 = cmapping format = 4 subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1) try: subTable_3_1.compile(self.font) except struct.error: # format 4 overflowed, fall back to format 12 if not allowFallback: raise ValueError( "cmap format 4 subtable overflowed; sort glyph order by unicode to fix." ) format = 12 subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1) subTables.append(subTable_3_1) subTable_0_3 = buildCmapSubTable(cmapping_3_1, format, 0, 3) subTables.append(subTable_0_3) if uvs is not None: uvsDict = {} for unicodeValue, variationSelector, glyphName in uvs: if cmapping.get(unicodeValue) == glyphName: # this is a default variation glyphName = None if variationSelector not in uvsDict: uvsDict[variationSelector] = [] uvsDict[variationSelector].append((unicodeValue, glyphName)) uvsSubTable = buildCmapSubTable({}, 14, 0, 5) uvsSubTable.uvsDict = uvsDict subTables.append(uvsSubTable) self.font["cmap"] = newTable("cmap") self.font["cmap"].tableVersion = 0 self.font["cmap"].tables = subTables
Build the `cmap` table for the font. The `cmapping` argument should be a dict mapping unicode code points as integers to glyph names. The `uvs` argument, when passed, must be a list of tuples, describing Unicode Variation Sequences. These tuples have three elements: (unicodeValue, variationSelector, glyphName) `unicodeValue` and `variationSelector` are integer code points. `glyphName` may be None, to indicate this is the default variation. Text processors will then use the cmap to find the glyph name. Each Unicode Variation Sequence should be an officially supported sequence, but this is not policed.
setupCharacterMap
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupOS2(self, **values): """Create a new `OS/2` table and initialize it with default values, which can be overridden by keyword arguments. """ self._initTableWithValues("OS/2", _OS2Defaults, values) if "xAvgCharWidth" not in values: assert ( "hmtx" in self.font ), "the 'hmtx' table must be setup before the 'OS/2' table" self.font["OS/2"].recalcAvgCharWidth(self.font) if not ( "ulUnicodeRange1" in values or "ulUnicodeRange2" in values or "ulUnicodeRange3" in values or "ulUnicodeRange3" in values ): assert ( "cmap" in self.font ), "the 'cmap' table must be setup before the 'OS/2' table" self.font["OS/2"].recalcUnicodeRanges(self.font)
Create a new `OS/2` table and initialize it with default values, which can be overridden by keyword arguments.
setupOS2
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True): """Create the `glyf` table from a dict, that maps glyph names to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`. If `calcGlyphBounds` is True, the bounds of all glyphs will be calculated. Only pass False if your glyph objects already have their bounding box values set. If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains cubic curves or is a variable composite but head.glyphDataFormat=0. Set it to False to skip the check if you know in advance all the glyphs are compatible with the specified glyphDataFormat. """ assert self.isTTF if validateGlyphFormat and self.font["head"].glyphDataFormat == 0: for name, g in glyphs.items(): if g.numberOfContours > 0 and any(f & flagCubic for f in g.flags): raise ValueError( f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; " "either convert to quadratics with cu2qu or set glyphDataFormat=1." ) self.font["loca"] = newTable("loca") self.font["glyf"] = newTable("glyf") self.font["glyf"].glyphs = glyphs if hasattr(self.font, "glyphOrder"): self.font["glyf"].glyphOrder = self.font.glyphOrder if calcGlyphBounds: self.calcGlyphBounds()
Create the `glyf` table from a dict, that maps glyph names to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`. If `calcGlyphBounds` is True, the bounds of all glyphs will be calculated. Only pass False if your glyph objects already have their bounding box values set. If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains cubic curves or is a variable composite but head.glyphDataFormat=0. Set it to False to skip the check if you know in advance all the glyphs are compatible with the specified glyphDataFormat.
setupGlyf
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupAvar(self, axes, mappings=None): """Adds an axis variations table to the font. Args: axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects. """ from .varLib import _add_avar if "fvar" not in self.font: raise KeyError("'fvar' table is missing; can't add 'avar'.") axisTags = [axis.axisTag for axis in self.font["fvar"].axes] axes = OrderedDict(enumerate(axes)) # Only values are used _add_avar(self.font, axes, mappings, axisTags)
Adds an axis variations table to the font. Args: axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
setupAvar
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def calcGlyphBounds(self): """Calculate the bounding boxes of all glyphs in the `glyf` table. This is usually not called explicitly by client code. """ glyphTable = self.font["glyf"] for glyph in glyphTable.glyphs.values(): glyph.recalcBounds(glyphTable)
Calculate the bounding boxes of all glyphs in the `glyf` table. This is usually not called explicitly by client code.
calcGlyphBounds
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupPost(self, keepGlyphNames=True, **values): """Create a new `post` table and initialize it with default values, which can be overridden by keyword arguments. """ isCFF2 = "CFF2" in self.font postTable = self._initTableWithValues("post", _postDefaults, values) if (self.isTTF or isCFF2) and keepGlyphNames: postTable.formatType = 2.0 postTable.extraNames = [] postTable.mapping = {} else: postTable.formatType = 3.0
Create a new `post` table and initialize it with default values, which can be overridden by keyword arguments.
setupPost
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupMaxp(self): """Create a new `maxp` table. This is called implicitly by FontBuilder itself and is usually not called by client code. """ if self.isTTF: defaults = _maxpDefaultsTTF else: defaults = _maxpDefaultsOTF self._initTableWithValues("maxp", defaults, {})
Create a new `maxp` table. This is called implicitly by FontBuilder itself and is usually not called by client code.
setupMaxp
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupDummyDSIG(self): """This adds an empty DSIG table to the font to make some MS applications happy. This does not properly sign the font. """ values = dict( ulVersion=1, usFlag=0, usNumSigs=0, signatureRecords=[], ) self._initTableWithValues("DSIG", {}, values)
This adds an empty DSIG table to the font to make some MS applications happy. This does not properly sign the font.
setupDummyDSIG
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False): """Add OpenType features to the font from a string containing Feature File syntax. The `filename` argument is used in error messages and to determine where to look for "include" files. The optional `tables` argument can be a list of OTL tables tags to build, allowing the caller to only build selected OTL tables. See `fontTools.feaLib` for details. The optional `debug` argument controls whether to add source debugging information to the font in the `Debg` table. """ from .feaLib.builder import addOpenTypeFeaturesFromString addOpenTypeFeaturesFromString( self.font, features, filename=filename, tables=tables, debug=debug )
Add OpenType features to the font from a string containing Feature File syntax. The `filename` argument is used in error messages and to determine where to look for "include" files. The optional `tables` argument can be a list of OTL tables tags to build, allowing the caller to only build selected OTL tables. See `fontTools.feaLib` for details. The optional `debug` argument controls whether to add source debugging information to the font in the `Debg` table.
addOpenTypeFeatures
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"): """Add conditional substitutions to a Variable Font. See `fontTools.varLib.featureVars.addFeatureVariations`. """ from .varLib import featureVars if "fvar" not in self.font: raise KeyError("'fvar' table is missing; can't add FeatureVariations.") featureVars.addFeatureVariations( self.font, conditionalSubstitutions, featureTag=featureTag )
Add conditional substitutions to a Variable Font. See `fontTools.varLib.featureVars.addFeatureVariations`.
addFeatureVariations
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupCOLR( self, colorLayers, version=None, varStore=None, varIndexMap=None, clipBoxes=None, allowLayerReuse=True, ): """Build new COLR table using color layers dictionary. Cf. `fontTools.colorLib.builder.buildCOLR`. """ from fontTools.colorLib.builder import buildCOLR glyphMap = self.font.getReverseGlyphMap() self.font["COLR"] = buildCOLR( colorLayers, version=version, glyphMap=glyphMap, varStore=varStore, varIndexMap=varIndexMap, clipBoxes=clipBoxes, allowLayerReuse=allowLayerReuse, )
Build new COLR table using color layers dictionary. Cf. `fontTools.colorLib.builder.buildCOLR`.
setupCOLR
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupCPAL( self, palettes, paletteTypes=None, paletteLabels=None, paletteEntryLabels=None, ): """Build new CPAL table using list of palettes. Optionally build CPAL v1 table using paletteTypes, paletteLabels and paletteEntryLabels. Cf. `fontTools.colorLib.builder.buildCPAL`. """ from fontTools.colorLib.builder import buildCPAL self.font["CPAL"] = buildCPAL( palettes, paletteTypes=paletteTypes, paletteLabels=paletteLabels, paletteEntryLabels=paletteEntryLabels, nameTable=self.font.get("name"), )
Build new CPAL table using list of palettes. Optionally build CPAL v1 table using paletteTypes, paletteLabels and paletteEntryLabels. Cf. `fontTools.colorLib.builder.buildCPAL`.
setupCPAL
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def setupStat(self, axes, locations=None, elidedFallbackName=2): """Build a new 'STAT' table. See `fontTools.otlLib.builder.buildStatTable` for details about the arguments. """ from .otlLib.builder import buildStatTable assert "name" in self.font, "name must to be set up first" buildStatTable( self.font, axes, locations, elidedFallbackName, macNames=any(nr.platformID == 1 for nr in self.font["name"].names), )
Build a new 'STAT' table. See `fontTools.otlLib.builder.buildStatTable` for details about the arguments.
setupStat
python
fonttools/fonttools
Lib/fontTools/fontBuilder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py
MIT
def main(args=None): """Convert OpenType fonts to XML and back""" from fontTools import configLogger if args is None: args = sys.argv[1:] try: jobs, options = parseOptions(args) except getopt.GetoptError as e: print("%s\nERROR: %s" % (__doc__, e), file=sys.stderr) sys.exit(2) configLogger(level=options.logLevel) try: process(jobs, options) except KeyboardInterrupt: log.error("(Cancelled.)") sys.exit(1) except SystemExit: raise except TTLibError as e: log.error(e) sys.exit(1) except: log.exception("Unhandled exception has occurred") sys.exit(1)
Convert OpenType fonts to XML and back
main
python
fonttools/fonttools
Lib/fontTools/ttx.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttx.py
MIT
def _convertCFF2ToCFF(cff, otFont): """Converts this object from CFF2 format to CFF format. This conversion is done 'in-place'. The conversion cannot be reversed. The CFF2 font cannot be variable. (TODO Accept those and convert to the default instance?) This assumes a decompiled CFF table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)""" cff.major = 1 topDictData = TopDictIndex(None) for item in cff.topDictIndex: # Iterate over, such that all are decompiled item.cff2GetGlyphOrder = None topDictData.append(item) cff.topDictIndex = topDictData topDict = topDictData[0] if hasattr(topDict, "VarStore"): raise ValueError("Variable CFF2 font cannot be converted to CFF format.") opOrder = buildOrder(topDictOperators) topDict.order = opOrder for key in topDict.rawDict.keys(): if key not in opOrder: del topDict.rawDict[key] if hasattr(topDict, key): delattr(topDict, key) fdArray = topDict.FDArray charStrings = topDict.CharStrings defaults = buildDefaults(privateDictOperators) order = buildOrder(privateDictOperators) for fd in fdArray: fd.setCFF2(False) privateDict = fd.Private privateDict.order = order for key in order: if key not in privateDict.rawDict and key in defaults: privateDict.rawDict[key] = defaults[key] for key in privateDict.rawDict.keys(): if key not in order: del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) for cs in charStrings.values(): cs.decompile() cs.program.append("endchar") for subrSets in [cff.GlobalSubrs] + [ getattr(fd.Private, "Subrs", []) for fd in fdArray ]: for cs in subrSets: cs.program.append("return") # Add (optimal) width to CharStrings that need it. widths = defaultdict(list) metrics = otFont["hmtx"].metrics for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) if fdIndex == None: fdIndex = 0 widths[fdIndex].append(metrics[glyphName][0]) for fdIndex, widthList in widths.items(): bestDefault, bestNominal = optimizeWidths(widthList) private = fdArray[fdIndex].Private private.defaultWidthX = bestDefault private.nominalWidthX = bestNominal for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) if fdIndex == None: fdIndex = 0 private = fdArray[fdIndex].Private width = metrics[glyphName][0] if width != private.defaultWidthX: cs.program.insert(0, width - private.nominalWidthX) mapping = { name: ("cid" + str(n) if n else ".notdef") for n, name in enumerate(topDict.charset) } topDict.charset = [ "cid" + str(n) if n else ".notdef" for n in range(len(topDict.charset)) ] charStrings.charStrings = { mapping[name]: v for name, v in charStrings.charStrings.items() } # I'm not sure why the following is *not* necessary. And it breaks # the output if I add it. # topDict.ROS = ("Adobe", "Identity", 0)
Converts this object from CFF2 format to CFF format. This conversion is done 'in-place'. The conversion cannot be reversed. The CFF2 font cannot be variable. (TODO Accept those and convert to the default instance?) This assumes a decompiled CFF table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)
_convertCFF2ToCFF
python
fonttools/fonttools
Lib/fontTools/cffLib/CFF2ToCFF.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFF2ToCFF.py
MIT
def main(args=None): """Convert CFF OTF font to CFF2 OTF font""" if args is None: import sys args = sys.argv[1:] import argparse parser = argparse.ArgumentParser( "fonttools cffLib.CFFToCFF2", description="Upgrade a CFF font to CFF2.", ) parser.add_argument( "input", metavar="INPUT.ttf", help="Input OTF file with CFF table." ) parser.add_argument( "-o", "--output", metavar="OUTPUT.ttf", default=None, help="Output instance OTF file (default: INPUT-CFF2.ttf).", ) parser.add_argument( "--no-recalc-timestamp", dest="recalc_timestamp", action="store_false", help="Don't set the output font's timestamp to the current time.", ) loggingGroup = parser.add_mutually_exclusive_group(required=False) loggingGroup.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) loggingGroup.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args) from fontTools import configLogger configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") ) import os infile = options.input if not os.path.isfile(infile): parser.error("No such file '{}'".format(infile)) outfile = ( makeOutputFileName(infile, overWrite=True, suffix="-CFF") if not options.output else options.output ) font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False) convertCFF2ToCFF(font) log.info( "Saving %s", outfile, ) font.save(outfile)
Convert CFF OTF font to CFF2 OTF font
main
python
fonttools/fonttools
Lib/fontTools/cffLib/CFF2ToCFF.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFF2ToCFF.py
MIT
def _convertCFFToCFF2(cff, otFont): """Converts this object from CFF format to CFF2 format. This conversion is done 'in-place'. The conversion cannot be reversed. This assumes a decompiled CFF table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)""" # Clean up T2CharStrings topDict = cff.topDictIndex[0] fdArray = topDict.FDArray if hasattr(topDict, "FDArray") else None charStrings = topDict.CharStrings globalSubrs = cff.GlobalSubrs localSubrs = ( [getattr(fd.Private, "Subrs", []) for fd in fdArray] if fdArray else ( [topDict.Private.Subrs] if hasattr(topDict, "Private") and hasattr(topDict.Private, "Subrs") else [] ) ) for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) cs.decompile() # Clean up subroutines first for subrs in [globalSubrs] + localSubrs: for subr in subrs: program = subr.program i = j = len(program) try: i = program.index("return") except ValueError: pass try: j = program.index("endchar") except ValueError: pass program[min(i, j) :] = [] # Clean up glyph charstrings removeUnusedSubrs = False nominalWidthXError = _NominalWidthUsedError() for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) program = cs.program thisLocalSubrs = ( localSubrs[fdIndex] if fdIndex is not None else ( getattr(topDict.Private, "Subrs", []) if hasattr(topDict, "Private") else [] ) ) # Intentionally use custom type for nominalWidthX, such that any # CharString that has an explicit width encoded will throw back to us. extractor = T2WidthExtractor( thisLocalSubrs, globalSubrs, nominalWidthXError, 0, ) try: extractor.execute(cs) except _NominalWidthUsedError: # Program has explicit width. We want to drop it, but can't # just pop the first number since it may be a subroutine call. # Instead, when seeing that, we embed the subroutine and recurse. # If this ever happened, we later prune unused subroutines. while len(program) >= 2 and program[1] in ["callsubr", "callgsubr"]: removeUnusedSubrs = True subrNumber = program.pop(0) assert isinstance(subrNumber, int), subrNumber op = program.pop(0) bias = extractor.localBias if op == "callsubr" else extractor.globalBias subrNumber += bias subrSet = thisLocalSubrs if op == "callsubr" else globalSubrs subrProgram = subrSet[subrNumber].program program[:0] = subrProgram # Now pop the actual width assert len(program) >= 1, program program.pop(0) if program and program[-1] == "endchar": program.pop() if removeUnusedSubrs: cff.remove_unused_subroutines() # Upconvert TopDict cff.major = 2 cff2GetGlyphOrder = cff.otFont.getGlyphOrder topDictData = TopDictIndex(None, cff2GetGlyphOrder) for item in cff.topDictIndex: # Iterate over, such that all are decompiled topDictData.append(item) cff.topDictIndex = topDictData topDict = topDictData[0] if hasattr(topDict, "Private"): privateDict = topDict.Private else: privateDict = None opOrder = buildOrder(topDictOperators2) topDict.order = opOrder topDict.cff2GetGlyphOrder = cff2GetGlyphOrder if not hasattr(topDict, "FDArray"): fdArray = topDict.FDArray = FDArrayIndex() fdArray.strings = None fdArray.GlobalSubrs = topDict.GlobalSubrs topDict.GlobalSubrs.fdArray = fdArray charStrings = topDict.CharStrings if charStrings.charStringsAreIndexed: charStrings.charStringsIndex.fdArray = fdArray else: charStrings.fdArray = fdArray fontDict = FontDict() fontDict.setCFF2(True) fdArray.append(fontDict) fontDict.Private = privateDict privateOpOrder = buildOrder(privateDictOperators2) if privateDict is not None: for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in privateDict.rawDict: # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key else: # clean up the PrivateDicts in the fdArray fdArray = topDict.FDArray privateOpOrder = buildOrder(privateDictOperators2) for fontDict in fdArray: fontDict.setCFF2(True) for key in list(fontDict.rawDict.keys()): if key not in fontDict.order: del fontDict.rawDict[key] if hasattr(fontDict, key): delattr(fontDict, key) privateDict = fontDict.Private for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in list(privateDict.rawDict.keys()): # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key # Now delete up the deprecated topDict operators from CFF 1.0 for entry in topDictOperators: key = entry[1] # We seem to need to keep the charset operator for now, # or we fail to compile with some fonts, like AdditionFont.otf. # I don't know which kind of CFF font those are. But keeping # charset seems to work. It will be removed when we save and # read the font again. # # AdditionFont.otf has <Encoding name="StandardEncoding"/>. if key == "charset": continue if key not in opOrder: if key in topDict.rawDict: del topDict.rawDict[key] if hasattr(topDict, key): delattr(topDict, key) # TODO(behdad): What does the following comment even mean? Both CFF and CFF2 # use the same T2Charstring class. I *think* what it means is that the CharStrings # were loaded for CFF1, and we need to reload them for CFF2 to set varstore, etc # on them. At least that's what I understand. It's probably safe to remove this # and just set vstore where needed. # # See comment above about charset as well. # At this point, the Subrs and Charstrings are all still T2Charstring class # easiest to fix this by compiling, then decompiling again file = BytesIO() cff.compile(file, otFont, isCFF2=True) file.seek(0) cff.decompile(file, otFont, isCFF2=True)
Converts this object from CFF format to CFF2 format. This conversion is done 'in-place'. The conversion cannot be reversed. This assumes a decompiled CFF table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)
_convertCFFToCFF2
python
fonttools/fonttools
Lib/fontTools/cffLib/CFFToCFF2.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFFToCFF2.py
MIT
def main(args=None): """Convert CFF OTF font to CFF2 OTF font""" if args is None: import sys args = sys.argv[1:] import argparse parser = argparse.ArgumentParser( "fonttools cffLib.CFFToCFF2", description="Upgrade a CFF font to CFF2.", ) parser.add_argument( "input", metavar="INPUT.ttf", help="Input OTF file with CFF table." ) parser.add_argument( "-o", "--output", metavar="OUTPUT.ttf", default=None, help="Output instance OTF file (default: INPUT-CFF2.ttf).", ) parser.add_argument( "--no-recalc-timestamp", dest="recalc_timestamp", action="store_false", help="Don't set the output font's timestamp to the current time.", ) loggingGroup = parser.add_mutually_exclusive_group(required=False) loggingGroup.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) loggingGroup.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args) from fontTools import configLogger configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") ) import os infile = options.input if not os.path.isfile(infile): parser.error("No such file '{}'".format(infile)) outfile = ( makeOutputFileName(infile, overWrite=True, suffix="-CFF2") if not options.output else options.output ) font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False) convertCFFToCFF2(font) log.info( "Saving %s", outfile, ) font.save(outfile)
Convert CFF OTF font to CFF2 OTF font
main
python
fonttools/fonttools
Lib/fontTools/cffLib/CFFToCFF2.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFFToCFF2.py
MIT
def commandsToProgram(commands): """Takes a commands list as returned by programToCommands() and converts it back to a T2CharString program list.""" program = [] for op, args in commands: if any(isinstance(arg, list) for arg in args): args = _flattenBlendArgs(args) program.extend(args) if op: program.append(op) return program
Takes a commands list as returned by programToCommands() and converts it back to a T2CharString program list.
commandsToProgram
python
fonttools/fonttools
Lib/fontTools/cffLib/specializer.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/specializer.py
MIT
def _everyN(el, n): """Group the list el into groups of size n""" l = len(el) if l % n != 0: raise ValueError(el) for i in range(0, l, n): yield el[i : i + n]
Group the list el into groups of size n
_everyN
python
fonttools/fonttools
Lib/fontTools/cffLib/specializer.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/specializer.py
MIT
def _categorizeVector(v): """ Takes X,Y vector v and returns one of r, h, v, or 0 depending on which of X and/or Y are zero, plus tuple of nonzero ones. If both are zero, it returns a single zero still. >>> _categorizeVector((0,0)) ('0', (0,)) >>> _categorizeVector((1,0)) ('h', (1,)) >>> _categorizeVector((0,2)) ('v', (2,)) >>> _categorizeVector((1,2)) ('r', (1, 2)) """ if not v[0]: if not v[1]: return "0", v[:1] else: return "v", v[1:] else: if not v[1]: return "h", v[:1] else: return "r", v
Takes X,Y vector v and returns one of r, h, v, or 0 depending on which of X and/or Y are zero, plus tuple of nonzero ones. If both are zero, it returns a single zero still. >>> _categorizeVector((0,0)) ('0', (0,)) >>> _categorizeVector((1,0)) ('h', (1,)) >>> _categorizeVector((0,2)) ('v', (2,)) >>> _categorizeVector((1,2)) ('r', (1, 2))
_categorizeVector
python
fonttools/fonttools
Lib/fontTools/cffLib/specializer.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/specializer.py
MIT
def optimizeWidthsBruteforce(widths): """Bruteforce version. Veeeeeeeeeeeeeeeeery slow. Only works for smallests of fonts.""" d = defaultdict(int) for w in widths: d[w] += 1 # Maximum number of bytes using default can possibly save maxDefaultAdvantage = 5 * max(d.values()) minw, maxw = min(widths), max(widths) domain = list(range(minw, maxw + 1)) bestCostWithoutDefault = min(byteCost(widths, None, nominal) for nominal in domain) bestCost = len(widths) * 5 + 1 for nominal in domain: if byteCost(widths, None, nominal) > bestCost + maxDefaultAdvantage: continue for default in domain: cost = byteCost(widths, default, nominal) if cost < bestCost: bestCost = cost bestDefault = default bestNominal = nominal return bestDefault, bestNominal
Bruteforce version. Veeeeeeeeeeeeeeeeery slow. Only works for smallests of fonts.
optimizeWidthsBruteforce
python
fonttools/fonttools
Lib/fontTools/cffLib/width.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/width.py
MIT
def optimizeWidths(widths): """Given a list of glyph widths, or dictionary mapping glyph width to number of glyphs having that, returns a tuple of best CFF default and nominal glyph widths. This algorithm is linear in UPEM+numGlyphs.""" if not hasattr(widths, "items"): d = defaultdict(int) for w in widths: d[w] += 1 widths = d keys = sorted(widths.keys()) minw, maxw = keys[0], keys[-1] domain = list(range(minw, maxw + 1)) # Cumulative sum/max forward/backward. cumFrqU = cumSum(widths, op=add) cumMaxU = cumSum(widths, op=max) cumFrqD = cumSum(widths, op=add, decreasing=True) cumMaxD = cumSum(widths, op=max, decreasing=True) # Cost per nominal choice, without default consideration. nomnCostU = missingdict( lambda x: cumFrqU[x] + cumFrqU[x - 108] + cumFrqU[x - 1132] * 3 ) nomnCostD = missingdict( lambda x: cumFrqD[x] + cumFrqD[x + 108] + cumFrqD[x + 1132] * 3 ) nomnCost = missingdict(lambda x: nomnCostU[x] + nomnCostD[x] - widths[x]) # Cost-saving per nominal choice, by best default choice. dfltCostU = missingdict( lambda x: max(cumMaxU[x], cumMaxU[x - 108] * 2, cumMaxU[x - 1132] * 5) ) dfltCostD = missingdict( lambda x: max(cumMaxD[x], cumMaxD[x + 108] * 2, cumMaxD[x + 1132] * 5) ) dfltCost = missingdict(lambda x: max(dfltCostU[x], dfltCostD[x])) # Combined cost per nominal choice. bestCost = missingdict(lambda x: nomnCost[x] - dfltCost[x]) # Best nominal. nominal = min(domain, key=lambda x: bestCost[x]) # Work back the best default. bestC = bestCost[nominal] dfltC = nomnCost[nominal] - bestCost[nominal] ends = [] if dfltC == dfltCostU[nominal]: starts = [nominal, nominal - 108, nominal - 1132] for start in starts: while cumMaxU[start] and cumMaxU[start] == cumMaxU[start - 1]: start -= 1 ends.append(start) else: starts = [nominal, nominal + 108, nominal + 1132] for start in starts: while cumMaxD[start] and cumMaxD[start] == cumMaxD[start + 1]: start += 1 ends.append(start) default = min(ends, key=lambda default: byteCost(widths, default, nominal)) return default, nominal
Given a list of glyph widths, or dictionary mapping glyph width to number of glyphs having that, returns a tuple of best CFF default and nominal glyph widths. This algorithm is linear in UPEM+numGlyphs.
optimizeWidths
python
fonttools/fonttools
Lib/fontTools/cffLib/width.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/width.py
MIT
def decompile(self, file, otFont, isCFF2=None): """Parse a binary CFF file into an internal representation. ``file`` should be a file handle object. ``otFont`` is the top-level :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file. If ``isCFF2`` is passed and set to ``True`` or ``False``, then the library makes an assertion that the CFF header is of the appropriate version. """ self.otFont = otFont sstruct.unpack(cffHeaderFormat, file.read(3), self) if isCFF2 is not None: # called from ttLib: assert 'major' as read from file matches the # expected version expected_major = 2 if isCFF2 else 1 if self.major != expected_major: raise ValueError( "Invalid CFF 'major' version: expected %d, found %d" % (expected_major, self.major) ) else: # use 'major' version from file to determine if isCFF2 assert self.major in (1, 2), "Unknown CFF format" isCFF2 = self.major == 2 if not isCFF2: self.offSize = struct.unpack("B", file.read(1))[0] file.seek(self.hdrSize) self.fontNames = list(tostr(s) for s in Index(file, isCFF2=isCFF2)) self.topDictIndex = TopDictIndex(file, isCFF2=isCFF2) self.strings = IndexedStrings(file) else: # isCFF2 self.topDictSize = struct.unpack(">H", file.read(2))[0] file.seek(self.hdrSize) self.fontNames = ["CFF2Font"] cff2GetGlyphOrder = otFont.getGlyphOrder # in CFF2, offsetSize is the size of the TopDict data. self.topDictIndex = TopDictIndex( file, cff2GetGlyphOrder, self.topDictSize, isCFF2=isCFF2 ) self.strings = None self.GlobalSubrs = GlobalSubrsIndex(file, isCFF2=isCFF2) self.topDictIndex.strings = self.strings self.topDictIndex.GlobalSubrs = self.GlobalSubrs
Parse a binary CFF file into an internal representation. ``file`` should be a file handle object. ``otFont`` is the top-level :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file. If ``isCFF2`` is passed and set to ``True`` or ``False``, then the library makes an assertion that the CFF header is of the appropriate version.
decompile
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def __getitem__(self, nameOrIndex): """Return TopDict instance identified by name (str) or index (int or any object that implements `__index__`). """ if hasattr(nameOrIndex, "__index__"): index = nameOrIndex.__index__() elif isinstance(nameOrIndex, str): name = nameOrIndex try: index = self.fontNames.index(name) except ValueError: raise KeyError(nameOrIndex) else: raise TypeError(nameOrIndex) return self.topDictIndex[index]
Return TopDict instance identified by name (str) or index (int or any object that implements `__index__`).
__getitem__
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def compile(self, file, otFont, isCFF2=None): """Write the object back into binary representation onto the given file. ``file`` should be a file handle object. ``otFont`` is the top-level :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file. If ``isCFF2`` is passed and set to ``True`` or ``False``, then the library makes an assertion that the CFF header is of the appropriate version. """ self.otFont = otFont if isCFF2 is not None: # called from ttLib: assert 'major' value matches expected version expected_major = 2 if isCFF2 else 1 if self.major != expected_major: raise ValueError( "Invalid CFF 'major' version: expected %d, found %d" % (expected_major, self.major) ) else: # use current 'major' value to determine output format assert self.major in (1, 2), "Unknown CFF format" isCFF2 = self.major == 2 if otFont.recalcBBoxes and not isCFF2: for topDict in self.topDictIndex: topDict.recalcFontBBox() if not isCFF2: strings = IndexedStrings() else: strings = None writer = CFFWriter(isCFF2) topCompiler = self.topDictIndex.getCompiler(strings, self, isCFF2=isCFF2) if isCFF2: self.hdrSize = 5 writer.add(sstruct.pack(cffHeaderFormat, self)) # Note: topDictSize will most likely change in CFFWriter.toFile(). self.topDictSize = topCompiler.getDataLength() writer.add(struct.pack(">H", self.topDictSize)) else: self.hdrSize = 4 self.offSize = 4 # will most likely change in CFFWriter.toFile(). writer.add(sstruct.pack(cffHeaderFormat, self)) writer.add(struct.pack("B", self.offSize)) if not isCFF2: fontNames = Index() for name in self.fontNames: fontNames.append(name) writer.add(fontNames.getCompiler(strings, self, isCFF2=isCFF2)) writer.add(topCompiler) if not isCFF2: writer.add(strings.getCompiler()) writer.add(self.GlobalSubrs.getCompiler(strings, self, isCFF2=isCFF2)) for topDict in self.topDictIndex: if not hasattr(topDict, "charset") or topDict.charset is None: charset = otFont.getGlyphOrder() topDict.charset = charset children = topCompiler.getChildren(strings) for child in children: writer.add(child) writer.toFile(file)
Write the object back into binary representation onto the given file. ``file`` should be a file handle object. ``otFont`` is the top-level :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file. If ``isCFF2`` is passed and set to ``True`` or ``False``, then the library makes an assertion that the CFF header is of the appropriate version.
compile
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def toXML(self, xmlWriter): """Write the object into XML representation onto the given :class:`fontTools.misc.xmlWriter.XMLWriter`. .. code:: python writer = xmlWriter.XMLWriter(sys.stdout) tt["CFF "].cff.toXML(writer) """ xmlWriter.simpletag("major", value=self.major) xmlWriter.newline() xmlWriter.simpletag("minor", value=self.minor) xmlWriter.newline() for fontName in self.fontNames: xmlWriter.begintag("CFFFont", name=tostr(fontName)) xmlWriter.newline() font = self[fontName] font.toXML(xmlWriter) xmlWriter.endtag("CFFFont") xmlWriter.newline() xmlWriter.newline() xmlWriter.begintag("GlobalSubrs") xmlWriter.newline() self.GlobalSubrs.toXML(xmlWriter) xmlWriter.endtag("GlobalSubrs") xmlWriter.newline()
Write the object into XML representation onto the given :class:`fontTools.misc.xmlWriter.XMLWriter`. .. code:: python writer = xmlWriter.XMLWriter(sys.stdout) tt["CFF "].cff.toXML(writer)
toXML
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def fromXML(self, name, attrs, content, otFont=None): """Reads data from the XML element into the ``CFFFontSet`` object.""" self.otFont = otFont # set defaults. These will be replaced if there are entries for them # in the XML file. if not hasattr(self, "major"): self.major = 1 if not hasattr(self, "minor"): self.minor = 0 if name == "CFFFont": if self.major == 1: if not hasattr(self, "offSize"): # this will be recalculated when the cff is compiled. self.offSize = 4 if not hasattr(self, "hdrSize"): self.hdrSize = 4 if not hasattr(self, "GlobalSubrs"): self.GlobalSubrs = GlobalSubrsIndex() if not hasattr(self, "fontNames"): self.fontNames = [] self.topDictIndex = TopDictIndex() fontName = attrs["name"] self.fontNames.append(fontName) topDict = TopDict(GlobalSubrs=self.GlobalSubrs) topDict.charset = None # gets filled in later elif self.major == 2: if not hasattr(self, "hdrSize"): self.hdrSize = 5 if not hasattr(self, "GlobalSubrs"): self.GlobalSubrs = GlobalSubrsIndex() if not hasattr(self, "fontNames"): self.fontNames = ["CFF2Font"] cff2GetGlyphOrder = self.otFont.getGlyphOrder topDict = TopDict( GlobalSubrs=self.GlobalSubrs, cff2GetGlyphOrder=cff2GetGlyphOrder ) self.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder) self.topDictIndex.append(topDict) for element in content: if isinstance(element, str): continue name, attrs, content = element topDict.fromXML(name, attrs, content) if hasattr(topDict, "VarStore") and topDict.FDArray[0].vstore is None: fdArray = topDict.FDArray for fontDict in fdArray: if hasattr(fontDict, "Private"): fontDict.Private.vstore = topDict.VarStore elif name == "GlobalSubrs": subrCharStringClass = psCharStrings.T2CharString if not hasattr(self, "GlobalSubrs"): self.GlobalSubrs = GlobalSubrsIndex() for element in content: if isinstance(element, str): continue name, attrs, content = element subr = subrCharStringClass() subr.fromXML(name, attrs, content) self.GlobalSubrs.append(subr) elif name == "major": self.major = int(attrs["value"]) elif name == "minor": self.minor = int(attrs["value"])
Reads data from the XML element into the ``CFFFontSet`` object.
fromXML
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def toXML(self, xmlWriter): """Write the subroutines index into XML representation onto the given :class:`fontTools.misc.xmlWriter.XMLWriter`. .. code:: python writer = xmlWriter.XMLWriter(sys.stdout) tt["CFF "].cff[0].GlobalSubrs.toXML(writer) """ xmlWriter.comment( "The 'index' attribute is only for humans; " "it is ignored when parsed." ) xmlWriter.newline() for i in range(len(self)): subr = self[i] if subr.needsDecompilation(): xmlWriter.begintag("CharString", index=i, raw=1) else: xmlWriter.begintag("CharString", index=i) xmlWriter.newline() subr.toXML(xmlWriter) xmlWriter.endtag("CharString") xmlWriter.newline()
Write the subroutines index into XML representation onto the given :class:`fontTools.misc.xmlWriter.XMLWriter`. .. code:: python writer = xmlWriter.XMLWriter(sys.stdout) tt["CFF "].cff[0].GlobalSubrs.toXML(writer)
toXML
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def parseEncodingSupplement(file, encoding, strings): """ Parse the CFF Encoding supplement data: - nSups: number of supplementary mappings - each mapping: (code, SID) pair and apply them to the `encoding` list in place. """ nSups = readCard8(file) for _ in range(nSups): code = readCard8(file) sid = readSID(file) name = strings[sid] encoding[code] = name
Parse the CFF Encoding supplement data: - nSups: number of supplementary mappings - each mapping: (code, SID) pair and apply them to the `encoding` list in place.
parseEncodingSupplement
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def parseEncoding0(charset, file): """ Format 0: simple list of codes. After reading the base table, optionally parse the supplement. """ nCodes = readCard8(file) encoding = [".notdef"] * 256 for glyphID in range(1, nCodes + 1): code = readCard8(file) if code != 0: encoding[code] = charset[glyphID] return encoding
Format 0: simple list of codes. After reading the base table, optionally parse the supplement.
parseEncoding0
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def arg_delta_blend(self, value): """A delta list with blend lists has to be *all* blend lists. The value is a list is arranged as follows:: [ [V0, d0..dn] [V1, d0..dn] ... [Vm, d0..dn] ] ``V`` is the absolute coordinate value from the default font, and ``d0-dn`` are the delta values from the *n* regions. Each ``V`` is an absolute coordinate from the default font. We want to return a list:: [ [v0, v1..vm] [d0..dn] ... [d0..dn] numBlends blendOp ] where each ``v`` is relative to the previous default font value. """ numMasters = len(value[0]) numBlends = len(value) numStack = (numBlends * numMasters) + 1 if numStack > self.maxBlendStack: # Figure out the max number of value we can blend # and divide this list up into chunks of that size. numBlendValues = int((self.maxBlendStack - 1) / numMasters) out = [] while True: numVal = min(len(value), numBlendValues) if numVal == 0: break valList = value[0:numVal] out1 = self.arg_delta_blend(valList) out.extend(out1) value = value[numVal:] else: firstList = [0] * numBlends deltaList = [None] * numBlends i = 0 prevVal = 0 while i < numBlends: # For PrivateDict BlueValues, the default font # values are absolute, not relative. # Must convert these back to relative coordinates # before writing to CFF2. defaultValue = value[i][0] firstList[i] = defaultValue - prevVal prevVal = defaultValue deltaList[i] = value[i][1:] i += 1 relValueList = firstList for blendList in deltaList: relValueList.extend(blendList) out = [encodeNumber(val) for val in relValueList] out.append(encodeNumber(numBlends)) out.append(bytechr(blendOp)) return out
A delta list with blend lists has to be *all* blend lists. The value is a list is arranged as follows:: [ [V0, d0..dn] [V1, d0..dn] ... [Vm, d0..dn] ] ``V`` is the absolute coordinate value from the default font, and ``d0-dn`` are the delta values from the *n* regions. Each ``V`` is an absolute coordinate from the default font. We want to return a list:: [ [v0, v1..vm] [d0..dn] ... [d0..dn] numBlends blendOp ] where each ``v`` is relative to the previous default font value.
arg_delta_blend
python
fonttools/fonttools
Lib/fontTools/cffLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/__init__.py
MIT
def populateCOLRv0( table: ot.COLR, colorGlyphsV0: _ColorGlyphsV0Dict, glyphMap: Optional[Mapping[str, int]] = None, ): """Build v0 color layers and add to existing COLR table. Args: table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``). colorGlyphsV0: map of base glyph names to lists of (layer glyph names, color palette index) tuples. Can be empty. glyphMap: a map from glyph names to glyph indices, as returned from ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID. """ if glyphMap is not None: colorGlyphItems = sorted( colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]] ) else: colorGlyphItems = colorGlyphsV0.items() baseGlyphRecords = [] layerRecords = [] for baseGlyph, layers in colorGlyphItems: baseRec = ot.BaseGlyphRecord() baseRec.BaseGlyph = baseGlyph baseRec.FirstLayerIndex = len(layerRecords) baseRec.NumLayers = len(layers) baseGlyphRecords.append(baseRec) for layerGlyph, paletteIndex in layers: layerRec = ot.LayerRecord() layerRec.LayerGlyph = layerGlyph layerRec.PaletteIndex = paletteIndex layerRecords.append(layerRec) table.BaseGlyphRecordArray = table.LayerRecordArray = None if baseGlyphRecords: table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray() table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords if layerRecords: table.LayerRecordArray = ot.LayerRecordArray() table.LayerRecordArray.LayerRecord = layerRecords table.BaseGlyphRecordCount = len(baseGlyphRecords) table.LayerRecordCount = len(layerRecords)
Build v0 color layers and add to existing COLR table. Args: table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``). colorGlyphsV0: map of base glyph names to lists of (layer glyph names, color palette index) tuples. Can be empty. glyphMap: a map from glyph names to glyph indices, as returned from ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID.
populateCOLRv0
python
fonttools/fonttools
Lib/fontTools/colorLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/colorLib/builder.py
MIT
def buildCOLR( colorGlyphs: _ColorGlyphsDict, version: Optional[int] = None, *, glyphMap: Optional[Mapping[str, int]] = None, varStore: Optional[ot.VarStore] = None, varIndexMap: Optional[ot.DeltaSetIndexMap] = None, clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None, allowLayerReuse: bool = True, ) -> C_O_L_R_.table_C_O_L_R_: """Build COLR table from color layers mapping. Args: colorGlyphs: map of base glyph name to, either list of (layer glyph name, color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or list of ``Paint`` for COLRv1. version: the version of COLR table. If None, the version is determined by the presence of COLRv1 paints or variation data (varStore), which require version 1; otherwise, if all base glyphs use only simple color layers, version 0 is used. glyphMap: a map from glyph names to glyph indices, as returned from TTFont.getReverseGlyphMap(), to optionally sort base records by GID. varStore: Optional ItemVarationStore for deltas associated with v1 layer. varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer. clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples: (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase). Returns: A new COLR table. """ self = C_O_L_R_.table_C_O_L_R_() if varStore is not None and version == 0: raise ValueError("Can't add VarStore to COLRv0") if version in (None, 0) and not varStore: # split color glyphs into v0 and v1 and encode separately colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs) if version == 0 and colorGlyphsV1: raise ValueError("Can't encode COLRv1 glyphs in COLRv0") else: # unless explicitly requested for v1 or have variations, in which case # we encode all color glyph as v1 colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs colr = ot.COLR() populateCOLRv0(colr, colorGlyphsV0, glyphMap) colr.LayerList, colr.BaseGlyphList = buildColrV1( colorGlyphsV1, glyphMap, allowLayerReuse=allowLayerReuse, ) if version is None: version = 1 if (varStore or colorGlyphsV1) else 0 elif version not in (0, 1): raise NotImplementedError(version) self.version = colr.Version = version if version == 0: self.ColorLayers = self._decompileColorLayersV0(colr) else: colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None colr.VarIndexMap = varIndexMap colr.VarStore = varStore self.table = colr return self
Build COLR table from color layers mapping. Args: colorGlyphs: map of base glyph name to, either list of (layer glyph name, color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or list of ``Paint`` for COLRv1. version: the version of COLR table. If None, the version is determined by the presence of COLRv1 paints or variation data (varStore), which require version 1; otherwise, if all base glyphs use only simple color layers, version 0 is used. glyphMap: a map from glyph names to glyph indices, as returned from TTFont.getReverseGlyphMap(), to optionally sort base records by GID. varStore: Optional ItemVarationStore for deltas associated with v1 layer. varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer. clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples: (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase). Returns: A new COLR table.
buildCOLR
python
fonttools/fonttools
Lib/fontTools/colorLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/colorLib/builder.py
MIT
def buildCPAL( palettes: Sequence[Sequence[Tuple[float, float, float, float]]], paletteTypes: Optional[Sequence[ColorPaletteType]] = None, paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None, paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None, nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None, ) -> C_P_A_L_.table_C_P_A_L_: """Build CPAL table from list of color palettes. Args: palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats in the range [0..1]. paletteTypes: optional list of ColorPaletteType, one for each palette. paletteLabels: optional list of palette labels. Each lable can be either: None (no label), a string (for for default English labels), or a localized string (as a dict keyed with BCP47 language codes). paletteEntryLabels: optional list of palette entry labels, one for each palette entry (see paletteLabels). nameTable: optional name table where to store palette and palette entry labels. Required if either paletteLabels or paletteEntryLabels is set. Return: A new CPAL v0 or v1 table, if custom palette types or labels are specified. """ if len({len(p) for p in palettes}) != 1: raise ColorLibError("color palettes have different lengths") if (paletteLabels or paletteEntryLabels) and not nameTable: raise TypeError( "nameTable is required if palette or palette entries have labels" ) cpal = C_P_A_L_.table_C_P_A_L_() cpal.numPaletteEntries = len(palettes[0]) cpal.palettes = [] for i, palette in enumerate(palettes): colors = [] for j, color in enumerate(palette): if not isinstance(color, tuple) or len(color) != 4: raise ColorLibError( f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}" ) if any(v > 1 or v < 0 for v in color): raise ColorLibError( f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}" ) # input colors are RGBA, CPAL encodes them as BGRA red, green, blue, alpha = color colors.append( C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha))) ) cpal.palettes.append(colors) if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)): cpal.version = 1 if paletteTypes is not None: if len(paletteTypes) != len(palettes): raise ColorLibError( f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}" ) cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes] else: cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len( palettes ) if paletteLabels is not None: if len(paletteLabels) != len(palettes): raise ColorLibError( f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}" ) cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable) else: cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes) if paletteEntryLabels is not None: if len(paletteEntryLabels) != cpal.numPaletteEntries: raise ColorLibError( f"Expected {cpal.numPaletteEntries} paletteEntryLabels, " f"got {len(paletteEntryLabels)}" ) cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable) else: cpal.paletteEntryLabels = [ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID ] * cpal.numPaletteEntries else: cpal.version = 0 return cpal
Build CPAL table from list of color palettes. Args: palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats in the range [0..1]. paletteTypes: optional list of ColorPaletteType, one for each palette. paletteLabels: optional list of palette labels. Each lable can be either: None (no label), a string (for for default English labels), or a localized string (as a dict keyed with BCP47 language codes). paletteEntryLabels: optional list of palette entry labels, one for each palette entry (see paletteLabels). nameTable: optional name table where to store palette and palette entry labels. Required if either paletteLabels or paletteEntryLabels is set. Return: A new CPAL v0 or v1 table, if custom palette types or labels are specified.
buildCPAL
python
fonttools/fonttools
Lib/fontTools/colorLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/colorLib/builder.py
MIT
def _main(args=None): """Convert a UFO font from cubic to quadratic curves""" parser = argparse.ArgumentParser(prog="cu2qu") parser.add_argument("--version", action="version", version=fontTools.__version__) parser.add_argument( "infiles", nargs="+", metavar="INPUT", help="one or more input UFO source file(s).", ) parser.add_argument("-v", "--verbose", action="count", default=0) parser.add_argument( "-e", "--conversion-error", type=float, metavar="ERROR", default=None, help="maxiumum approximation error measured in EM (default: 0.001)", ) parser.add_argument( "-m", "--mixed", default=False, action="store_true", help="whether to used mixed quadratic and cubic curves", ) parser.add_argument( "--keep-direction", dest="reverse_direction", action="store_false", help="do not reverse the contour direction", ) mode_parser = parser.add_mutually_exclusive_group() mode_parser.add_argument( "-i", "--interpolatable", action="store_true", help="whether curve conversion should keep interpolation compatibility", ) mode_parser.add_argument( "-j", "--jobs", type=int, nargs="?", default=1, const=_cpu_count(), metavar="N", help="Convert using N multiple processes (default: %(default)s)", ) output_parser = parser.add_mutually_exclusive_group() output_parser.add_argument( "-o", "--output-file", default=None, metavar="OUTPUT", help=( "output filename for the converted UFO. By default fonts are " "modified in place. This only works with a single input." ), ) output_parser.add_argument( "-d", "--output-dir", default=None, metavar="DIRECTORY", help="output directory where to save converted UFOs", ) options = parser.parse_args(args) if ufo_module is None: parser.error("Either ufoLib2 or defcon are required to run this script.") if not options.verbose: level = "WARNING" elif options.verbose == 1: level = "INFO" else: level = "DEBUG" logging.basicConfig(level=level) if len(options.infiles) > 1 and options.output_file: parser.error("-o/--output-file can't be used with multile inputs") if options.output_dir: output_dir = options.output_dir if not os.path.exists(output_dir): os.mkdir(output_dir) elif not os.path.isdir(output_dir): parser.error("'%s' is not a directory" % output_dir) output_paths = [ os.path.join(output_dir, os.path.basename(p)) for p in options.infiles ] elif options.output_file: output_paths = [options.output_file] else: # save in-place output_paths = [None] * len(options.infiles) kwargs = dict( dump_stats=options.verbose > 0, max_err_em=options.conversion_error, reverse_direction=options.reverse_direction, all_quadratic=False if options.mixed else True, ) if options.interpolatable: logger.info("Converting curves compatibly") ufos = [open_ufo(infile) for infile in options.infiles] if fonts_to_quadratic(ufos, **kwargs): for ufo, output_path in zip(ufos, output_paths): logger.info("Saving %s", output_path) if output_path: ufo.save(output_path) else: ufo.save() else: for input_path, output_path in zip(options.infiles, output_paths): if output_path: _copytree(input_path, output_path) else: jobs = min(len(options.infiles), options.jobs) if options.jobs > 1 else 1 if jobs > 1: func = partial(_font_to_quadratic, **kwargs) logger.info("Running %d parallel processes", jobs) with closing(mp.Pool(jobs)) as pool: pool.starmap(func, zip(options.infiles, output_paths)) else: for input_path, output_path in zip(options.infiles, output_paths): _font_to_quadratic(input_path, output_path, **kwargs)
Convert a UFO font from cubic to quadratic curves
_main
python
fonttools/fonttools
Lib/fontTools/cu2qu/cli.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cli.py
MIT
def split_cubic_into_n_iter(p0, p1, p2, p3, n): """Split a cubic Bezier into n equal parts. Splits the curve into `n` equal parts by curve time. (t=0..1/n, t=1/n..2/n, ...) Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: An iterator yielding the control points (four complex values) of the subcurves. """ # Hand-coded special-cases if n == 2: return iter(split_cubic_into_two(p0, p1, p2, p3)) if n == 3: return iter(split_cubic_into_three(p0, p1, p2, p3)) if n == 4: a, b = split_cubic_into_two(p0, p1, p2, p3) return iter( split_cubic_into_two(a[0], a[1], a[2], a[3]) + split_cubic_into_two(b[0], b[1], b[2], b[3]) ) if n == 6: a, b = split_cubic_into_two(p0, p1, p2, p3) return iter( split_cubic_into_three(a[0], a[1], a[2], a[3]) + split_cubic_into_three(b[0], b[1], b[2], b[3]) ) return _split_cubic_into_n_gen(p0, p1, p2, p3, n)
Split a cubic Bezier into n equal parts. Splits the curve into `n` equal parts by curve time. (t=0..1/n, t=1/n..2/n, ...) Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: An iterator yielding the control points (four complex values) of the subcurves.
split_cubic_into_n_iter
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def split_cubic_into_two(p0, p1, p2, p3): """Split a cubic Bezier into two equal parts. Splits the curve into two equal parts at t = 0.5 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: tuple: Two cubic Beziers (each expressed as a tuple of four complex values). """ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 deriv3 = (p3 + p2 - p1 - p0) * 0.125 return ( (p0, (p0 + p1) * 0.5, mid - deriv3, mid), (mid, mid + deriv3, (p2 + p3) * 0.5, p3), )
Split a cubic Bezier into two equal parts. Splits the curve into two equal parts at t = 0.5 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: tuple: Two cubic Beziers (each expressed as a tuple of four complex values).
split_cubic_into_two
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def split_cubic_into_three(p0, p1, p2, p3): """Split a cubic Bezier into three equal parts. Splits the curve into three equal parts at t = 1/3 and t = 2/3 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: tuple: Three cubic Beziers (each expressed as a tuple of four complex values). """ mid1 = (8 * p0 + 12 * p1 + 6 * p2 + p3) * (1 / 27) deriv1 = (p3 + 3 * p2 - 4 * p0) * (1 / 27) mid2 = (p0 + 6 * p1 + 12 * p2 + 8 * p3) * (1 / 27) deriv2 = (4 * p3 - 3 * p1 - p0) * (1 / 27) return ( (p0, (2 * p0 + p1) / 3.0, mid1 - deriv1, mid1), (mid1, mid1 + deriv1, mid2 - deriv2, mid2), (mid2, mid2 + deriv2, (p2 + 2 * p3) / 3.0, p3), )
Split a cubic Bezier into three equal parts. Splits the curve into three equal parts at t = 1/3 and t = 2/3 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: tuple: Three cubic Beziers (each expressed as a tuple of four complex values).
split_cubic_into_three
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def cubic_approx_control(t, p0, p1, p2, p3): """Approximate a cubic Bezier using a quadratic one. Args: t (double): Position of control point. p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: complex: Location of candidate control point on quadratic curve. """ _p1 = p0 + (p1 - p0) * 1.5 _p2 = p3 + (p2 - p3) * 1.5 return _p1 + (_p2 - _p1) * t
Approximate a cubic Bezier using a quadratic one. Args: t (double): Position of control point. p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: complex: Location of candidate control point on quadratic curve.
cubic_approx_control
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def calc_intersect(a, b, c, d): """Calculate the intersection of two lines. Args: a (complex): Start point of first line. b (complex): End point of first line. c (complex): Start point of second line. d (complex): End point of second line. Returns: complex: Location of intersection if one present, ``complex(NaN,NaN)`` if no intersection was found. """ ab = b - a cd = d - c p = ab * 1j try: h = dot(p, a - c) / dot(p, cd) except ZeroDivisionError: return complex(NAN, NAN) return c + cd * h
Calculate the intersection of two lines. Args: a (complex): Start point of first line. b (complex): End point of first line. c (complex): Start point of second line. d (complex): End point of second line. Returns: complex: Location of intersection if one present, ``complex(NaN,NaN)`` if no intersection was found.
calc_intersect
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): """Check if a cubic Bezier lies within a given distance of the origin. "Origin" means *the* origin (0,0), not the start of the curve. Note that no checks are made on the start and end positions of the curve; this function only checks the inside of the curve. Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. tolerance (double): Distance from origin. Returns: bool: True if the cubic Bezier ``p`` entirely lies within a distance ``tolerance`` of the origin, False otherwise. """ # First check p2 then p1, as p2 has higher error early on. if abs(p2) <= tolerance and abs(p1) <= tolerance: return True # Split. mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 if abs(mid) > tolerance: return False deriv3 = (p3 + p2 - p1 - p0) * 0.125 return cubic_farthest_fit_inside( p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
Check if a cubic Bezier lies within a given distance of the origin. "Origin" means *the* origin (0,0), not the start of the curve. Note that no checks are made on the start and end positions of the curve; this function only checks the inside of the curve. Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. tolerance (double): Distance from origin. Returns: bool: True if the cubic Bezier ``p`` entirely lies within a distance ``tolerance`` of the origin, False otherwise.
cubic_farthest_fit_inside
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def curves_to_quadratic(curves, max_errors, all_quadratic=True): """Return quadratic Bezier splines approximating the input cubic Beziers. Args: curves: A sequence of *n* curves, each curve being a sequence of four 2D tuples. max_errors: A sequence of *n* floats representing the maximum permissible deviation from each of the cubic Bezier curves. all_quadratic (bool): If True (default) returned values are a quadratic spline. If False, they are either a single quadratic curve or a single cubic curve. Example:: >>> curves_to_quadratic( [ ... [ (50,50), (100,100), (150,100), (200,50) ], ... [ (75,50), (120,100), (150,75), (200,60) ] ... ], [1,1] ) [[(50.0, 50.0), (75.0, 75.0), (125.0, 91.66666666666666), (175.0, 75.0), (200.0, 50.0)], [(75.0, 50.0), (97.5, 75.0), (135.41666666666666, 82.08333333333333), (175.0, 67.5), (200.0, 60.0)]] The returned splines have "implied oncurve points" suitable for use in TrueType ``glif`` outlines - i.e. in the first spline returned above, the first quadratic segment runs from (50,50) to ( (75 + 125)/2 , (120 + 91.666..)/2 ) = (100, 83.333...). Returns: If all_quadratic is True, a list of splines, each spline being a list of 2D tuples. If all_quadratic is False, a list of curves, each curve being a quadratic (length 3), or cubic (length 4). Raises: fontTools.cu2qu.Errors.ApproxNotFoundError: if no suitable approximation can be found for all curves with the given parameters. """ curves = [[complex(*p) for p in curve] for curve in curves] assert len(max_errors) == len(curves) l = len(curves) splines = [None] * l last_i = i = 0 n = 1 while True: spline = cubic_approx_spline(curves[i], n, max_errors[i], all_quadratic) if spline is None: if n == MAX_N: break n += 1 last_i = i continue splines[i] = spline i = (i + 1) % l if i == last_i: # done. go home return [[(s.real, s.imag) for s in spline] for spline in splines] raise ApproxNotFoundError(curves)
Return quadratic Bezier splines approximating the input cubic Beziers. Args: curves: A sequence of *n* curves, each curve being a sequence of four 2D tuples. max_errors: A sequence of *n* floats representing the maximum permissible deviation from each of the cubic Bezier curves. all_quadratic (bool): If True (default) returned values are a quadratic spline. If False, they are either a single quadratic curve or a single cubic curve. Example:: >>> curves_to_quadratic( [ ... [ (50,50), (100,100), (150,100), (200,50) ], ... [ (75,50), (120,100), (150,75), (200,60) ] ... ], [1,1] ) [[(50.0, 50.0), (75.0, 75.0), (125.0, 91.66666666666666), (175.0, 75.0), (200.0, 50.0)], [(75.0, 50.0), (97.5, 75.0), (135.41666666666666, 82.08333333333333), (175.0, 67.5), (200.0, 60.0)]] The returned splines have "implied oncurve points" suitable for use in TrueType ``glif`` outlines - i.e. in the first spline returned above, the first quadratic segment runs from (50,50) to ( (75 + 125)/2 , (120 + 91.666..)/2 ) = (100, 83.333...). Returns: If all_quadratic is True, a list of splines, each spline being a list of 2D tuples. If all_quadratic is False, a list of curves, each curve being a quadratic (length 3), or cubic (length 4). Raises: fontTools.cu2qu.Errors.ApproxNotFoundError: if no suitable approximation can be found for all curves with the given parameters.
curves_to_quadratic
python
fonttools/fonttools
Lib/fontTools/cu2qu/cu2qu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/cu2qu.py
MIT
def zip(*args): """Ensure each argument to zip has the same length. Also make sure a list is returned for python 2/3 compatibility. """ if len(set(len(a) for a in args)) != 1: raise UnequalZipLengthsError(*args) return list(_zip(*args))
Ensure each argument to zip has the same length. Also make sure a list is returned for python 2/3 compatibility.
zip
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def _get_segments(glyph): """Get a glyph's segments as extracted by GetSegmentsPen.""" pen = GetSegmentsPen() # glyph.draw(pen) # We can't simply draw the glyph with the pen, but we must initialize the # PointToSegmentPen explicitly with outputImpliedClosingLine=True. # By default PointToSegmentPen does not outputImpliedClosingLine -- unless # last and first point on closed contour are duplicated. Because we are # converting multiple glyphs at the same time, we want to make sure # this function returns the same number of segments, whether or not # the last and first point overlap. # https://github.com/googlefonts/fontmake/issues/572 # https://github.com/fonttools/fonttools/pull/1720 pointPen = PointToSegmentPen(pen, outputImpliedClosingLine=True) glyph.drawPoints(pointPen) return pen.segments
Get a glyph's segments as extracted by GetSegmentsPen.
_get_segments
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def _set_segments(glyph, segments, reverse_direction): """Draw segments as extracted by GetSegmentsPen back to a glyph.""" glyph.clearContours() pen = glyph.getPen() if reverse_direction: pen = ReverseContourPen(pen) for tag, args in segments: if tag == "move": pen.moveTo(*args) elif tag == "line": pen.lineTo(*args) elif tag == "curve": pen.curveTo(*args[1:]) elif tag == "qcurve": pen.qCurveTo(*args[1:]) elif tag == "close": pen.closePath() elif tag == "end": pen.endPath() else: raise AssertionError('Unhandled segment type "%s"' % tag)
Draw segments as extracted by GetSegmentsPen back to a glyph.
_set_segments
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def _segments_to_quadratic(segments, max_err, stats, all_quadratic=True): """Return quadratic approximations of cubic segments.""" assert all(s[0] == "curve" for s in segments), "Non-cubic given to convert" new_points = curves_to_quadratic([s[1] for s in segments], max_err, all_quadratic) n = len(new_points[0]) assert all(len(s) == n for s in new_points[1:]), "Converted incompatibly" spline_length = str(n - 2) stats[spline_length] = stats.get(spline_length, 0) + 1 if all_quadratic or n == 3: return [("qcurve", p) for p in new_points] else: return [("curve", p) for p in new_points]
Return quadratic approximations of cubic segments.
_segments_to_quadratic
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def _glyphs_to_quadratic(glyphs, max_err, reverse_direction, stats, all_quadratic=True): """Do the actual conversion of a set of compatible glyphs, after arguments have been set up. Return True if the glyphs were modified, else return False. """ try: segments_by_location = zip(*[_get_segments(g) for g in glyphs]) except UnequalZipLengthsError: raise IncompatibleSegmentNumberError(glyphs) if not any(segments_by_location): return False # always modify input glyphs if reverse_direction is True glyphs_modified = reverse_direction new_segments_by_location = [] incompatible = {} for i, segments in enumerate(segments_by_location): tag = segments[0][0] if not all(s[0] == tag for s in segments[1:]): incompatible[i] = [s[0] for s in segments] elif tag == "curve": new_segments = _segments_to_quadratic( segments, max_err, stats, all_quadratic ) if all_quadratic or new_segments != segments: glyphs_modified = True segments = new_segments new_segments_by_location.append(segments) if glyphs_modified: new_segments_by_glyph = zip(*new_segments_by_location) for glyph, new_segments in zip(glyphs, new_segments_by_glyph): _set_segments(glyph, new_segments, reverse_direction) if incompatible: raise IncompatibleSegmentTypesError(glyphs, segments=incompatible) return glyphs_modified
Do the actual conversion of a set of compatible glyphs, after arguments have been set up. Return True if the glyphs were modified, else return False.
_glyphs_to_quadratic
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def glyphs_to_quadratic( glyphs, max_err=None, reverse_direction=False, stats=None, all_quadratic=True ): """Convert the curves of a set of compatible of glyphs to quadratic. All curves will be converted to quadratic at once, ensuring interpolation compatibility. If this is not required, calling glyphs_to_quadratic with one glyph at a time may yield slightly more optimized results. Return True if glyphs were modified, else return False. Raises IncompatibleGlyphsError if glyphs have non-interpolatable outlines. """ if stats is None: stats = {} if not max_err: # assume 1000 is the default UPEM max_err = DEFAULT_MAX_ERR * 1000 if isinstance(max_err, (list, tuple)): max_errors = max_err else: max_errors = [max_err] * len(glyphs) assert len(max_errors) == len(glyphs) return _glyphs_to_quadratic( glyphs, max_errors, reverse_direction, stats, all_quadratic )
Convert the curves of a set of compatible of glyphs to quadratic. All curves will be converted to quadratic at once, ensuring interpolation compatibility. If this is not required, calling glyphs_to_quadratic with one glyph at a time may yield slightly more optimized results. Return True if glyphs were modified, else return False. Raises IncompatibleGlyphsError if glyphs have non-interpolatable outlines.
glyphs_to_quadratic
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def fonts_to_quadratic( fonts, max_err_em=None, max_err=None, reverse_direction=False, stats=None, dump_stats=False, remember_curve_type=True, all_quadratic=True, ): """Convert the curves of a collection of fonts to quadratic. All curves will be converted to quadratic at once, ensuring interpolation compatibility. If this is not required, calling fonts_to_quadratic with one font at a time may yield slightly more optimized results. Return the set of modified glyph names if any, else return an empty set. By default, cu2qu stores the curve type in the fonts' lib, under a private key "com.github.googlei18n.cu2qu.curve_type", and will not try to convert them again if the curve type is already set to "quadratic". Setting 'remember_curve_type' to False disables this optimization. Raises IncompatibleFontsError if same-named glyphs from different fonts have non-interpolatable outlines. """ if remember_curve_type: curve_types = {f.lib.get(CURVE_TYPE_LIB_KEY, "cubic") for f in fonts} if len(curve_types) == 1: curve_type = next(iter(curve_types)) if curve_type in ("quadratic", "mixed"): logger.info("Curves already converted to quadratic") return False elif curve_type == "cubic": pass # keep converting else: raise NotImplementedError(curve_type) elif len(curve_types) > 1: # going to crash later if they do differ logger.warning("fonts may contain different curve types") if stats is None: stats = {} if max_err_em and max_err: raise TypeError("Only one of max_err and max_err_em can be specified.") if not (max_err_em or max_err): max_err_em = DEFAULT_MAX_ERR if isinstance(max_err, (list, tuple)): assert len(max_err) == len(fonts) max_errors = max_err elif max_err: max_errors = [max_err] * len(fonts) if isinstance(max_err_em, (list, tuple)): assert len(fonts) == len(max_err_em) max_errors = [f.info.unitsPerEm * e for f, e in zip(fonts, max_err_em)] elif max_err_em: max_errors = [f.info.unitsPerEm * max_err_em for f in fonts] modified = set() glyph_errors = {} for name in set().union(*(f.keys() for f in fonts)): glyphs = [] cur_max_errors = [] for font, error in zip(fonts, max_errors): if name in font: glyphs.append(font[name]) cur_max_errors.append(error) try: if _glyphs_to_quadratic( glyphs, cur_max_errors, reverse_direction, stats, all_quadratic ): modified.add(name) except IncompatibleGlyphsError as exc: logger.error(exc) glyph_errors[name] = exc if glyph_errors: raise IncompatibleFontsError(glyph_errors) if modified and dump_stats: spline_lengths = sorted(stats.keys()) logger.info( "New spline lengths: %s" % (", ".join("%s: %d" % (l, stats[l]) for l in spline_lengths)) ) if remember_curve_type: for font in fonts: curve_type = font.lib.get(CURVE_TYPE_LIB_KEY, "cubic") new_curve_type = "quadratic" if all_quadratic else "mixed" if curve_type != new_curve_type: font.lib[CURVE_TYPE_LIB_KEY] = new_curve_type return modified
Convert the curves of a collection of fonts to quadratic. All curves will be converted to quadratic at once, ensuring interpolation compatibility. If this is not required, calling fonts_to_quadratic with one font at a time may yield slightly more optimized results. Return the set of modified glyph names if any, else return an empty set. By default, cu2qu stores the curve type in the fonts' lib, under a private key "com.github.googlei18n.cu2qu.curve_type", and will not try to convert them again if the curve type is already set to "quadratic". Setting 'remember_curve_type' to False disables this optimization. Raises IncompatibleFontsError if same-named glyphs from different fonts have non-interpolatable outlines.
fonts_to_quadratic
python
fonttools/fonttools
Lib/fontTools/cu2qu/ufo.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cu2qu/ufo.py
MIT
def defaultMakeInstanceFilename( doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames ) -> str: """Default callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overriden because it's not specified by the STAT table. """ familyName = instance.familyName or statNames.familyNames.get("en") styleName = instance.styleName or statNames.styleNames.get("en") return f"{familyName}-{styleName}.ttf"
Default callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overriden because it's not specified by the STAT table.
defaultMakeInstanceFilename
python
fonttools/fonttools
Lib/fontTools/designspaceLib/split.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/split.py
MIT
def splitInterpolable( doc: DesignSpaceDocument, makeNames: bool = True, expandLocations: bool = True, makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename, ) -> Iterator[Tuple[SimpleLocationDict, DesignSpaceDocument]]: """Split the given DS5 into several interpolable sub-designspaces. There are as many interpolable sub-spaces as there are combinations of discrete axis values. E.g. with axes: - italic (discrete) Upright or Italic - style (discrete) Sans or Serif - weight (continuous) 100 to 900 There are 4 sub-spaces in which the Weight axis should interpolate: (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif). The sub-designspaces still include the full axis definitions and STAT data, but the rules, sources, variable fonts, instances are trimmed down to only keep what falls within the interpolable sub-space. Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table. .. versionadded:: 5.0 """ discreteAxes = [] interpolableUserRegion: Region = {} for axis in doc.axes: if hasattr(axis, "values"): # Mypy doesn't support narrowing union types via hasattr() # TODO(Python 3.10): use TypeGuard # https://mypy.readthedocs.io/en/stable/type_narrowing.html axis = cast(DiscreteAxisDescriptor, axis) discreteAxes.append(axis) else: axis = cast(AxisDescriptor, axis) interpolableUserRegion[axis.name] = Range( axis.minimum, axis.maximum, axis.default, ) valueCombinations = itertools.product(*[axis.values for axis in discreteAxes]) for values in valueCombinations: discreteUserLocation = { discreteAxis.name: value for discreteAxis, value in zip(discreteAxes, values) } subDoc = _extractSubSpace( doc, {**interpolableUserRegion, **discreteUserLocation}, keepVFs=True, makeNames=makeNames, expandLocations=expandLocations, makeInstanceFilename=makeInstanceFilename, ) yield discreteUserLocation, subDoc
Split the given DS5 into several interpolable sub-designspaces. There are as many interpolable sub-spaces as there are combinations of discrete axis values. E.g. with axes: - italic (discrete) Upright or Italic - style (discrete) Sans or Serif - weight (continuous) 100 to 900 There are 4 sub-spaces in which the Weight axis should interpolate: (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif). The sub-designspaces still include the full axis definitions and STAT data, but the rules, sources, variable fonts, instances are trimmed down to only keep what falls within the interpolable sub-space. Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table. .. versionadded:: 5.0
splitInterpolable
python
fonttools/fonttools
Lib/fontTools/designspaceLib/split.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/split.py
MIT
def splitVariableFonts( doc: DesignSpaceDocument, makeNames: bool = False, expandLocations: bool = False, makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename, ) -> Iterator[Tuple[str, DesignSpaceDocument]]: """Convert each variable font listed in this document into a standalone designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that can only deal with 1 VF at a time. Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table. .. versionadded:: 5.0 """ # Make one DesignspaceDoc v5 for each variable font for vf in doc.getVariableFonts(): vfUserRegion = getVFUserRegion(doc, vf) vfDoc = _extractSubSpace( doc, vfUserRegion, keepVFs=False, makeNames=makeNames, expandLocations=expandLocations, makeInstanceFilename=makeInstanceFilename, ) vfDoc.lib = {**vfDoc.lib, **vf.lib} yield vf.name, vfDoc
Convert each variable font listed in this document into a standalone designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that can only deal with 1 VF at a time. Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table. .. versionadded:: 5.0
splitVariableFonts
python
fonttools/fonttools
Lib/fontTools/designspaceLib/split.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/split.py
MIT
def convert5to4( doc: DesignSpaceDocument, ) -> Dict[str, DesignSpaceDocument]: """Convert each variable font listed in this document into a standalone format 4 designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that only know about format 4. .. versionadded:: 5.0 """ vfs = {} for _location, subDoc in splitInterpolable(doc): for vfName, vfDoc in splitVariableFonts(subDoc): vfDoc.formatVersion = "4.1" vfs[vfName] = vfDoc return vfs
Convert each variable font listed in this document into a standalone format 4 designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that only know about format 4. .. versionadded:: 5.0
convert5to4
python
fonttools/fonttools
Lib/fontTools/designspaceLib/split.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/split.py
MIT
def getStatNames( doc: DesignSpaceDocument, userLocation: SimpleLocationDict ) -> StatNames: """Compute the family, style, PostScript names of the given ``userLocation`` using the document's STAT information. Also computes localizations. If not enough STAT data is available for a given name, either its dict of localized names will be empty (family and style names), or the name will be None (PostScript name). Note: this method does not consider info attached to the instance, like family name. The user needs to override all names on an instance that STAT information would compute differently than desired. .. versionadded:: 5.0 """ familyNames: Dict[str, str] = {} defaultSource: Optional[SourceDescriptor] = doc.findDefault() if defaultSource is None: LOGGER.warning("Cannot determine default source to look up family name.") elif defaultSource.familyName is None: LOGGER.warning( "Cannot look up family name, assign the 'familyname' attribute to the default source." ) else: familyNames = { "en": defaultSource.familyName, **defaultSource.localisedFamilyName, } styleNames: Dict[str, str] = {} # If a free-standing label matches the location, use it for name generation. label = doc.labelForUserLocation(userLocation) if label is not None: styleNames = {"en": label.name, **label.labelNames} # Otherwise, scour the axis labels for matches. else: # Gather all languages in which at least one translation is provided # Then build names for all these languages, but fallback to English # whenever a translation is missing. labels = _getAxisLabelsForUserLocation(doc.axes, userLocation) if labels: languages = set( language for label in labels for language in label.labelNames ) languages.add("en") for language in languages: styleName = " ".join( label.labelNames.get(language, label.defaultName) for label in labels if not label.elidable ) if not styleName and doc.elidedFallbackName is not None: styleName = doc.elidedFallbackName styleNames[language] = styleName if "en" not in familyNames or "en" not in styleNames: # Not enough information to compute PS names of styleMap names return StatNames( familyNames=familyNames, styleNames=styleNames, postScriptFontName=None, styleMapFamilyNames={}, styleMapStyleName=None, ) postScriptFontName = f"{familyNames['en']}-{styleNames['en']}".replace(" ", "") styleMapStyleName, regularUserLocation = _getRibbiStyle(doc, userLocation) styleNamesForStyleMap = styleNames if regularUserLocation != userLocation: regularStatNames = getStatNames(doc, regularUserLocation) styleNamesForStyleMap = regularStatNames.styleNames styleMapFamilyNames = {} for language in set(familyNames).union(styleNames.keys()): familyName = familyNames.get(language, familyNames["en"]) styleName = styleNamesForStyleMap.get(language, styleNamesForStyleMap["en"]) styleMapFamilyNames[language] = (familyName + " " + styleName).strip() return StatNames( familyNames=familyNames, styleNames=styleNames, postScriptFontName=postScriptFontName, styleMapFamilyNames=styleMapFamilyNames, styleMapStyleName=styleMapStyleName, )
Compute the family, style, PostScript names of the given ``userLocation`` using the document's STAT information. Also computes localizations. If not enough STAT data is available for a given name, either its dict of localized names will be empty (family and style names), or the name will be None (PostScript name). Note: this method does not consider info attached to the instance, like family name. The user needs to override all names on an instance that STAT information would compute differently than desired. .. versionadded:: 5.0
getStatNames
python
fonttools/fonttools
Lib/fontTools/designspaceLib/statNames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/statNames.py
MIT
def _getSortedAxisLabels( axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]], ) -> Dict[str, list[AxisLabelDescriptor]]: """Returns axis labels sorted by their ordering, with unordered ones appended as they are listed.""" # First, get the axis labels with explicit ordering... sortedAxes = sorted( (axis for axis in axes if axis.axisOrdering is not None), key=lambda a: a.axisOrdering, ) sortedLabels: Dict[str, list[AxisLabelDescriptor]] = { axis.name: axis.axisLabels for axis in sortedAxes } # ... then append the others in the order they appear. # NOTE: This relies on Python 3.7+ dict's preserved insertion order. for axis in axes: if axis.axisOrdering is None: sortedLabels[axis.name] = axis.axisLabels return sortedLabels
Returns axis labels sorted by their ordering, with unordered ones appended as they are listed.
_getSortedAxisLabels
python
fonttools/fonttools
Lib/fontTools/designspaceLib/statNames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/statNames.py
MIT
def _getRibbiStyle( self: DesignSpaceDocument, userLocation: SimpleLocationDict ) -> Tuple[RibbiStyleName, SimpleLocationDict]: """Compute the RIBBI style name of the given user location, return the location of the matching Regular in the RIBBI group. .. versionadded:: 5.0 """ regularUserLocation = {} axes_by_tag = {axis.tag: axis for axis in self.axes} bold: bool = False italic: bool = False axis = axes_by_tag.get("wght") if axis is not None: for regular_label in axis.axisLabels: if ( regular_label.linkedUserValue == userLocation[axis.name] # In the "recursive" case where both the Regular has # linkedUserValue pointing the Bold, and the Bold has # linkedUserValue pointing to the Regular, only consider the # first case: Regular (e.g. 400) has linkedUserValue pointing to # Bold (e.g. 700, higher than Regular) and regular_label.userValue < regular_label.linkedUserValue ): regularUserLocation[axis.name] = regular_label.userValue bold = True break axis = axes_by_tag.get("ital") or axes_by_tag.get("slnt") if axis is not None: for upright_label in axis.axisLabels: if ( upright_label.linkedUserValue == userLocation[axis.name] # In the "recursive" case where both the Upright has # linkedUserValue pointing the Italic, and the Italic has # linkedUserValue pointing to the Upright, only consider the # first case: Upright (e.g. ital=0, slant=0) has # linkedUserValue pointing to Italic (e.g ital=1, slant=-12 or # slant=12 for backwards italics, in any case higher than # Upright in absolute value, hence the abs() below. and abs(upright_label.userValue) < abs(upright_label.linkedUserValue) ): regularUserLocation[axis.name] = upright_label.userValue italic = True break return BOLD_ITALIC_TO_RIBBI_STYLE[bold, italic], { **userLocation, **regularUserLocation, }
Compute the RIBBI style name of the given user location, return the location of the matching Regular in the RIBBI group. .. versionadded:: 5.0
_getRibbiStyle
python
fonttools/fonttools
Lib/fontTools/designspaceLib/statNames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/statNames.py
MIT
def posix(path): """Normalize paths using forward slash to work also on Windows.""" new_path = posixpath.join(*path.split(os.path.sep)) if path.startswith("/"): # The above transformation loses absolute paths new_path = "/" + new_path elif path.startswith(r"\\"): # The above transformation loses leading slashes of UNC path mounts new_path = "//" + new_path return new_path
Normalize paths using forward slash to work also on Windows.
posix
python
fonttools/fonttools
Lib/fontTools/designspaceLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
MIT
def posixpath_property(private_name): """Generate a propery that holds a path always using forward slashes.""" def getter(self): # Normal getter return getattr(self, private_name) def setter(self, value): # The setter rewrites paths using forward slashes if value is not None: value = posix(value) setattr(self, private_name, value) return property(getter, setter)
Generate a propery that holds a path always using forward slashes.
posixpath_property
python
fonttools/fonttools
Lib/fontTools/designspaceLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
MIT
def getFullDesignLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict: """Get the complete design location of this source, from its :attr:`designLocation` and the document's axis defaults. .. versionadded:: 5.0 """ result: SimpleLocationDict = {} for axis in doc.axes: if axis.name in self.designLocation: result[axis.name] = self.designLocation[axis.name] else: result[axis.name] = axis.map_forward(axis.default) return result
Get the complete design location of this source, from its :attr:`designLocation` and the document's axis defaults. .. versionadded:: 5.0
getFullDesignLocation
python
fonttools/fonttools
Lib/fontTools/designspaceLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
MIT