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 tenso...
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...
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...
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 ...
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() ...
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.zero...
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 wit...
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`. ...
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] # seriali...
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 ...
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....
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() correc...
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 ...
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 ...
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. ...
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]...
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(backb...
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
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): I...
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 ...
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. ...
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 ...
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 ...
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*h...
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 ...
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)) e...
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=RuntimeWarn...
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) ret...
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: ...
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.Ra...
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 ...
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 >>>...
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.be...
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' ...
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) ...
[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_c...
[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. i...
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(n...
[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.StreamHandle...
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 sel...
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"] i...
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") ch...
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 = {} ...
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...
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)...
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 <= 0x...
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`...
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 corr...
__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 Va...
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, v...
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...
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...
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 ...
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' t...
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 (...
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(...
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=[], ) s...
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 optiona...
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...
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(...
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`. """ fr...
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. `fo...
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 u...
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) sy...
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. t...
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 :met...
_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( ...
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.)""" # Cl...
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( ...
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.ex...
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,)) ...
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)) ...
_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, max...
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) ...
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 ...
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 as...
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): n...
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 ...
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 librar...
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("...
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"): sel...
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) """ ...
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...
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: ...
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] ...
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 ...
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...
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 name...
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: ...
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...
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[...
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 c...
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=...
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 handl...
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. ...
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 po...
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 cu...
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...
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: ...
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...
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: Loca...
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...
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, ``comp...
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 ...
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 cur...
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 max...
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 cur...
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 PointToSegmen...
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.moveT...
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_...
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_segme...
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...
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...
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, e...
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 nam...
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 b...
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...
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 T...
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 sta...
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 us...
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. .. ...
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, eithe...
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 (...
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 = so...
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 """ regularUserLocati...
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 tran...
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 Non...
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 ...
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