repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject.subset_otf_from_ufo | python | def subset_otf_from_ufo(self, otf_path, ufo):
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt) | Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L625-L680 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject.run_from_glyphs | python | def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs) | Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L682-L719 | [
"def run_from_designspace(\n self,\n designspace_path,\n output=(),\n interpolate=False,\n masters_as_instances=False,\n interpolate_binary_layout=False,\n round_instances=False,\n feature_writers=None,\n expand_features_to_instances=False,\n **kwargs\n):\n \"\"\"Run toolchain from a DesignSpace document to produce either static\n instance fonts (ttf or otf), interpolatable or variable fonts.\n\n Args:\n designspace_path: Path to designspace document.\n interpolate: If True output all instance fonts, otherwise just\n masters. If the value is a string, only build instance(s) that\n match given name. The string is compiled into a regular\n expression and matched against the \"name\" attribute of\n designspace instances using `re.fullmatch`.\n masters_as_instances: If True, output master fonts as instances.\n interpolate_binary_layout: Interpolate layout tables from compiled\n master binaries.\n round_instances: apply integer rounding when interpolating with\n MutatorMath.\n kwargs: Arguments passed along to run_from_ufos.\n\n Raises:\n TypeError: \"variable\" or \"interpolatable\" outputs are incompatible\n with arguments \"interpolate\", \"masters_as_instances\", and\n \"interpolate_binary_layout\".\n \"\"\"\n\n interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)\n static_outputs = STATIC_OUTPUTS.intersection(output)\n if interp_outputs:\n for argname in (\n \"interpolate\",\n \"masters_as_instances\",\n \"interpolate_binary_layout\",\n ):\n if locals()[argname]:\n raise TypeError(\n '\"%s\" argument incompatible with output %r'\n % (argname, \", \".join(sorted(interp_outputs)))\n )\n\n designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)\n\n # if no --feature-writers option was passed, check in the designspace's\n # <lib> element if user supplied a custom featureWriters configuration;\n # if so, use that for all the UFOs built from this designspace\n if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:\n feature_writers = loadFeatureWriters(designspace)\n\n if static_outputs:\n self._run_from_designspace_static(\n designspace,\n outputs=static_outputs,\n interpolate=interpolate,\n masters_as_instances=masters_as_instances,\n interpolate_binary_layout=interpolate_binary_layout,\n round_instances=round_instances,\n feature_writers=feature_writers,\n expand_features_to_instances=expand_features_to_instances,\n **kwargs\n )\n if interp_outputs:\n self._run_from_designspace_interpolatable(\n designspace,\n outputs=interp_outputs,\n feature_writers=feature_writers,\n **kwargs\n )\n"
] | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject.interpolate_instance_ufos | python | def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos | Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L721-L789 | [
"def _search_instances(designspace, pattern):\n instances = OrderedDict()\n for instance in designspace.instances:\n # is 'name' optional? 'filename' certainly must not be\n if fullmatch(pattern, instance.name):\n instances[instance.name] = instance.filename\n if not instances:\n raise FontmakeError(\"No instance found with %r\" % pattern)\n return instances\n"
] | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject.run_from_designspace | python | def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
) | Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout". | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L791-L866 | [
"def _run_from_designspace_static(\n self,\n designspace,\n outputs,\n interpolate=False,\n masters_as_instances=False,\n interpolate_binary_layout=False,\n round_instances=False,\n feature_writers=None,\n expand_features_to_instances=False,\n **kwargs\n):\n ufos = []\n if not interpolate or masters_as_instances:\n ufos.extend((s.path for s in designspace.sources if s.path))\n if interpolate:\n pattern = interpolate if isinstance(interpolate, basestring) else None\n ufos.extend(\n self.interpolate_instance_ufos(\n designspace,\n include=pattern,\n round_instances=round_instances,\n expand_features_to_instances=expand_features_to_instances,\n )\n )\n\n if interpolate_binary_layout is False:\n interpolate_layout_from = interpolate_layout_dir = None\n else:\n interpolate_layout_from = designspace\n if isinstance(interpolate_binary_layout, basestring):\n interpolate_layout_dir = interpolate_binary_layout\n else:\n interpolate_layout_dir = None\n\n self.run_from_ufos(\n ufos,\n output=outputs,\n is_instance=(interpolate or masters_as_instances),\n interpolate_layout_from=interpolate_layout_from,\n interpolate_layout_dir=interpolate_layout_dir,\n feature_writers=feature_writers,\n **kwargs\n )\n",
"def _run_from_designspace_interpolatable(\n self, designspace, outputs, output_path=None, output_dir=None, **kwargs\n):\n ttf_designspace = otf_designspace = None\n\n if \"variable\" in outputs:\n ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)\n self.build_variable_font(\n ttf_designspace, output_path=output_path, output_dir=output_dir\n )\n\n if \"ttf-interpolatable\" in outputs:\n if ttf_designspace is None:\n ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)\n self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)\n\n if \"variable-cff2\" in outputs:\n otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)\n self.build_variable_font(\n otf_designspace,\n output_path=output_path,\n output_dir=output_dir,\n ttf=False,\n )\n\n if \"otf-interpolatable\" in outputs:\n if otf_designspace is None:\n otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)\n self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)\n"
] | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject.run_from_ufos | python | def run_from_ufos(self, ufos, output=(), **kwargs):
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True | Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L943-L981 | [
"def build_otfs(self, ufos, **kwargs):\n \"\"\"Build OpenType binaries with CFF outlines.\"\"\"\n self.save_otfs(ufos, **kwargs)\n",
"def build_ttfs(self, ufos, **kwargs):\n \"\"\"Build OpenType binaries with TrueType outlines.\"\"\"\n self.save_otfs(ufos, ttf=True, **kwargs)\n"
] | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject._font_name | python | def _font_name(self, ufo):
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name) | Generate a postscript-style font name. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L994-L1006 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject._output_dir | python | def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir | Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L1008-L1040 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject._output_path | python | def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext)) | Generate output path for a font file with given extension. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L1042-L1074 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject._designspace_locations | python | def _designspace_locations(self, designspace):
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps | Map font filenames to their locations in a designspace. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L1076-L1086 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _closest_location(self, location_map, target):
"""Return path of font whose location is closest to target."""
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest
|
googlefonts/fontmake | Lib/fontmake/font_project.py | FontProject._closest_location | python | def _closest_location(self, location_map, target):
def dist(a, b):
return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))
paths = iter(location_map.keys())
closest = next(paths)
closest_dist = dist(target, location_map[closest])
for path in paths:
cur_dist = dist(target, location_map[path])
if cur_dist < closest_dist:
closest = path
closest_dist = cur_dist
return closest | Return path of font whose location is closest to target. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L1088-L1102 | null | class FontProject(object):
"""Provides methods for building fonts."""
def __init__(self, timing=False, verbose="INFO", validate_ufo=False):
logging.basicConfig(level=getattr(logging, verbose.upper()))
logging.getLogger("fontTools.subset").setLevel(logging.WARNING)
if timing:
configLogger(logger=timer.logger, level=logging.DEBUG)
logger.debug(
"ufoLib UFO validation is %s", "enabled" if validate_ufo else "disabled"
)
setUfoLibReadValidate(validate_ufo)
setUfoLibWriteValidate(validate_ufo)
@timer()
def build_master_ufos(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
):
"""Build UFOs and MutatorMath designspace from Glyphs source."""
import glyphsLib
if master_dir is None:
master_dir = self._output_dir("ufo")
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if instance_dir is None:
instance_dir = self._output_dir("ufo", is_instance=True)
if not os.path.isdir(instance_dir):
os.mkdir(instance_dir)
font = glyphsLib.GSFont(glyphs_path)
if designspace_path is not None:
designspace_dir = os.path.dirname(designspace_path)
else:
designspace_dir = master_dir
# glyphsLib.to_designspace expects instance_dir to be relative
instance_dir = os.path.relpath(instance_dir, designspace_dir)
designspace = glyphsLib.to_designspace(
font, family_name=family_name, instance_dir=instance_dir
)
masters = {}
# multiple sources can have the same font/filename (but different layer),
# we want to save a font only once
for source in designspace.sources:
if source.filename in masters:
assert source.font is masters[source.filename]
continue
ufo_path = os.path.join(master_dir, source.filename)
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
source.path = ufo_path
source.font.save(ufo_path)
masters[source.filename] = source.font
if designspace_path is None:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
if mti_source:
self.add_mti_features_to_master_ufos(mti_source, masters.values())
return designspace_path
@timer()
def add_mti_features_to_master_ufos(self, mti_source, masters):
mti_dir = os.path.dirname(mti_source)
with open(mti_source, "rb") as mti_file:
mti_paths = readPlist(mti_file)
for master in masters:
key = os.path.basename(master.path).rstrip(".ufo")
for table, path in mti_paths[key].items():
with open(os.path.join(mti_dir, path), "rb") as mti_source:
ufo_path = (
"com.github.googlei18n.ufo2ft.mtiFeatures/%s.mti"
% table.strip()
)
master.data[ufo_path] = mti_source.read()
# If we have MTI sources, any Adobe feature files derived from
# the Glyphs file should be ignored. We clear it here because
# it only contains junk information anyway.
master.features.text = ""
master.save()
@_deprecated
@timer()
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name)
for glyph in ufo:
if not glyph_filter(glyph):
continue
contours = list(glyph)
glyph.clearContours()
try:
union(contours, glyph.getPointPen())
except BooleanOperationsError:
logger.error(
"Failed to remove overlaps for %s: %r", font_name, glyph.name
)
raise
@_deprecated
@timer()
def decompose_glyphs(self, ufos, glyph_filter=lambda g: True):
"""Move components of UFOs' glyphs to their outlines."""
for ufo in ufos:
logger.info("Decomposing glyphs for " + self._font_name(ufo))
for glyph in ufo:
if not glyph.components or not glyph_filter(glyph):
continue
self._deep_copy_contours(ufo, glyph, glyph, Transform())
glyph.clearComponents()
def _deep_copy_contours(self, ufo, parent, component, transformation):
"""Copy contours from component to parent, including nested components."""
for nested in component.components:
self._deep_copy_contours(
ufo,
parent,
ufo[nested.baseGlyph],
transformation.transform(nested.transformation),
)
if component != parent:
pen = TransformPen(parent.getPen(), transformation)
# if the transformation has a negative determinant, it will reverse
# the contour direction of the component
xx, xy, yx, yy = transformation[:4]
if xx * yy - xy * yx < 0:
pen = ReverseContourPen(pen)
component.draw(pen)
@_deprecated
@timer()
def convert_curves(
self, ufos, compatible=False, reverse_direction=True, conversion_error=None
):
from cu2qu.ufo import font_to_quadratic, fonts_to_quadratic
if compatible:
logger.info("Converting curves compatibly")
fonts_to_quadratic(
ufos,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
else:
for ufo in ufos:
logger.info("Converting curves for " + self._font_name(ufo))
font_to_quadratic(
ufo,
max_err_em=conversion_error,
reverse_direction=reverse_direction,
dump_stats=True,
)
def build_otfs(self, ufos, **kwargs):
"""Build OpenType binaries with CFF outlines."""
self.save_otfs(ufos, **kwargs)
def build_ttfs(self, ufos, **kwargs):
"""Build OpenType binaries with TrueType outlines."""
self.save_otfs(ufos, ttf=True, **kwargs)
@staticmethod
def _load_designspace_sources(designspace):
# set source.font attributes, but only load fonts once
masters = {}
for source in designspace.sources:
if source.path in masters:
source.font = masters[source.path]
else:
assert source.path is not None
source.font = Font(source.path)
masters[source.path] = source.font
def _build_interpolatable_masters(
self,
designspace,
ttf,
use_production_names=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
cff_round_tolerance=None,
**kwargs
):
if hasattr(designspace, "__fspath__"):
ds_path = designspace.__fspath__()
if isinstance(designspace, basestring):
ds_path = designspace
else:
# reload designspace from its path so we have a new copy
# that can be modified in-place.
ds_path = designspace.path
if ds_path is not None:
designspace = designspaceLib.DesignSpaceDocument.fromfile(ds_path)
self._load_designspace_sources(designspace)
if ttf:
return ufo2ft.compileInterpolatableTTFsFromDS(
designspace,
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True,
)
else:
return ufo2ft.compileInterpolatableOTFsFromDS(
designspace,
useProductionNames=use_production_names,
roundTolerance=cff_round_tolerance,
featureWriters=feature_writers,
inplace=True,
)
def build_interpolatable_ttfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
def build_interpolatable_otfs(self, designspace, **kwargs):
"""Build OpenType binaries with interpolatable TrueType outlines
from DesignSpaceDocument object.
"""
return self._build_interpolatable_masters(designspace, ttf=False, **kwargs)
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
ext = "ttf" if ttf else "otf"
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
if master_bin_dir is None:
master_bin_dir = self._output_dir(ext, interpolatable=True)
finder = partial(_varLib_finder, directory=master_bin_dir)
else:
assert all(isinstance(s.font, TTFont) for s in designspace.sources)
finder = lambda s: s # noqa: E731
if output_path is None:
output_path = (
os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
)
output_path = self._output_path(
output_path, ext, is_variable=True, output_dir=output_dir
)
logger.info("Building variable font " + output_path)
font, _, _ = varLib.build(designspace, finder)
font.save(output_path)
def _iter_compile(self, ufos, ttf=False, **kwargs):
# generator function that calls ufo2ft compiler for each ufo and
# yields ttFont instances
options = dict(kwargs)
if ttf:
for key in ("optimizeCFF", "roundTolerance"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileTTF, "TTF"
else:
for key in ("cubicConversionError", "reverseDirection"):
options.pop(key, None)
compile_func, fmt = ufo2ft.compileOTF, "OTF"
for ufo in ufos:
name = self._font_name(ufo)
logger.info("Building {} for {}".format(fmt, name))
yield compile_func(ufo, **options)
@timer()
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_round_tolerance=None,
remove_overlaps=True,
overlaps_backend=None,
reverse_direction=True,
conversion_error=None,
feature_writers=None,
interpolate_layout_from=None,
interpolate_layout_dir=None,
output_path=None,
output_dir=None,
inplace=True,
):
"""Build OpenType binaries from UFOs.
Args:
ufos: Font objects to compile.
ttf: If True, build fonts with TrueType outlines and .ttf extension.
is_instance: If output fonts are instances, for generating paths.
interpolatable: If output is interpolatable, for generating paths.
use_afdko: If True, use AFDKO to compile feature source.
autohint: Parameters to provide to ttfautohint. If not provided, the
autohinting step is skipped.
subset: Whether to subset the output according to data in the UFOs.
If not provided, also determined by flags in the UFOs.
use_production_names: Whether to use production glyph names in the
output. If not provided, determined by flags in the UFOs.
subroutinize: If True, subroutinize CFF outlines in output.
cff_round_tolerance (float): controls the rounding of point
coordinates in CFF table. It is defined as the maximum absolute
difference between the original float and the rounded integer
value. By default, all floats are rounded to integer (tolerance
0.5); a value of 0 completely disables rounding; values in
between only round floats which are close to their integral
part within the tolerated range. Ignored if ttf=True.
remove_overlaps: If True, remove overlaps in glyph shapes.
overlaps_backend: name of the library to remove overlaps. Can be
either "booleanOperations" (default) or "pathops".
reverse_direction: If True, reverse contour directions when
compiling TrueType outlines.
conversion_error: Error to allow when converting cubic CFF contours
to quadratic TrueType contours.
feature_writers: list of ufo2ft-compatible feature writer classes
or pre-initialized objects that are passed on to ufo2ft
feature compiler to generate automatic feature code. The
default value (None) means that ufo2ft will use its built-in
default feature writers (for kern, mark, mkmk, etc.). An empty
list ([]) will skip any automatic feature generation.
interpolate_layout_from: A DesignSpaceDocument object to give varLib
for interpolating layout tables to use in output.
interpolate_layout_dir: Directory containing the compiled master
fonts to use for interpolating binary layout tables.
output_path: output font file path. Only works when the input
'ufos' list contains a single font.
output_dir: directory where to save output files. Mutually
exclusive with 'output_path' argument.
"""
assert not (output_path and output_dir), "mutually exclusive args"
if output_path is not None and len(ufos) > 1:
raise ValueError("output_path requires a single input")
if subroutinize is not None:
import warnings
warnings.warn(
"the 'subroutinize' argument is deprecated, use 'optimize_cff'",
UserWarning,
)
if subroutinize:
optimize_cff = CFFOptimization.SUBROUTINIZE
else:
# for b/w compatibility, we still run the charstring specializer
# even when --no-subroutinize is used. Use the new --optimize-cff
# option to disable both specilization and subroutinization
optimize_cff = CFFOptimization.SPECIALIZE
ext = "ttf" if ttf else "otf"
if interpolate_layout_from is not None:
if interpolate_layout_dir is None:
interpolate_layout_dir = self._output_dir(
ext, is_instance=False, interpolatable=interpolatable
)
finder = partial(_varLib_finder, directory=interpolate_layout_dir, ext=ext)
# no need to generate automatic features in ufo2ft, since here we
# are interpolating precompiled GPOS table with fontTools.varLib.
# An empty 'featureWriters' list tells ufo2ft to not generate any
# automatic features.
# TODO: Add an argument to ufo2ft.compileOTF/compileTTF to
# completely skip compiling features into OTL tables
feature_writers = []
compiler_options = dict(
useProductionNames=use_production_names,
reverseDirection=reverse_direction,
cubicConversionError=conversion_error,
featureWriters=feature_writers,
inplace=True, # avoid extra copy
)
if use_afdko:
compiler_options["featureCompilerClass"] = FDKFeatureCompiler
if interpolatable:
if not ttf:
raise NotImplementedError("interpolatable CFF not supported yet")
logger.info("Building interpolation-compatible TTFs")
fonts = ufo2ft.compileInterpolatableTTFs(ufos, **compiler_options)
else:
fonts = self._iter_compile(
ufos,
ttf,
removeOverlaps=remove_overlaps,
overlapsBackend=overlaps_backend,
optimizeCFF=optimize_cff,
roundTolerance=cff_round_tolerance,
**compiler_options
)
do_autohint = ttf and autohint is not None
for font, ufo in zip(fonts, ufos):
if interpolate_layout_from is not None:
master_locations, instance_locations = self._designspace_locations(
interpolate_layout_from
)
loc = instance_locations[_normpath(ufo.path)]
gpos_src = interpolate_layout(
interpolate_layout_from, loc, finder, mapped=True
)
font["GPOS"] = gpos_src["GPOS"]
gsub_src = TTFont(finder(self._closest_location(master_locations, loc)))
if "GDEF" in gsub_src:
font["GDEF"] = gsub_src["GDEF"]
if "GSUB" in gsub_src:
font["GSUB"] = gsub_src["GSUB"]
if do_autohint:
# if we are autohinting, we save the unhinted font to a
# temporary path, and the hinted one to the final destination
fd, otf_path = tempfile.mkstemp("." + ext)
os.close(fd)
elif output_path is None:
otf_path = self._output_path(
ufo, ext, is_instance, interpolatable, output_dir=output_dir
)
else:
otf_path = output_path
logger.info("Saving %s", otf_path)
font.save(otf_path)
# 'subset' is an Optional[bool], can be None, True or False.
# When False, we never subset; when True, we always do; when
# None (default), we check the presence of custom parameters
if subset is False:
pass
elif subset is True or (
(KEEP_GLYPHS_OLD_KEY in ufo.lib or KEEP_GLYPHS_NEW_KEY in ufo.lib)
or any(glyph.lib.get(GLYPH_EXPORT_KEY, True) is False for glyph in ufo)
):
self.subset_otf_from_ufo(otf_path, ufo)
if not do_autohint:
continue
if output_path is not None:
hinted_otf_path = output_path
else:
hinted_otf_path = self._output_path(
ufo,
ext,
is_instance,
interpolatable,
autohinted=True,
output_dir=output_dir,
)
try:
ttfautohint(otf_path, hinted_otf_path, args=autohint)
except TTFAError:
# copy unhinted font to destination before re-raising error
shutil.copyfile(otf_path, hinted_otf_path)
raise
finally:
# must clean up temp file
os.remove(otf_path)
def _save_interpolatable_fonts(self, designspace, output_dir, ttf):
ext = "ttf" if ttf else "otf"
for source in designspace.sources:
assert isinstance(source.font, TTFont)
otf_path = self._output_path(
source,
ext,
is_instance=False,
interpolatable=True,
output_dir=output_dir,
suffix=source.layerName,
)
logger.info("Saving %s", otf_path)
source.font.save(otf_path)
source.path = otf_path
source.layerName = None
for instance in designspace.instances:
instance.path = instance.filename = None
if output_dir is None:
output_dir = self._output_dir(ext, interpolatable=True)
designspace_path = os.path.join(output_dir, os.path.basename(designspace.path))
logger.info("Saving %s", designspace_path)
designspace.write(designspace_path)
def subset_otf_from_ufo(self, otf_path, ufo):
"""Subset a font using export flags set by glyphsLib.
There are two more settings that can change export behavior:
"Export Glyphs" and "Remove Glyphs", which are currently not supported
for complexity reasons. See
https://github.com/googlei18n/glyphsLib/issues/295.
"""
from fontTools import subset
# ufo2ft always inserts a ".notdef" glyph as the first glyph
ufo_order = makeOfficialGlyphOrder(ufo)
if ".notdef" not in ufo_order:
ufo_order.insert(0, ".notdef")
ot_order = TTFont(otf_path).getGlyphOrder()
assert ot_order[0] == ".notdef"
assert len(ufo_order) == len(ot_order)
for key in (KEEP_GLYPHS_NEW_KEY, KEEP_GLYPHS_OLD_KEY):
keep_glyphs_list = ufo.lib.get(key)
if keep_glyphs_list is not None:
keep_glyphs = set(keep_glyphs_list)
break
else:
keep_glyphs = None
include = []
for source_name, binary_name in zip(ufo_order, ot_order):
if keep_glyphs and source_name not in keep_glyphs:
continue
if source_name in ufo:
exported = ufo[source_name].lib.get(GLYPH_EXPORT_KEY, True)
if not exported:
continue
include.append(binary_name)
# copied from nototools.subset
opt = subset.Options()
opt.name_IDs = ["*"]
opt.name_legacy = True
opt.name_languages = ["*"]
opt.layout_features = ["*"]
opt.notdef_outline = True
opt.recalc_bounds = True
opt.recalc_timestamp = True
opt.canonical_order = True
opt.glyph_names = True
font = subset.load_font(otf_path, opt, lazy=False)
subsetter = subset.Subsetter(options=opt)
subsetter.populate(glyphs=include)
subsetter.subset(font)
subset.save_font(font, otf_path, opt)
def run_from_glyphs(
self,
glyphs_path,
designspace_path=None,
master_dir=None,
instance_dir=None,
family_name=None,
mti_source=None,
**kwargs
):
"""Run toolchain from Glyphs source.
Args:
glyphs_path: Path to source file.
designspace_path: Output path of generated designspace document.
By default it's "<family_name>[-<base_style>].designspace".
master_dir: Directory where to save UFO masters (default:
"master_ufo").
instance_dir: Directory where to save UFO instances (default:
"instance_ufo").
family_name: If provided, uses this family name in the output.
mti_source: Path to property list file containing a dictionary
mapping UFO masters to dictionaries mapping layout table
tags to MTI source paths which should be compiled into
those tables.
kwargs: Arguments passed along to run_from_designspace.
"""
logger.info("Building master UFOs and designspace from Glyphs source")
designspace_path = self.build_master_ufos(
glyphs_path,
designspace_path=designspace_path,
master_dir=master_dir,
instance_dir=instance_dir,
family_name=family_name,
mti_source=mti_source,
)
self.run_from_designspace(designspace_path, **kwargs)
def interpolate_instance_ufos(
self,
designspace,
include=None,
round_instances=False,
expand_features_to_instances=False,
):
"""Interpolate master UFOs with MutatorMath and return instance UFOs.
Args:
designspace: a DesignSpaceDocument object containing sources and
instances.
include (str): optional regular expression pattern to match the
DS instance 'name' attribute and only interpolate the matching
instances.
round_instances (bool): round instances' coordinates to integer.
expand_features_to_instances: parses the master feature file, expands all
include()s and writes the resulting full feature file to all instance
UFOs. Use this if you share feature files among masters in external
files. Otherwise, the relative include paths can break as instances
may end up elsewhere. Only done on interpolation.
Returns:
list of defcon.Font objects corresponding to the UFO instances.
Raises:
FontmakeError: if any of the sources defines a custom 'layer', for
this is not supported by MutatorMath.
ValueError: "expand_features_to_instances" is True but no source in the
designspace document is designated with '<features copy="1"/>'.
"""
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
if any(source.layerName is not None for source in designspace.sources):
raise FontmakeError(
"MutatorMath doesn't support DesignSpace sources with 'layer' "
"attribute"
)
# TODO: replace mutatorMath with ufoProcessor?
builder = DesignSpaceDocumentReader(
designspace.path, ufoVersion=3, roundGeometry=round_instances, verbose=True
)
logger.info("Interpolating master UFOs from designspace")
if include is not None:
instances = self._search_instances(designspace, pattern=include)
for instance_name in instances:
builder.readInstance(("name", instance_name))
filenames = set(instances.values())
else:
builder.readInstances()
filenames = None # will include all instances
logger.info("Applying instance data from designspace")
instance_ufos = apply_instance_data(designspace, include_filenames=filenames)
if expand_features_to_instances:
logger.debug("Expanding features to instance UFOs")
master_source = next(
(s for s in designspace.sources if s.copyFeatures), None
)
if not master_source:
raise ValueError("No source is designated as the master for features.")
else:
master_source_font = builder.sources[master_source.name][0]
master_source_features = parseLayoutFeatures(master_source_font).asFea()
for instance_ufo in instance_ufos:
instance_ufo.features.text = master_source_features
instance_ufo.save()
return instance_ufos
def run_from_designspace(
self,
designspace_path,
output=(),
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
"""Run toolchain from a DesignSpace document to produce either static
instance fonts (ttf or otf), interpolatable or variable fonts.
Args:
designspace_path: Path to designspace document.
interpolate: If True output all instance fonts, otherwise just
masters. If the value is a string, only build instance(s) that
match given name. The string is compiled into a regular
expression and matched against the "name" attribute of
designspace instances using `re.fullmatch`.
masters_as_instances: If True, output master fonts as instances.
interpolate_binary_layout: Interpolate layout tables from compiled
master binaries.
round_instances: apply integer rounding when interpolating with
MutatorMath.
kwargs: Arguments passed along to run_from_ufos.
Raises:
TypeError: "variable" or "interpolatable" outputs are incompatible
with arguments "interpolate", "masters_as_instances", and
"interpolate_binary_layout".
"""
interp_outputs = INTERPOLATABLE_OUTPUTS.intersection(output)
static_outputs = STATIC_OUTPUTS.intersection(output)
if interp_outputs:
for argname in (
"interpolate",
"masters_as_instances",
"interpolate_binary_layout",
):
if locals()[argname]:
raise TypeError(
'"%s" argument incompatible with output %r'
% (argname, ", ".join(sorted(interp_outputs)))
)
designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace_path)
# if no --feature-writers option was passed, check in the designspace's
# <lib> element if user supplied a custom featureWriters configuration;
# if so, use that for all the UFOs built from this designspace
if feature_writers is None and FEATURE_WRITERS_KEY in designspace.lib:
feature_writers = loadFeatureWriters(designspace)
if static_outputs:
self._run_from_designspace_static(
designspace,
outputs=static_outputs,
interpolate=interpolate,
masters_as_instances=masters_as_instances,
interpolate_binary_layout=interpolate_binary_layout,
round_instances=round_instances,
feature_writers=feature_writers,
expand_features_to_instances=expand_features_to_instances,
**kwargs
)
if interp_outputs:
self._run_from_designspace_interpolatable(
designspace,
outputs=interp_outputs,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_static(
self,
designspace,
outputs,
interpolate=False,
masters_as_instances=False,
interpolate_binary_layout=False,
round_instances=False,
feature_writers=None,
expand_features_to_instances=False,
**kwargs
):
ufos = []
if not interpolate or masters_as_instances:
ufos.extend((s.path for s in designspace.sources if s.path))
if interpolate:
pattern = interpolate if isinstance(interpolate, basestring) else None
ufos.extend(
self.interpolate_instance_ufos(
designspace,
include=pattern,
round_instances=round_instances,
expand_features_to_instances=expand_features_to_instances,
)
)
if interpolate_binary_layout is False:
interpolate_layout_from = interpolate_layout_dir = None
else:
interpolate_layout_from = designspace
if isinstance(interpolate_binary_layout, basestring):
interpolate_layout_dir = interpolate_binary_layout
else:
interpolate_layout_dir = None
self.run_from_ufos(
ufos,
output=outputs,
is_instance=(interpolate or masters_as_instances),
interpolate_layout_from=interpolate_layout_from,
interpolate_layout_dir=interpolate_layout_dir,
feature_writers=feature_writers,
**kwargs
)
def _run_from_designspace_interpolatable(
self, designspace, outputs, output_path=None, output_dir=None, **kwargs
):
ttf_designspace = otf_designspace = None
if "variable" in outputs:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self.build_variable_font(
ttf_designspace, output_path=output_path, output_dir=output_dir
)
if "ttf-interpolatable" in outputs:
if ttf_designspace is None:
ttf_designspace = self.build_interpolatable_ttfs(designspace, **kwargs)
self._save_interpolatable_fonts(ttf_designspace, output_dir, ttf=True)
if "variable-cff2" in outputs:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self.build_variable_font(
otf_designspace,
output_path=output_path,
output_dir=output_dir,
ttf=False,
)
if "otf-interpolatable" in outputs:
if otf_designspace is None:
otf_designspace = self.build_interpolatable_otfs(designspace, **kwargs)
self._save_interpolatable_fonts(otf_designspace, output_dir, ttf=False)
def run_from_ufos(self, ufos, output=(), **kwargs):
"""Run toolchain from UFO sources.
Args:
ufos: List of UFO sources, as either paths or opened objects.
output: List of output formats to generate.
kwargs: Arguments passed along to save_otfs.
"""
if set(output) == {"ufo"}:
return
# the `ufos` parameter can be a list of UFO objects
# or it can be a path (string) with a glob syntax
ufo_paths = []
if isinstance(ufos, basestring):
ufo_paths = glob.glob(ufos)
ufos = [Font(x) for x in ufo_paths]
elif isinstance(ufos, list):
# ufos can be either paths or open Font objects, so normalize them
ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
ufo_paths = [x.path for x in ufos]
else:
raise FontmakeError(
"UFOs parameter is neither a defcon.Font object, a path or a glob, "
"nor a list of any of these.",
ufos,
)
need_reload = False
if "otf" in output:
self.build_otfs(ufos, **kwargs)
need_reload = True
if "ttf" in output:
if need_reload:
ufos = [Font(path) for path in ufo_paths]
self.build_ttfs(ufos, **kwargs)
need_reload = True
@staticmethod
def _search_instances(designspace, pattern):
instances = OrderedDict()
for instance in designspace.instances:
# is 'name' optional? 'filename' certainly must not be
if fullmatch(pattern, instance.name):
instances[instance.name] = instance.filename
if not instances:
raise FontmakeError("No instance found with %r" % pattern)
return instances
def _font_name(self, ufo):
"""Generate a postscript-style font name."""
family_name = (
ufo.info.familyName.replace(" ", "")
if ufo.info.familyName is not None
else "None"
)
style_name = (
ufo.info.styleName.replace(" ", "")
if ufo.info.styleName is not None
else "None"
)
return "{}-{}".format(family_name, style_name)
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
"""Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The output is variable font or not.
Return:
output directory string.
"""
assert not (is_variable and any([is_instance, interpolatable]))
# FIXME? Use user configurable destination folders.
if is_variable:
dir_prefix = "variable_"
elif is_instance:
dir_prefix = "instance_"
else:
dir_prefix = "master_"
dir_suffix = "_interpolatable" if interpolatable else ""
output_dir = dir_prefix + ext + dir_suffix
if autohinted:
output_dir = os.path.join("autohinted", output_dir)
return output_dir
def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if isinstance(ufo_or_font_name, basestring):
font_name = ufo_or_font_name
elif ufo_or_font_name.path:
font_name = os.path.splitext(
os.path.basename(os.path.normpath(ufo_or_font_name.path))
)[0]
else:
font_name = self._font_name(ufo_or_font_name)
if output_dir is None:
output_dir = self._output_dir(
ext, is_instance, interpolatable, autohinted, is_variable
)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if suffix:
return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
else:
return os.path.join(output_dir, "{}.{}".format(font_name, ext))
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
location_map[path] = element.location
maps.append(location_map)
return maps
|
googlefonts/fontmake | Lib/fontmake/ttfautohint.py | ttfautohint | python | def ttfautohint(in_file, out_file, args=None, **kwargs):
arg_list = ["ttfautohint"]
file_args = [in_file, out_file]
if args is not None:
if kwargs:
raise TypeError("Should not provide both cmd args and kwargs.")
rv = subprocess.call(arg_list + args.split() + file_args)
if rv != 0:
raise TTFAError(rv)
return
boolean_options = (
"debug",
"composites",
"dehint",
"help",
"ignore_restrictions",
"detailed_info",
"no_info",
"adjust_subglyphs",
"symbol",
"ttfa_table",
"verbose",
"version",
"windows_compatibility",
)
other_options = (
"default_script",
"fallback_script",
"family_suffix",
"hinting_limit",
"fallback_stem_width",
"hinting_range_min",
"control_file",
"hinting_range_max",
"strong_stem_width",
"increase_x_height",
"x_height_snapping_exceptions",
)
for option in boolean_options:
if kwargs.pop(option, False):
arg_list.append("--" + option.replace("_", "-"))
for option in other_options:
arg = kwargs.pop(option, None)
if arg is not None:
arg_list.append("--{}={}".format(option.replace("_", "-"), arg))
if kwargs:
raise TypeError("Unexpected argument(s): " + ", ".join(kwargs.keys()))
rv = subprocess.call(arg_list + file_args)
if rv != 0:
raise TTFAError(rv) | Thin wrapper around the ttfautohint command line tool.
Can take in command line arguments directly as a string, or spelled out as
Python keyword arguments. | train | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/ttfautohint.py#L21-L82 | null | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
from fontmake.errors import TTFAError
|
robmarkcole/HASS-data-detective | detective/auth.py | auth_from_hass_config | python | def auth_from_hass_config(path=None, **kwargs):
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs) | Initialize auth from HASS config. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L8-L13 | [
"def find_hass_config():\n \"\"\"Try to find HASS config.\"\"\"\n if \"HASSIO_TOKEN\" in os.environ:\n return \"/config\"\n\n config_dir = default_hass_config_dir()\n\n if os.path.isdir(config_dir):\n return config_dir\n\n raise ValueError(\n \"Unable to automatically find the location of Home Assistant \"\n \"config. Please pass it in.\"\n )\n"
] | """Auth helper."""
import json
import os
from . import config
class Auth:
"""Class to hold auth."""
def __init__(self, auth_path):
"""Load auth data and store in class."""
with open(auth_path) as fp:
auth = json.load(fp)
self.users = {user["id"]: user for user in auth["data"]["users"]}
self.refresh_tokens = {
token["id"]: {
"id": token["id"],
"user": self.users[token["user_id"]],
"client_name": token["client_name"],
"client_id": token["client_id"],
}
for token in auth["data"]["refresh_tokens"]
}
def user_name(self, user_id):
"""Return name for user."""
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"]
|
robmarkcole/HASS-data-detective | detective/auth.py | Auth.user_name | python | def user_name(self, user_id):
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"] | Return name for user. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L35-L42 | null | class Auth:
"""Class to hold auth."""
def __init__(self, auth_path):
"""Load auth data and store in class."""
with open(auth_path) as fp:
auth = json.load(fp)
self.users = {user["id"]: user for user in auth["data"]["users"]}
self.refresh_tokens = {
token["id"]: {
"id": token["id"],
"user": self.users[token["user_id"]],
"client_name": token["client_name"],
"client_id": token["client_id"],
}
for token in auth["data"]["refresh_tokens"]
}
|
robmarkcole/HASS-data-detective | detective/config.py | default_hass_config_dir | python | def default_hass_config_dir():
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant") | Put together the default configuration directory based on the OS. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L10-L13 | null | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | find_hass_config | python | def find_hass_config():
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
) | Try to find HASS config. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L16-L29 | [
"def default_hass_config_dir():\n \"\"\"Put together the default configuration directory based on the OS.\"\"\"\n data_dir = os.getenv(\"APPDATA\") if os.name == \"nt\" else os.path.expanduser(\"~\")\n return os.path.join(data_dir, \".homeassistant\")\n"
] | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | _secret_yaml | python | def _secret_yaml(loader, node):
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None | Load secrets and embed it into the configuration YAML. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L36-L49 | null | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | _include_yaml | python | def _include_yaml(loader, node):
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value)) | Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L52-L58 | null | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | _stub_tag | python | def _stub_tag(constructor, node):
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {} | Stub a constructor with a dictionary. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L61-L72 | null | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | load_yaml | python | def load_yaml(fname):
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {} | Load a YAML file. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L89-L101 | null | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url
|
robmarkcole/HASS-data-detective | detective/config.py | db_url_from_hass_config | python | def db_url_from_hass_config(path):
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url | Find the recorder database url from a HASS config dir. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L104-L122 | [
"def load_hass_config(path):\n \"\"\"Load the HASS config.\"\"\"\n return load_yaml(os.path.join(path, \"configuration.yaml\"))\n"
] | """
Helper functions for config.
"""
import os
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
class HassSafeConstructor(SafeConstructor):
"""Hass specific SafeConstructor."""
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {}
HassSafeConstructor.add_constructor("!include", _include_yaml)
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
def load_hass_config(path):
"""Load the HASS config."""
return load_yaml(os.path.join(path, "configuration.yaml"))
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
|
robmarkcole/HASS-data-detective | detective/time.py | localize | python | def localize(dt):
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt | Localize a datetime object to local time. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/time.py#L19-L24 | null | """
Helper functions for datetimes.
"""
from datetime import datetime
import time
import pytz
UTC = pytz.UTC
# Ordered list of time categories that `time_category` produces
TIME_CATEGORIES = ["morning", "daytime", "evening", "night"]
# To localize the returned UTC times to local times
LOCAL_UTC_OFFSET = datetime.fromtimestamp(time.time()) - datetime.utcfromtimestamp(
time.time()
)
def is_weekday(dtObj):
"""Check a datetime object dtObj is a weekday"""
return dtObj.weekday() < 5
def time_category(dtObj):
"""Return a time category, bed, home, work, given a dtObj."""
if 9 <= dtObj.hour <= 17:
return "daytime"
elif 5 <= dtObj.hour < 9:
return "morning"
elif 17 < dtObj.hour < 23:
return "evening"
else:
return "night"
def sqlalch_datetime(dt):
"""Convert a SQLAlchemy datetime string to a datetime object."""
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return dt.replace(tzinfo=UTC)
|
robmarkcole/HASS-data-detective | detective/time.py | sqlalch_datetime | python | def sqlalch_datetime(dt):
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return dt.replace(tzinfo=UTC) | Convert a SQLAlchemy datetime string to a datetime object. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/time.py#L44-L50 | null | """
Helper functions for datetimes.
"""
from datetime import datetime
import time
import pytz
UTC = pytz.UTC
# Ordered list of time categories that `time_category` produces
TIME_CATEGORIES = ["morning", "daytime", "evening", "night"]
# To localize the returned UTC times to local times
LOCAL_UTC_OFFSET = datetime.fromtimestamp(time.time()) - datetime.utcfromtimestamp(
time.time()
)
def localize(dt):
"""Localize a datetime object to local time."""
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt
def is_weekday(dtObj):
"""Check a datetime object dtObj is a weekday"""
return dtObj.weekday() < 5
def time_category(dtObj):
"""Return a time category, bed, home, work, given a dtObj."""
if 9 <= dtObj.hour <= 17:
return "daytime"
elif 5 <= dtObj.hour < 9:
return "morning"
elif 17 < dtObj.hour < 23:
return "evening"
else:
return "night"
|
robmarkcole/HASS-data-detective | detective/core.py | db_from_hass_config | python | def db_from_hass_config(path=None, **kwargs):
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs) | Initialize a database from HASS config. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L14-L20 | [
"def find_hass_config():\n \"\"\"Try to find HASS config.\"\"\"\n if \"HASSIO_TOKEN\" in os.environ:\n return \"/config\"\n\n config_dir = default_hass_config_dir()\n\n if os.path.isdir(config_dir):\n return config_dir\n\n raise ValueError(\n \"Unable to automatically find the location of Home Assistant \"\n \"config. Please pass it in.\"\n )\n",
"def db_url_from_hass_config(path):\n \"\"\"Find the recorder database url from a HASS config dir.\"\"\"\n config = load_hass_config(path)\n default_path = os.path.join(path, \"home-assistant_v2.db\")\n default_url = \"sqlite:///{}\".format(default_path)\n\n recorder = config.get(\"recorder\")\n\n if recorder:\n db_url = recorder.get(\"db_url\")\n if db_url is not None:\n return db_url\n\n if not os.path.isfile(default_path):\n raise ValueError(\n \"Unable to determine DB url from hass config at {}\".format(path)\n )\n\n return default_url\n"
] | """
Classes and functions for parsing home-assistant data.
"""
from urllib.parse import urlparse
from typing import List
import matplotlib.pyplot as plt
import pandas as pd
from sqlalchemy import create_engine, text
from . import config, functions
def get_db_type(url):
return urlparse(url).scheme.split("+")[0]
def stripped_db_url(url):
"""Return a version of the DB url with the password stripped out."""
parsed = urlparse(url)
if parsed.password is None:
return url
return parsed._replace(
netloc="{}:***@{}".format(parsed.username, parsed.hostname)
).geturl()
class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
class NumericalSensors:
"""
Class handling numerical sensor data, acts on existing pandas dataframe.
"""
def __init__(self, master_df):
# Extract all the numerical sensors
sensors_num_df = master_df.query('domain == "sensor" & numerical == True')
sensors_num_df = sensors_num_df.astype("float")
# List of sensors
entities = list(sensors_num_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No sensor data available")
return
# Pivot sensor dataframe for plotting
sensors_num_df = sensors_num_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
sensors_num_df.index = pd.to_datetime(
sensors_num_df.index, errors="ignore", utc=True
)
sensors_num_df.index = sensors_num_df.index.tz_localize(None)
# ffil data as triggered on events
sensors_num_df = sensors_num_df.fillna(method="ffill")
sensors_num_df = sensors_num_df.dropna() # Drop any remaining nan.
self._sensors_num_df = sensors_num_df.copy()
def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
"""
Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities
"""
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc)
def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._sensors_num_df
class BinarySensors:
"""
Class handling binary sensor data.
"""
def __init__(self, master_df):
# Extract all the binary sensors with binary values
binary_df = master_df.query(
'domain == "binary_sensor" & (state == "on" | state == "off")'
)
# List of sensors
entities = list(binary_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No binary sensor data available")
return
# Binarise
binary_df["state"] = binary_df["state"].apply(
lambda x: functions.binary_state(x)
)
# Pivot
binary_df = binary_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
# Index to datetime
binary_df.index = pd.to_datetime(binary_df.index, errors="ignore", utc=True)
binary_df.index = binary_df.index.tz_localize(None)
self._binary_df = binary_df.copy()
return
def plot(self, entity):
"""
Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot
"""
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resampled.columns = ["value"]
fig, ax = plt.subplots(1, 1, figsize=(16, 2))
ax.fill_between(resampled.index, y1=0, y2=1, facecolor="royalblue", label="off")
ax.fill_between(
resampled.index,
y1=0,
y2=1,
where=(resampled["value"] > 0),
facecolor="red",
label="on",
)
ax.set_title(entity)
ax.set_xlabel("Date")
ax.set_frame_on(False)
ax.set_yticks([])
plt.legend(loc=(1.01, 0.7))
plt.show()
return
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._binary_df
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | stripped_db_url | python | def stripped_db_url(url):
parsed = urlparse(url)
if parsed.password is None:
return url
return parsed._replace(
netloc="{}:***@{}".format(parsed.username, parsed.hostname)
).geturl() | Return a version of the DB url with the password stripped out. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L27-L36 | null | """
Classes and functions for parsing home-assistant data.
"""
from urllib.parse import urlparse
from typing import List
import matplotlib.pyplot as plt
import pandas as pd
from sqlalchemy import create_engine, text
from . import config, functions
def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs)
def get_db_type(url):
return urlparse(url).scheme.split("+")[0]
class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
class NumericalSensors:
"""
Class handling numerical sensor data, acts on existing pandas dataframe.
"""
def __init__(self, master_df):
# Extract all the numerical sensors
sensors_num_df = master_df.query('domain == "sensor" & numerical == True')
sensors_num_df = sensors_num_df.astype("float")
# List of sensors
entities = list(sensors_num_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No sensor data available")
return
# Pivot sensor dataframe for plotting
sensors_num_df = sensors_num_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
sensors_num_df.index = pd.to_datetime(
sensors_num_df.index, errors="ignore", utc=True
)
sensors_num_df.index = sensors_num_df.index.tz_localize(None)
# ffil data as triggered on events
sensors_num_df = sensors_num_df.fillna(method="ffill")
sensors_num_df = sensors_num_df.dropna() # Drop any remaining nan.
self._sensors_num_df = sensors_num_df.copy()
def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
"""
Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities
"""
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc)
def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._sensors_num_df
class BinarySensors:
"""
Class handling binary sensor data.
"""
def __init__(self, master_df):
# Extract all the binary sensors with binary values
binary_df = master_df.query(
'domain == "binary_sensor" & (state == "on" | state == "off")'
)
# List of sensors
entities = list(binary_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No binary sensor data available")
return
# Binarise
binary_df["state"] = binary_df["state"].apply(
lambda x: functions.binary_state(x)
)
# Pivot
binary_df = binary_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
# Index to datetime
binary_df.index = pd.to_datetime(binary_df.index, errors="ignore", utc=True)
binary_df.index = binary_df.index.tz_localize(None)
self._binary_df = binary_df.copy()
return
def plot(self, entity):
"""
Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot
"""
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resampled.columns = ["value"]
fig, ax = plt.subplots(1, 1, figsize=(16, 2))
ax.fill_between(resampled.index, y1=0, y2=1, facecolor="royalblue", label="off")
ax.fill_between(
resampled.index,
y1=0,
y2=1,
where=(resampled["value"] > 0),
facecolor="red",
label="on",
)
ax.set_title(entity)
ax.set_xlabel("Date")
ax.set_frame_on(False)
ax.set_yticks([])
plt.legend(loc=(1.01, 0.7))
plt.show()
return
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._binary_df
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.perform_query | python | def perform_query(self, query, **params):
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise | Perform a query, where query is a string. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L74-L80 | null | class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.fetch_entities | python | def fetch_entities(self):
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities))) | Fetch entities for which we have data. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L82-L104 | [
"def perform_query(self, query, **params):\n \"\"\"Perform a query, where query is a string.\"\"\"\n try:\n return self.engine.execute(query, params)\n except:\n print(\"Error with query: {}\".format(query))\n raise\n"
] | class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.fetch_data_by_list | python | def fetch_data_by_list(self, entities: List[str], limit=50000):
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df | Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L106-L153 | [
"def perform_query(self, query, **params):\n \"\"\"Perform a query, where query is a string.\"\"\"\n try:\n return self.engine.execute(query, params)\n except:\n print(\"Error with query: {}\".format(query))\n raise\n"
] | class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.fetch_all_data | python | def fetch_all_data(self, limit=50000):
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.") | Fetch data for all entities. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L155-L179 | [
"def perform_query(self, query, **params):\n \"\"\"Perform a query, where query is a string.\"\"\"\n try:\n return self.engine.execute(query, params)\n except:\n print(\"Error with query: {}\".format(query))\n raise\n",
"def parse_all_data(self):\n \"\"\"Parses the master df.\"\"\"\n self._master_df.columns = [\"domain\", \"entity\", \"state\", \"last_changed\"]\n\n # Check if state is float and store in numericals category.\n self._master_df[\"numerical\"] = self._master_df[\"state\"].apply(\n lambda x: functions.isfloat(x)\n )\n\n # Multiindexing\n self._master_df.set_index(\n [\"domain\", \"entity\", \"numerical\", \"last_changed\"], inplace=True\n )\n"
] | class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
)
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.parse_all_data | python | def parse_all_data(self):
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
) | Parses the master df. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L181-L193 | null | class HassDatabase:
"""
Initializing the parser fetches all of the data from the database and
places it in a master pandas dataframe.
"""
def __init__(self, url, *, fetch_entities=True):
"""
Parameters
----------
url : str
The URL to the database.
"""
self.url = url
self._master_df = None
self._domains = None
self._entities = None
try:
self.engine = create_engine(url)
print("Successfully connected to database", stripped_db_url(url))
if fetch_entities:
self.fetch_entities()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
)
print(exc)
raise
self.db_type = get_db_type(url)
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))
def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Basic query from list of entities. Must be from same domain.
Attempts to unpack lists up to 2 deep.
Parameters
----------
entities : a list of entities
returns a df
"""
if not len(set([e.split(".")[0] for e in entities])) == 1:
print("Error: entities must be from same domain.")
return
if len(entities) == 1:
print("Must pass more than 1 entity.")
return
query = text(
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT :limit
""".format(
",".join("'{}'".format(ent) for ent in entities)
)
)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
df.index = pd.to_datetime(df.index, errors="ignore", utc=True)
try:
df["state"] = (
df["state"].mask(df["state"].eq("None")).dropna().astype(float)
)
df = df.pivot_table(index="last_changed", columns="entity", values="state")
df = df.fillna(method="ffill")
df = df.dropna() # Drop any remaining nan.
return df
except:
print("Error: entities were not all numericals, unformatted df.")
return df
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.")
@property
def master_df(self):
"""Return the dataframe holding numerical sensor data."""
return self._master_df
@property
def domains(self):
"""Return the domains."""
if self._domains is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._domains
@property
def entities(self):
"""Return the entities dict."""
if self._entities is None:
raise ValueError("Not initialized! Call entities.fetch_entities() first")
return self._entities
|
robmarkcole/HASS-data-detective | detective/core.py | NumericalSensors.correlations | python | def correlations(self):
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all | Calculate the correlation coefficients. | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L248-L272 | null | class NumericalSensors:
"""
Class handling numerical sensor data, acts on existing pandas dataframe.
"""
def __init__(self, master_df):
# Extract all the numerical sensors
sensors_num_df = master_df.query('domain == "sensor" & numerical == True')
sensors_num_df = sensors_num_df.astype("float")
# List of sensors
entities = list(sensors_num_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No sensor data available")
return
# Pivot sensor dataframe for plotting
sensors_num_df = sensors_num_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
sensors_num_df.index = pd.to_datetime(
sensors_num_df.index, errors="ignore", utc=True
)
sensors_num_df.index = sensors_num_df.index.tz_localize(None)
# ffil data as triggered on events
sensors_num_df = sensors_num_df.fillna(method="ffill")
sensors_num_df = sensors_num_df.dropna() # Drop any remaining nan.
self._sensors_num_df = sensors_num_df.copy()
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
"""
Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities
"""
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc)
def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._sensors_num_df
|
robmarkcole/HASS-data-detective | detective/core.py | NumericalSensors.export_to_csv | python | def export_to_csv(self, entities: List[str], filename="sensors.csv"):
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc) | Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L274-L290 | null | class NumericalSensors:
"""
Class handling numerical sensor data, acts on existing pandas dataframe.
"""
def __init__(self, master_df):
# Extract all the numerical sensors
sensors_num_df = master_df.query('domain == "sensor" & numerical == True')
sensors_num_df = sensors_num_df.astype("float")
# List of sensors
entities = list(sensors_num_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No sensor data available")
return
# Pivot sensor dataframe for plotting
sensors_num_df = sensors_num_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
sensors_num_df.index = pd.to_datetime(
sensors_num_df.index, errors="ignore", utc=True
)
sensors_num_df.index = sensors_num_df.index.tz_localize(None)
# ffil data as triggered on events
sensors_num_df = sensors_num_df.fillna(method="ffill")
sensors_num_df = sensors_num_df.dropna() # Drop any remaining nan.
self._sensors_num_df = sensors_num_df.copy()
def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
"""
Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities
"""
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc)
def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._sensors_num_df
|
robmarkcole/HASS-data-detective | detective/core.py | NumericalSensors.plot | python | def plot(self, entities: List[str]):
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return | Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L292-L305 | null | class NumericalSensors:
"""
Class handling numerical sensor data, acts on existing pandas dataframe.
"""
def __init__(self, master_df):
# Extract all the numerical sensors
sensors_num_df = master_df.query('domain == "sensor" & numerical == True')
sensors_num_df = sensors_num_df.astype("float")
# List of sensors
entities = list(sensors_num_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No sensor data available")
return
# Pivot sensor dataframe for plotting
sensors_num_df = sensors_num_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
sensors_num_df.index = pd.to_datetime(
sensors_num_df.index, errors="ignore", utc=True
)
sensors_num_df.index = sensors_num_df.index.tz_localize(None)
# ffil data as triggered on events
sensors_num_df = sensors_num_df.fillna(method="ffill")
sensors_num_df = sensors_num_df.dropna() # Drop any remaining nan.
self._sensors_num_df = sensors_num_df.copy()
def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
"""
Export selected sensor data to a csv.
Parameters
----------
filename : the name of the .csv file to create
entities : a list of numerical sensor entities
"""
if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
print("Invalid entities entered, aborting export_to_csv")
return
try:
self._sensors_num_df[entities].to_csv(path_or_buf=filename)
print(f"Successfully exported entered entities to {filename}")
except Exception as exc:
print(exc)
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._sensors_num_df
|
robmarkcole/HASS-data-detective | detective/core.py | BinarySensors.plot | python | def plot(self, entity):
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resampled.columns = ["value"]
fig, ax = plt.subplots(1, 1, figsize=(16, 2))
ax.fill_between(resampled.index, y1=0, y2=1, facecolor="royalblue", label="off")
ax.fill_between(
resampled.index,
y1=0,
y2=1,
where=(resampled["value"] > 0),
facecolor="red",
label="on",
)
ax.set_title(entity)
ax.set_xlabel("Date")
ax.set_frame_on(False)
ax.set_yticks([])
plt.legend(loc=(1.01, 0.7))
plt.show()
return | Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot | train | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L353-L381 | null | class BinarySensors:
"""
Class handling binary sensor data.
"""
def __init__(self, master_df):
# Extract all the binary sensors with binary values
binary_df = master_df.query(
'domain == "binary_sensor" & (state == "on" | state == "off")'
)
# List of sensors
entities = list(binary_df.index.get_level_values("entity").unique())
self._entities = entities
if len(entities) == 0:
print("No binary sensor data available")
return
# Binarise
binary_df["state"] = binary_df["state"].apply(
lambda x: functions.binary_state(x)
)
# Pivot
binary_df = binary_df.pivot_table(
index="last_changed", columns="entity", values="state"
)
# Index to datetime
binary_df.index = pd.to_datetime(binary_df.index, errors="ignore", utc=True)
binary_df.index = binary_df.index.tz_localize(None)
self._binary_df = binary_df.copy()
return
@property
def data(self):
"""Return the dataframe holding numerical sensor data."""
return self._binary_df
@property
def entities(self):
"""Return the list of sensors entities."""
return self._entities
|
shtalinberg/django-el-pagination | el_pagination/templatetags/el_pagination_tags.py | paginate | python | def paginate(parser, token, paginator_class=None):
# Validate arguments.
try:
tag_name, tag_args = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Use a regexp to catch args.
match = PAGINATE_EXPRESSION.match(tag_args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
kwargs = match.groupdict()
objects = kwargs.pop('objects')
# The variable name must be present if a nested context variable is passed.
if '.' in objects and kwargs['var_name'] is None:
msg = (
'%(tag)r tag requires a variable name `as` argumnent if the '
'queryset is provided as a nested context variable (%(objects)s). '
'You must either pass a direct queryset (e.g. taking advantage '
'of the `with` template tag) or provide a new variable name to '
'store the resulting queryset (e.g. `%(tag)s %(objects)s as '
'objects`).'
) % {'tag': tag_name, 'objects': objects}
raise template.TemplateSyntaxError(msg)
# Call the node.
return PaginateNode(paginator_class, objects, **kwargs) | Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* original variable (usually a queryset)
and add to the context another name that refers to entries of the current
page, e.g.:
.. code-block:: html+django
{% paginate entries as page_entries %}
The *as* argument is also useful when a nested context variable is provided
as queryset. In this case, and only in this case, the resulting variable
name is mandatory, e.g.:
.. code-block:: html+django
{% paginate entries.all as entries %}
The number of paginated entries is taken from settings, but you can
override the default locally, e.g.:
.. code-block:: html+django
{% paginate 20 entries %}
Of course you can mix it all:
.. code-block:: html+django
{% paginate 20 entries as paginated_entries %}
By default, the first page is displayed the first time you load the page,
but you can change this, e.g.:
.. code-block:: html+django
{% paginate entries starting from page 3 %}
When changing the default page, it is also possible to reference the last
page (or the second last page, and so on) by using negative indexes, e.g:
.. code-block:: html+django
{% paginate entries starting from page -1 %}
This can be also achieved using a template variable that was passed to the
context, e.g.:
.. code-block:: html+django
{% paginate entries starting from page page_number %}
If the passed page number does not exist, the first page is displayed.
If you have multiple paginations in the same page, you can change the
querydict key for the single pagination, e.g.:
.. code-block:: html+django
{% paginate entries using article_page %}
In this case *article_page* is intended to be a context variable, but you
can hardcode the key using quotes, e.g.:
.. code-block:: html+django
{% paginate entries using 'articles_at_page' %}
Again, you can mix it all (the order of arguments is important):
.. code-block:: html+django
{% paginate 20 entries
starting from page 3 using page_key as paginated_entries %}
Additionally you can pass a path to be used for the pagination:
.. code-block:: html+django
{% paginate 20 entries
using page_key with pagination_url as paginated_entries %}
This way you can easily create views acting as API endpoints, and point
your Ajax calls to that API. In this case *pagination_url* is considered a
context variable, but it is also possible to hardcode the URL, e.g.:
.. code-block:: html+django
{% paginate 20 entries with "/mypage/" %}
If you want the first page to contain a different number of items than
subsequent pages, you can separate the two values with a comma, e.g. if
you want 3 items on the first page and 10 on other pages:
.. code-block:: html+django
{% paginate 3,10 entries %}
You must use this tag before calling the {% show_more %} one. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L45-L185 | null | """Django Endless Pagination template tags."""
from __future__ import unicode_literals
import re
from django import template
from django.utils.encoding import iri_to_uri
from django.http import Http404
from el_pagination import (
models,
settings,
utils,
)
from el_pagination.paginators import (
DefaultPaginator,
EmptyPage,
LazyPaginator,
)
PAGINATE_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(((?P<first_page>\w+)\,)?(?P<per_page>\w+)\s+)? # First page, per page.
(?P<objects>[\.\w]+) # Objects / queryset.
(\s+starting\s+from\s+page\s+(?P<number>[\-]?\d+|\w+))? # Page start.
(\s+using\s+(?P<key>[\"\'\-\w]+))? # Querystring key.
(\s+with\s+(?P<override_path>[\"\'\/\w]+))? # Override path.
(\s+as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(starting\s+from\s+page\s+(?P<number>\w+))?\s* # Page start.
(using\s+(?P<key>[\"\'\-\w]+))?\s* # Querystring key.
(as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
register = template.Library()
@register.tag
@register.tag
def lazy_paginate(parser, token):
"""Lazy paginate objects.
Paginate objects without hitting the database with a *select count* query.
Use this the same way as *paginate* tag when you are not interested
in the total number of pages.
"""
return paginate(parser, token, paginator_class=LazyPaginator)
class PaginateNode(template.Node):
"""Add to context the objects of the current page.
Also add the Django paginator's *page* object.
"""
def __init__(
self, paginator_class, objects, first_page=None, per_page=None,
var_name=None, number=None, key=None, override_path=None):
self.paginator = paginator_class or DefaultPaginator
self.objects = template.Variable(objects)
# If *var_name* is not passed, then the queryset name will be used.
self.var_name = objects if var_name is None else var_name
# If *per_page* is not passed then the default value form settings
# will be used.
self.per_page_variable = None
if per_page is None:
self.per_page = settings.PER_PAGE
elif per_page.isdigit():
self.per_page = int(per_page)
else:
self.per_page_variable = template.Variable(per_page)
# Handle first page: if it is not passed then *per_page* is used.
self.first_page_variable = None
if first_page is None:
self.first_page = None
elif first_page.isdigit():
self.first_page = int(first_page)
else:
self.first_page_variable = template.Variable(first_page)
# Handle page number when it is not specified in querystring.
self.page_number_variable = None
if number is None:
self.page_number = 1
else:
try:
self.page_number = int(number)
except ValueError:
self.page_number_variable = template.Variable(number)
# Set the querystring key attribute.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Handle *override_path*.
self.override_path_variable = None
if override_path is None:
self.override_path = None
elif (
override_path[0] in ('"', "'") and
override_path[-1] == override_path[0]):
self.override_path = override_path[1:-1]
else:
self.override_path_variable = template.Variable(override_path)
def render(self, context):
# Handle page number when it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# Calculate the number of items to show on each page.
if self.per_page_variable is None:
per_page = self.per_page
else:
per_page = int(self.per_page_variable.resolve(context))
# Calculate the number of items to show in the first page.
if self.first_page_variable is None:
first_page = self.first_page or per_page
else:
first_page = int(self.first_page_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# Retrieve the override path if used.
if self.override_path_variable is None:
override_path = self.override_path
else:
override_path = self.override_path_variable.resolve(context)
# Retrieve the queryset and create the paginator object.
objects = self.objects.resolve(context)
paginator = self.paginator(
objects, per_page, first_page=first_page, orphans=settings.ORPHANS)
# Normalize the default page number if a negative one is provided.
if default_number < 0:
default_number = utils.normalize_page_number(
default_number, paginator.page_range)
# The current request is used to get the requested page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
# Get the page.
try:
page = paginator.page(page_number)
except EmptyPage:
page = paginator.page(1)
if settings.PAGE_OUT_OF_RANGE_404:
raise Http404('Page out of range')
# Populate the context with required data.
data = {
'default_number': default_number,
'override_path': override_path,
'page': page,
'querystring_key': querystring_key,
}
context.update({'endless': data, self.var_name: page.object_list})
return ''
@register.inclusion_tag('el_pagination/show_more.html', takes_context=True)
def show_more(context, label=None, loading=settings.LOADING, class_name=None):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
You could pass in the extra CSS style class name as a third argument
{% show_more "even more" "working" "class_name" %}
Must be called after ``{% paginate objects %}``.
"""
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the showmore template.
data = utils.get_data_from_context(context)
page = data['page']
# show the template only if there is a next page
if page.has_next():
request = context['request']
page_number = page.next_page_number()
# Generate the querystring.
querystring_key = data['querystring_key']
querystring = utils.get_querystring_for_page(
request, page_number, querystring_key,
default_number=data['default_number'])
return {
'label': label,
'loading': loading,
'class_name': class_name,
'path': iri_to_uri(data['override_path'] or request.path),
'querystring': querystring,
'querystring_key': querystring_key,
'request': request,
}
# No next page, nothing to see.
return {}
@register.tag
def get_pages(parser, token):
"""Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in different ways:
- just print *pages.get_rendered* and you will get Digg-style pagination displayed:
.. code-block:: html+django
{{ pages.get_rendered }}
- display pages count:
.. code-block:: html+django
{{ pages|length }}
- check if the page list contains more than one page:
.. code-block:: html+django
{{ pages.paginated }}
{# the following is equivalent #}
{{ pages|length > 1 }}
- get a specific page:
.. code-block:: html+django
{# the current selected page #}
{{ pages.current }}
{# the first page #}
{{ pages.first }}
{# the last page #}
{{ pages.last }}
{# the previous page (or nothing if you are on first page) #}
{{ pages.previous }}
{# the next page (or nothing if you are in last page) #}
{{ pages.next }}
{# the third page #}
{{ pages.3 }}
{# this means page.1 is the same as page.first #}
{# the 1-based index of the first item on the current page #}
{{ pages.current_start_index }}
{# the 1-based index of the last item on the current page #}
{{ pages.current_end_index }}
{# the total number of objects, across all pages #}
{{ pages.total_count }}
{# the first page represented as an arrow #}
{{ pages.first_as_arrow }}
{# the last page represented as an arrow #}
{{ pages.last_as_arrow }}
- iterate over *pages* to get all pages:
.. code-block:: html+django
{% for page in pages %}
{# display page link #}
{{ page.render_link}}
{# the page url (beginning with "?") #}
{{ page.url }}
{# the page path #}
{{ page.path }}
{# the page number #}
{{ page.number }}
{# a string representing the page (commonly the page number) #}
{{ page.label }}
{# check if the page is the current one #}
{{ page.is_current }}
{# check if the page is the first one #}
{{ page.is_first }}
{# check if the page is the last one #}
{{ page.is_last }}
{% endfor %}
You can change the variable name, e.g.:
.. code-block:: html+django
{% get_pages as page_links %}
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
var_name = 'pages'
else:
args = args.split()
if len(args) == 2 and args[0] == 'as':
var_name = args[1]
else:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Call the node.
return GetPagesNode(var_name)
class GetPagesNode(template.Node):
"""Add the page list to context."""
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Add the PageList instance to the context.
context[self.var_name] = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
context=context,
default_number=data['default_number'],
override_path=data['override_path'],
)
return ''
@register.tag
def show_pages(parser, token):
"""Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py*
to a callable, or to a dotted path representing a callable, used to
customize the pages that are displayed.
See the *__unicode__* method of ``endless_pagination.models.PageList`` for
a detailed explanation of how the callable can be used.
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
if len(token.contents.split()) != 1:
msg = '%r tag takes no arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Call the node.
return ShowPagesNode()
class ShowPagesNode(template.Node):
"""Show the pagination."""
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Return the string representation of the sequence of pages.
pages = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
default_number=data['default_number'],
override_path=data['override_path'],
context=context
)
return pages.get_rendered()
@register.tag
def show_current_number(parser, token):
"""Show the current page number, or insert it in the context.
This tag can for example be useful to change the page title according to
the current page number.
To just show current page number:
.. code-block:: html+django
{% show_current_number %}
If you use multiple paginations in the same page, you can get the page
number for a specific pagination using the querystring key, e.g.:
.. code-block:: html+django
{% show_current_number using mykey %}
The default page when no querystring is specified is 1. If you changed it
in the `paginate`_ template tag, you have to call ``show_current_number``
according to your choice, e.g.:
.. code-block:: html+django
{% show_current_number starting from page 3 %}
This can be also achieved using a template variable you passed to the
context, e.g.:
.. code-block:: html+django
{% show_current_number starting from page page_number %}
You can of course mix it all (the order of arguments is important):
.. code-block:: html+django
{% show_current_number starting from page 3 using mykey %}
If you want to insert the current page number in the context, without
actually displaying it in the template, use the *as* argument, i.e.:
.. code-block:: html+django
{% show_current_number as page_number %}
{% show_current_number
starting from page 3 using mykey as page_number %}
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
key = None
number = None
tag_name = token.contents[0]
var_name = None
else:
# Use a regexp to catch args.
match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
groupdict = match.groupdict()
key = groupdict['key']
number = groupdict['number']
var_name = groupdict['var_name']
# Call the node.
return ShowCurrentNumberNode(number, key, var_name)
class ShowCurrentNumberNode(template.Node):
"""Show the page number taken from context."""
def __init__(self, number, key, var_name):
# Retrieve the page number.
self.page_number_variable = None
if number is None:
self.page_number = 1
elif number.isdigit():
self.page_number = int(number)
else:
self.page_number_variable = template.Variable(number)
# Get the queystring key.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Get the template variable name.
self.var_name = var_name
def render(self, context):
# Get the page number to use if it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# The request object is used to retrieve the current page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
if self.var_name is None:
return utils.text(page_number)
context[self.var_name] = page_number
return ''
|
shtalinberg/django-el-pagination | el_pagination/templatetags/el_pagination_tags.py | get_pages | python | def get_pages(parser, token):
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
var_name = 'pages'
else:
args = args.split()
if len(args) == 2 and args[0] == 'as':
var_name = args[1]
else:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Call the node.
return GetPagesNode(var_name) | Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in different ways:
- just print *pages.get_rendered* and you will get Digg-style pagination displayed:
.. code-block:: html+django
{{ pages.get_rendered }}
- display pages count:
.. code-block:: html+django
{{ pages|length }}
- check if the page list contains more than one page:
.. code-block:: html+django
{{ pages.paginated }}
{# the following is equivalent #}
{{ pages|length > 1 }}
- get a specific page:
.. code-block:: html+django
{# the current selected page #}
{{ pages.current }}
{# the first page #}
{{ pages.first }}
{# the last page #}
{{ pages.last }}
{# the previous page (or nothing if you are on first page) #}
{{ pages.previous }}
{# the next page (or nothing if you are in last page) #}
{{ pages.next }}
{# the third page #}
{{ pages.3 }}
{# this means page.1 is the same as page.first #}
{# the 1-based index of the first item on the current page #}
{{ pages.current_start_index }}
{# the 1-based index of the last item on the current page #}
{{ pages.current_end_index }}
{# the total number of objects, across all pages #}
{{ pages.total_count }}
{# the first page represented as an arrow #}
{{ pages.first_as_arrow }}
{# the last page represented as an arrow #}
{{ pages.last_as_arrow }}
- iterate over *pages* to get all pages:
.. code-block:: html+django
{% for page in pages %}
{# display page link #}
{{ page.render_link}}
{# the page url (beginning with "?") #}
{{ page.url }}
{# the page path #}
{{ page.path }}
{# the page number #}
{{ page.number }}
{# a string representing the page (commonly the page number) #}
{{ page.label }}
{# check if the page is the current one #}
{{ page.is_current }}
{# check if the page is the first one #}
{{ page.is_first }}
{# check if the page is the last one #}
{{ page.is_last }}
{% endfor %}
You can change the variable name, e.g.:
.. code-block:: html+django
{% get_pages as page_links %}
Must be called after ``{% paginate objects %}``. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L378-L500 | null | """Django Endless Pagination template tags."""
from __future__ import unicode_literals
import re
from django import template
from django.utils.encoding import iri_to_uri
from django.http import Http404
from el_pagination import (
models,
settings,
utils,
)
from el_pagination.paginators import (
DefaultPaginator,
EmptyPage,
LazyPaginator,
)
PAGINATE_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(((?P<first_page>\w+)\,)?(?P<per_page>\w+)\s+)? # First page, per page.
(?P<objects>[\.\w]+) # Objects / queryset.
(\s+starting\s+from\s+page\s+(?P<number>[\-]?\d+|\w+))? # Page start.
(\s+using\s+(?P<key>[\"\'\-\w]+))? # Querystring key.
(\s+with\s+(?P<override_path>[\"\'\/\w]+))? # Override path.
(\s+as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(starting\s+from\s+page\s+(?P<number>\w+))?\s* # Page start.
(using\s+(?P<key>[\"\'\-\w]+))?\s* # Querystring key.
(as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
register = template.Library()
@register.tag
def paginate(parser, token, paginator_class=None):
"""Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* original variable (usually a queryset)
and add to the context another name that refers to entries of the current
page, e.g.:
.. code-block:: html+django
{% paginate entries as page_entries %}
The *as* argument is also useful when a nested context variable is provided
as queryset. In this case, and only in this case, the resulting variable
name is mandatory, e.g.:
.. code-block:: html+django
{% paginate entries.all as entries %}
The number of paginated entries is taken from settings, but you can
override the default locally, e.g.:
.. code-block:: html+django
{% paginate 20 entries %}
Of course you can mix it all:
.. code-block:: html+django
{% paginate 20 entries as paginated_entries %}
By default, the first page is displayed the first time you load the page,
but you can change this, e.g.:
.. code-block:: html+django
{% paginate entries starting from page 3 %}
When changing the default page, it is also possible to reference the last
page (or the second last page, and so on) by using negative indexes, e.g:
.. code-block:: html+django
{% paginate entries starting from page -1 %}
This can be also achieved using a template variable that was passed to the
context, e.g.:
.. code-block:: html+django
{% paginate entries starting from page page_number %}
If the passed page number does not exist, the first page is displayed.
If you have multiple paginations in the same page, you can change the
querydict key for the single pagination, e.g.:
.. code-block:: html+django
{% paginate entries using article_page %}
In this case *article_page* is intended to be a context variable, but you
can hardcode the key using quotes, e.g.:
.. code-block:: html+django
{% paginate entries using 'articles_at_page' %}
Again, you can mix it all (the order of arguments is important):
.. code-block:: html+django
{% paginate 20 entries
starting from page 3 using page_key as paginated_entries %}
Additionally you can pass a path to be used for the pagination:
.. code-block:: html+django
{% paginate 20 entries
using page_key with pagination_url as paginated_entries %}
This way you can easily create views acting as API endpoints, and point
your Ajax calls to that API. In this case *pagination_url* is considered a
context variable, but it is also possible to hardcode the URL, e.g.:
.. code-block:: html+django
{% paginate 20 entries with "/mypage/" %}
If you want the first page to contain a different number of items than
subsequent pages, you can separate the two values with a comma, e.g. if
you want 3 items on the first page and 10 on other pages:
.. code-block:: html+django
{% paginate 3,10 entries %}
You must use this tag before calling the {% show_more %} one.
"""
# Validate arguments.
try:
tag_name, tag_args = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Use a regexp to catch args.
match = PAGINATE_EXPRESSION.match(tag_args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
kwargs = match.groupdict()
objects = kwargs.pop('objects')
# The variable name must be present if a nested context variable is passed.
if '.' in objects and kwargs['var_name'] is None:
msg = (
'%(tag)r tag requires a variable name `as` argumnent if the '
'queryset is provided as a nested context variable (%(objects)s). '
'You must either pass a direct queryset (e.g. taking advantage '
'of the `with` template tag) or provide a new variable name to '
'store the resulting queryset (e.g. `%(tag)s %(objects)s as '
'objects`).'
) % {'tag': tag_name, 'objects': objects}
raise template.TemplateSyntaxError(msg)
# Call the node.
return PaginateNode(paginator_class, objects, **kwargs)
@register.tag
def lazy_paginate(parser, token):
"""Lazy paginate objects.
Paginate objects without hitting the database with a *select count* query.
Use this the same way as *paginate* tag when you are not interested
in the total number of pages.
"""
return paginate(parser, token, paginator_class=LazyPaginator)
class PaginateNode(template.Node):
"""Add to context the objects of the current page.
Also add the Django paginator's *page* object.
"""
def __init__(
self, paginator_class, objects, first_page=None, per_page=None,
var_name=None, number=None, key=None, override_path=None):
self.paginator = paginator_class or DefaultPaginator
self.objects = template.Variable(objects)
# If *var_name* is not passed, then the queryset name will be used.
self.var_name = objects if var_name is None else var_name
# If *per_page* is not passed then the default value form settings
# will be used.
self.per_page_variable = None
if per_page is None:
self.per_page = settings.PER_PAGE
elif per_page.isdigit():
self.per_page = int(per_page)
else:
self.per_page_variable = template.Variable(per_page)
# Handle first page: if it is not passed then *per_page* is used.
self.first_page_variable = None
if first_page is None:
self.first_page = None
elif first_page.isdigit():
self.first_page = int(first_page)
else:
self.first_page_variable = template.Variable(first_page)
# Handle page number when it is not specified in querystring.
self.page_number_variable = None
if number is None:
self.page_number = 1
else:
try:
self.page_number = int(number)
except ValueError:
self.page_number_variable = template.Variable(number)
# Set the querystring key attribute.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Handle *override_path*.
self.override_path_variable = None
if override_path is None:
self.override_path = None
elif (
override_path[0] in ('"', "'") and
override_path[-1] == override_path[0]):
self.override_path = override_path[1:-1]
else:
self.override_path_variable = template.Variable(override_path)
def render(self, context):
# Handle page number when it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# Calculate the number of items to show on each page.
if self.per_page_variable is None:
per_page = self.per_page
else:
per_page = int(self.per_page_variable.resolve(context))
# Calculate the number of items to show in the first page.
if self.first_page_variable is None:
first_page = self.first_page or per_page
else:
first_page = int(self.first_page_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# Retrieve the override path if used.
if self.override_path_variable is None:
override_path = self.override_path
else:
override_path = self.override_path_variable.resolve(context)
# Retrieve the queryset and create the paginator object.
objects = self.objects.resolve(context)
paginator = self.paginator(
objects, per_page, first_page=first_page, orphans=settings.ORPHANS)
# Normalize the default page number if a negative one is provided.
if default_number < 0:
default_number = utils.normalize_page_number(
default_number, paginator.page_range)
# The current request is used to get the requested page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
# Get the page.
try:
page = paginator.page(page_number)
except EmptyPage:
page = paginator.page(1)
if settings.PAGE_OUT_OF_RANGE_404:
raise Http404('Page out of range')
# Populate the context with required data.
data = {
'default_number': default_number,
'override_path': override_path,
'page': page,
'querystring_key': querystring_key,
}
context.update({'endless': data, self.var_name: page.object_list})
return ''
@register.inclusion_tag('el_pagination/show_more.html', takes_context=True)
def show_more(context, label=None, loading=settings.LOADING, class_name=None):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
You could pass in the extra CSS style class name as a third argument
{% show_more "even more" "working" "class_name" %}
Must be called after ``{% paginate objects %}``.
"""
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the showmore template.
data = utils.get_data_from_context(context)
page = data['page']
# show the template only if there is a next page
if page.has_next():
request = context['request']
page_number = page.next_page_number()
# Generate the querystring.
querystring_key = data['querystring_key']
querystring = utils.get_querystring_for_page(
request, page_number, querystring_key,
default_number=data['default_number'])
return {
'label': label,
'loading': loading,
'class_name': class_name,
'path': iri_to_uri(data['override_path'] or request.path),
'querystring': querystring,
'querystring_key': querystring_key,
'request': request,
}
# No next page, nothing to see.
return {}
@register.tag
class GetPagesNode(template.Node):
"""Add the page list to context."""
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Add the PageList instance to the context.
context[self.var_name] = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
context=context,
default_number=data['default_number'],
override_path=data['override_path'],
)
return ''
@register.tag
def show_pages(parser, token):
"""Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py*
to a callable, or to a dotted path representing a callable, used to
customize the pages that are displayed.
See the *__unicode__* method of ``endless_pagination.models.PageList`` for
a detailed explanation of how the callable can be used.
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
if len(token.contents.split()) != 1:
msg = '%r tag takes no arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Call the node.
return ShowPagesNode()
class ShowPagesNode(template.Node):
"""Show the pagination."""
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Return the string representation of the sequence of pages.
pages = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
default_number=data['default_number'],
override_path=data['override_path'],
context=context
)
return pages.get_rendered()
@register.tag
def show_current_number(parser, token):
"""Show the current page number, or insert it in the context.
This tag can for example be useful to change the page title according to
the current page number.
To just show current page number:
.. code-block:: html+django
{% show_current_number %}
If you use multiple paginations in the same page, you can get the page
number for a specific pagination using the querystring key, e.g.:
.. code-block:: html+django
{% show_current_number using mykey %}
The default page when no querystring is specified is 1. If you changed it
in the `paginate`_ template tag, you have to call ``show_current_number``
according to your choice, e.g.:
.. code-block:: html+django
{% show_current_number starting from page 3 %}
This can be also achieved using a template variable you passed to the
context, e.g.:
.. code-block:: html+django
{% show_current_number starting from page page_number %}
You can of course mix it all (the order of arguments is important):
.. code-block:: html+django
{% show_current_number starting from page 3 using mykey %}
If you want to insert the current page number in the context, without
actually displaying it in the template, use the *as* argument, i.e.:
.. code-block:: html+django
{% show_current_number as page_number %}
{% show_current_number
starting from page 3 using mykey as page_number %}
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
key = None
number = None
tag_name = token.contents[0]
var_name = None
else:
# Use a regexp to catch args.
match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
groupdict = match.groupdict()
key = groupdict['key']
number = groupdict['number']
var_name = groupdict['var_name']
# Call the node.
return ShowCurrentNumberNode(number, key, var_name)
class ShowCurrentNumberNode(template.Node):
"""Show the page number taken from context."""
def __init__(self, number, key, var_name):
# Retrieve the page number.
self.page_number_variable = None
if number is None:
self.page_number = 1
elif number.isdigit():
self.page_number = int(number)
else:
self.page_number_variable = template.Variable(number)
# Get the queystring key.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Get the template variable name.
self.var_name = var_name
def render(self, context):
# Get the page number to use if it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# The request object is used to retrieve the current page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
if self.var_name is None:
return utils.text(page_number)
context[self.var_name] = page_number
return ''
|
shtalinberg/django-el-pagination | el_pagination/templatetags/el_pagination_tags.py | show_pages | python | def show_pages(parser, token):
# Validate args.
if len(token.contents.split()) != 1:
msg = '%r tag takes no arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Call the node.
return ShowPagesNode() | Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py*
to a callable, or to a dotted path representing a callable, used to
customize the pages that are displayed.
See the *__unicode__* method of ``endless_pagination.models.PageList`` for
a detailed explanation of how the callable can be used.
Must be called after ``{% paginate objects %}``. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L526-L556 | null | """Django Endless Pagination template tags."""
from __future__ import unicode_literals
import re
from django import template
from django.utils.encoding import iri_to_uri
from django.http import Http404
from el_pagination import (
models,
settings,
utils,
)
from el_pagination.paginators import (
DefaultPaginator,
EmptyPage,
LazyPaginator,
)
PAGINATE_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(((?P<first_page>\w+)\,)?(?P<per_page>\w+)\s+)? # First page, per page.
(?P<objects>[\.\w]+) # Objects / queryset.
(\s+starting\s+from\s+page\s+(?P<number>[\-]?\d+|\w+))? # Page start.
(\s+using\s+(?P<key>[\"\'\-\w]+))? # Querystring key.
(\s+with\s+(?P<override_path>[\"\'\/\w]+))? # Override path.
(\s+as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(starting\s+from\s+page\s+(?P<number>\w+))?\s* # Page start.
(using\s+(?P<key>[\"\'\-\w]+))?\s* # Querystring key.
(as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
register = template.Library()
@register.tag
def paginate(parser, token, paginator_class=None):
"""Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* original variable (usually a queryset)
and add to the context another name that refers to entries of the current
page, e.g.:
.. code-block:: html+django
{% paginate entries as page_entries %}
The *as* argument is also useful when a nested context variable is provided
as queryset. In this case, and only in this case, the resulting variable
name is mandatory, e.g.:
.. code-block:: html+django
{% paginate entries.all as entries %}
The number of paginated entries is taken from settings, but you can
override the default locally, e.g.:
.. code-block:: html+django
{% paginate 20 entries %}
Of course you can mix it all:
.. code-block:: html+django
{% paginate 20 entries as paginated_entries %}
By default, the first page is displayed the first time you load the page,
but you can change this, e.g.:
.. code-block:: html+django
{% paginate entries starting from page 3 %}
When changing the default page, it is also possible to reference the last
page (or the second last page, and so on) by using negative indexes, e.g:
.. code-block:: html+django
{% paginate entries starting from page -1 %}
This can be also achieved using a template variable that was passed to the
context, e.g.:
.. code-block:: html+django
{% paginate entries starting from page page_number %}
If the passed page number does not exist, the first page is displayed.
If you have multiple paginations in the same page, you can change the
querydict key for the single pagination, e.g.:
.. code-block:: html+django
{% paginate entries using article_page %}
In this case *article_page* is intended to be a context variable, but you
can hardcode the key using quotes, e.g.:
.. code-block:: html+django
{% paginate entries using 'articles_at_page' %}
Again, you can mix it all (the order of arguments is important):
.. code-block:: html+django
{% paginate 20 entries
starting from page 3 using page_key as paginated_entries %}
Additionally you can pass a path to be used for the pagination:
.. code-block:: html+django
{% paginate 20 entries
using page_key with pagination_url as paginated_entries %}
This way you can easily create views acting as API endpoints, and point
your Ajax calls to that API. In this case *pagination_url* is considered a
context variable, but it is also possible to hardcode the URL, e.g.:
.. code-block:: html+django
{% paginate 20 entries with "/mypage/" %}
If you want the first page to contain a different number of items than
subsequent pages, you can separate the two values with a comma, e.g. if
you want 3 items on the first page and 10 on other pages:
.. code-block:: html+django
{% paginate 3,10 entries %}
You must use this tag before calling the {% show_more %} one.
"""
# Validate arguments.
try:
tag_name, tag_args = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Use a regexp to catch args.
match = PAGINATE_EXPRESSION.match(tag_args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
kwargs = match.groupdict()
objects = kwargs.pop('objects')
# The variable name must be present if a nested context variable is passed.
if '.' in objects and kwargs['var_name'] is None:
msg = (
'%(tag)r tag requires a variable name `as` argumnent if the '
'queryset is provided as a nested context variable (%(objects)s). '
'You must either pass a direct queryset (e.g. taking advantage '
'of the `with` template tag) or provide a new variable name to '
'store the resulting queryset (e.g. `%(tag)s %(objects)s as '
'objects`).'
) % {'tag': tag_name, 'objects': objects}
raise template.TemplateSyntaxError(msg)
# Call the node.
return PaginateNode(paginator_class, objects, **kwargs)
@register.tag
def lazy_paginate(parser, token):
"""Lazy paginate objects.
Paginate objects without hitting the database with a *select count* query.
Use this the same way as *paginate* tag when you are not interested
in the total number of pages.
"""
return paginate(parser, token, paginator_class=LazyPaginator)
class PaginateNode(template.Node):
"""Add to context the objects of the current page.
Also add the Django paginator's *page* object.
"""
def __init__(
self, paginator_class, objects, first_page=None, per_page=None,
var_name=None, number=None, key=None, override_path=None):
self.paginator = paginator_class or DefaultPaginator
self.objects = template.Variable(objects)
# If *var_name* is not passed, then the queryset name will be used.
self.var_name = objects if var_name is None else var_name
# If *per_page* is not passed then the default value form settings
# will be used.
self.per_page_variable = None
if per_page is None:
self.per_page = settings.PER_PAGE
elif per_page.isdigit():
self.per_page = int(per_page)
else:
self.per_page_variable = template.Variable(per_page)
# Handle first page: if it is not passed then *per_page* is used.
self.first_page_variable = None
if first_page is None:
self.first_page = None
elif first_page.isdigit():
self.first_page = int(first_page)
else:
self.first_page_variable = template.Variable(first_page)
# Handle page number when it is not specified in querystring.
self.page_number_variable = None
if number is None:
self.page_number = 1
else:
try:
self.page_number = int(number)
except ValueError:
self.page_number_variable = template.Variable(number)
# Set the querystring key attribute.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Handle *override_path*.
self.override_path_variable = None
if override_path is None:
self.override_path = None
elif (
override_path[0] in ('"', "'") and
override_path[-1] == override_path[0]):
self.override_path = override_path[1:-1]
else:
self.override_path_variable = template.Variable(override_path)
def render(self, context):
# Handle page number when it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# Calculate the number of items to show on each page.
if self.per_page_variable is None:
per_page = self.per_page
else:
per_page = int(self.per_page_variable.resolve(context))
# Calculate the number of items to show in the first page.
if self.first_page_variable is None:
first_page = self.first_page or per_page
else:
first_page = int(self.first_page_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# Retrieve the override path if used.
if self.override_path_variable is None:
override_path = self.override_path
else:
override_path = self.override_path_variable.resolve(context)
# Retrieve the queryset and create the paginator object.
objects = self.objects.resolve(context)
paginator = self.paginator(
objects, per_page, first_page=first_page, orphans=settings.ORPHANS)
# Normalize the default page number if a negative one is provided.
if default_number < 0:
default_number = utils.normalize_page_number(
default_number, paginator.page_range)
# The current request is used to get the requested page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
# Get the page.
try:
page = paginator.page(page_number)
except EmptyPage:
page = paginator.page(1)
if settings.PAGE_OUT_OF_RANGE_404:
raise Http404('Page out of range')
# Populate the context with required data.
data = {
'default_number': default_number,
'override_path': override_path,
'page': page,
'querystring_key': querystring_key,
}
context.update({'endless': data, self.var_name: page.object_list})
return ''
@register.inclusion_tag('el_pagination/show_more.html', takes_context=True)
def show_more(context, label=None, loading=settings.LOADING, class_name=None):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
You could pass in the extra CSS style class name as a third argument
{% show_more "even more" "working" "class_name" %}
Must be called after ``{% paginate objects %}``.
"""
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the showmore template.
data = utils.get_data_from_context(context)
page = data['page']
# show the template only if there is a next page
if page.has_next():
request = context['request']
page_number = page.next_page_number()
# Generate the querystring.
querystring_key = data['querystring_key']
querystring = utils.get_querystring_for_page(
request, page_number, querystring_key,
default_number=data['default_number'])
return {
'label': label,
'loading': loading,
'class_name': class_name,
'path': iri_to_uri(data['override_path'] or request.path),
'querystring': querystring,
'querystring_key': querystring_key,
'request': request,
}
# No next page, nothing to see.
return {}
@register.tag
def get_pages(parser, token):
"""Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in different ways:
- just print *pages.get_rendered* and you will get Digg-style pagination displayed:
.. code-block:: html+django
{{ pages.get_rendered }}
- display pages count:
.. code-block:: html+django
{{ pages|length }}
- check if the page list contains more than one page:
.. code-block:: html+django
{{ pages.paginated }}
{# the following is equivalent #}
{{ pages|length > 1 }}
- get a specific page:
.. code-block:: html+django
{# the current selected page #}
{{ pages.current }}
{# the first page #}
{{ pages.first }}
{# the last page #}
{{ pages.last }}
{# the previous page (or nothing if you are on first page) #}
{{ pages.previous }}
{# the next page (or nothing if you are in last page) #}
{{ pages.next }}
{# the third page #}
{{ pages.3 }}
{# this means page.1 is the same as page.first #}
{# the 1-based index of the first item on the current page #}
{{ pages.current_start_index }}
{# the 1-based index of the last item on the current page #}
{{ pages.current_end_index }}
{# the total number of objects, across all pages #}
{{ pages.total_count }}
{# the first page represented as an arrow #}
{{ pages.first_as_arrow }}
{# the last page represented as an arrow #}
{{ pages.last_as_arrow }}
- iterate over *pages* to get all pages:
.. code-block:: html+django
{% for page in pages %}
{# display page link #}
{{ page.render_link}}
{# the page url (beginning with "?") #}
{{ page.url }}
{# the page path #}
{{ page.path }}
{# the page number #}
{{ page.number }}
{# a string representing the page (commonly the page number) #}
{{ page.label }}
{# check if the page is the current one #}
{{ page.is_current }}
{# check if the page is the first one #}
{{ page.is_first }}
{# check if the page is the last one #}
{{ page.is_last }}
{% endfor %}
You can change the variable name, e.g.:
.. code-block:: html+django
{% get_pages as page_links %}
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
var_name = 'pages'
else:
args = args.split()
if len(args) == 2 and args[0] == 'as':
var_name = args[1]
else:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Call the node.
return GetPagesNode(var_name)
class GetPagesNode(template.Node):
"""Add the page list to context."""
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Add the PageList instance to the context.
context[self.var_name] = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
context=context,
default_number=data['default_number'],
override_path=data['override_path'],
)
return ''
@register.tag
class ShowPagesNode(template.Node):
"""Show the pagination."""
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Return the string representation of the sequence of pages.
pages = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
default_number=data['default_number'],
override_path=data['override_path'],
context=context
)
return pages.get_rendered()
@register.tag
def show_current_number(parser, token):
"""Show the current page number, or insert it in the context.
This tag can for example be useful to change the page title according to
the current page number.
To just show current page number:
.. code-block:: html+django
{% show_current_number %}
If you use multiple paginations in the same page, you can get the page
number for a specific pagination using the querystring key, e.g.:
.. code-block:: html+django
{% show_current_number using mykey %}
The default page when no querystring is specified is 1. If you changed it
in the `paginate`_ template tag, you have to call ``show_current_number``
according to your choice, e.g.:
.. code-block:: html+django
{% show_current_number starting from page 3 %}
This can be also achieved using a template variable you passed to the
context, e.g.:
.. code-block:: html+django
{% show_current_number starting from page page_number %}
You can of course mix it all (the order of arguments is important):
.. code-block:: html+django
{% show_current_number starting from page 3 using mykey %}
If you want to insert the current page number in the context, without
actually displaying it in the template, use the *as* argument, i.e.:
.. code-block:: html+django
{% show_current_number as page_number %}
{% show_current_number
starting from page 3 using mykey as page_number %}
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
key = None
number = None
tag_name = token.contents[0]
var_name = None
else:
# Use a regexp to catch args.
match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
groupdict = match.groupdict()
key = groupdict['key']
number = groupdict['number']
var_name = groupdict['var_name']
# Call the node.
return ShowCurrentNumberNode(number, key, var_name)
class ShowCurrentNumberNode(template.Node):
"""Show the page number taken from context."""
def __init__(self, number, key, var_name):
# Retrieve the page number.
self.page_number_variable = None
if number is None:
self.page_number = 1
elif number.isdigit():
self.page_number = int(number)
else:
self.page_number_variable = template.Variable(number)
# Get the queystring key.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Get the template variable name.
self.var_name = var_name
def render(self, context):
# Get the page number to use if it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# The request object is used to retrieve the current page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
if self.var_name is None:
return utils.text(page_number)
context[self.var_name] = page_number
return ''
|
shtalinberg/django-el-pagination | el_pagination/templatetags/el_pagination_tags.py | show_current_number | python | def show_current_number(parser, token):
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
key = None
number = None
tag_name = token.contents[0]
var_name = None
else:
# Use a regexp to catch args.
match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
groupdict = match.groupdict()
key = groupdict['key']
number = groupdict['number']
var_name = groupdict['var_name']
# Call the node.
return ShowCurrentNumberNode(number, key, var_name) | Show the current page number, or insert it in the context.
This tag can for example be useful to change the page title according to
the current page number.
To just show current page number:
.. code-block:: html+django
{% show_current_number %}
If you use multiple paginations in the same page, you can get the page
number for a specific pagination using the querystring key, e.g.:
.. code-block:: html+django
{% show_current_number using mykey %}
The default page when no querystring is specified is 1. If you changed it
in the `paginate`_ template tag, you have to call ``show_current_number``
according to your choice, e.g.:
.. code-block:: html+django
{% show_current_number starting from page 3 %}
This can be also achieved using a template variable you passed to the
context, e.g.:
.. code-block:: html+django
{% show_current_number starting from page page_number %}
You can of course mix it all (the order of arguments is important):
.. code-block:: html+django
{% show_current_number starting from page 3 using mykey %}
If you want to insert the current page number in the context, without
actually displaying it in the template, use the *as* argument, i.e.:
.. code-block:: html+django
{% show_current_number as page_number %}
{% show_current_number
starting from page 3 using mykey as page_number %} | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L579-L649 | null | """Django Endless Pagination template tags."""
from __future__ import unicode_literals
import re
from django import template
from django.utils.encoding import iri_to_uri
from django.http import Http404
from el_pagination import (
models,
settings,
utils,
)
from el_pagination.paginators import (
DefaultPaginator,
EmptyPage,
LazyPaginator,
)
PAGINATE_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(((?P<first_page>\w+)\,)?(?P<per_page>\w+)\s+)? # First page, per page.
(?P<objects>[\.\w]+) # Objects / queryset.
(\s+starting\s+from\s+page\s+(?P<number>[\-]?\d+|\w+))? # Page start.
(\s+using\s+(?P<key>[\"\'\-\w]+))? # Querystring key.
(\s+with\s+(?P<override_path>[\"\'\/\w]+))? # Override path.
(\s+as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r"""
^ # Beginning of line.
(starting\s+from\s+page\s+(?P<number>\w+))?\s* # Page start.
(using\s+(?P<key>[\"\'\-\w]+))?\s* # Querystring key.
(as\s+(?P<var_name>\w+))? # Context variable name.
$ # End of line.
""", re.VERBOSE)
register = template.Library()
@register.tag
def paginate(parser, token, paginator_class=None):
"""Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* original variable (usually a queryset)
and add to the context another name that refers to entries of the current
page, e.g.:
.. code-block:: html+django
{% paginate entries as page_entries %}
The *as* argument is also useful when a nested context variable is provided
as queryset. In this case, and only in this case, the resulting variable
name is mandatory, e.g.:
.. code-block:: html+django
{% paginate entries.all as entries %}
The number of paginated entries is taken from settings, but you can
override the default locally, e.g.:
.. code-block:: html+django
{% paginate 20 entries %}
Of course you can mix it all:
.. code-block:: html+django
{% paginate 20 entries as paginated_entries %}
By default, the first page is displayed the first time you load the page,
but you can change this, e.g.:
.. code-block:: html+django
{% paginate entries starting from page 3 %}
When changing the default page, it is also possible to reference the last
page (or the second last page, and so on) by using negative indexes, e.g:
.. code-block:: html+django
{% paginate entries starting from page -1 %}
This can be also achieved using a template variable that was passed to the
context, e.g.:
.. code-block:: html+django
{% paginate entries starting from page page_number %}
If the passed page number does not exist, the first page is displayed.
If you have multiple paginations in the same page, you can change the
querydict key for the single pagination, e.g.:
.. code-block:: html+django
{% paginate entries using article_page %}
In this case *article_page* is intended to be a context variable, but you
can hardcode the key using quotes, e.g.:
.. code-block:: html+django
{% paginate entries using 'articles_at_page' %}
Again, you can mix it all (the order of arguments is important):
.. code-block:: html+django
{% paginate 20 entries
starting from page 3 using page_key as paginated_entries %}
Additionally you can pass a path to be used for the pagination:
.. code-block:: html+django
{% paginate 20 entries
using page_key with pagination_url as paginated_entries %}
This way you can easily create views acting as API endpoints, and point
your Ajax calls to that API. In this case *pagination_url* is considered a
context variable, but it is also possible to hardcode the URL, e.g.:
.. code-block:: html+django
{% paginate 20 entries with "/mypage/" %}
If you want the first page to contain a different number of items than
subsequent pages, you can separate the two values with a comma, e.g. if
you want 3 items on the first page and 10 on other pages:
.. code-block:: html+django
{% paginate 3,10 entries %}
You must use this tag before calling the {% show_more %} one.
"""
# Validate arguments.
try:
tag_name, tag_args = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Use a regexp to catch args.
match = PAGINATE_EXPRESSION.match(tag_args)
if match is None:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Retrieve objects.
kwargs = match.groupdict()
objects = kwargs.pop('objects')
# The variable name must be present if a nested context variable is passed.
if '.' in objects and kwargs['var_name'] is None:
msg = (
'%(tag)r tag requires a variable name `as` argumnent if the '
'queryset is provided as a nested context variable (%(objects)s). '
'You must either pass a direct queryset (e.g. taking advantage '
'of the `with` template tag) or provide a new variable name to '
'store the resulting queryset (e.g. `%(tag)s %(objects)s as '
'objects`).'
) % {'tag': tag_name, 'objects': objects}
raise template.TemplateSyntaxError(msg)
# Call the node.
return PaginateNode(paginator_class, objects, **kwargs)
@register.tag
def lazy_paginate(parser, token):
"""Lazy paginate objects.
Paginate objects without hitting the database with a *select count* query.
Use this the same way as *paginate* tag when you are not interested
in the total number of pages.
"""
return paginate(parser, token, paginator_class=LazyPaginator)
class PaginateNode(template.Node):
"""Add to context the objects of the current page.
Also add the Django paginator's *page* object.
"""
def __init__(
self, paginator_class, objects, first_page=None, per_page=None,
var_name=None, number=None, key=None, override_path=None):
self.paginator = paginator_class or DefaultPaginator
self.objects = template.Variable(objects)
# If *var_name* is not passed, then the queryset name will be used.
self.var_name = objects if var_name is None else var_name
# If *per_page* is not passed then the default value form settings
# will be used.
self.per_page_variable = None
if per_page is None:
self.per_page = settings.PER_PAGE
elif per_page.isdigit():
self.per_page = int(per_page)
else:
self.per_page_variable = template.Variable(per_page)
# Handle first page: if it is not passed then *per_page* is used.
self.first_page_variable = None
if first_page is None:
self.first_page = None
elif first_page.isdigit():
self.first_page = int(first_page)
else:
self.first_page_variable = template.Variable(first_page)
# Handle page number when it is not specified in querystring.
self.page_number_variable = None
if number is None:
self.page_number = 1
else:
try:
self.page_number = int(number)
except ValueError:
self.page_number_variable = template.Variable(number)
# Set the querystring key attribute.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Handle *override_path*.
self.override_path_variable = None
if override_path is None:
self.override_path = None
elif (
override_path[0] in ('"', "'") and
override_path[-1] == override_path[0]):
self.override_path = override_path[1:-1]
else:
self.override_path_variable = template.Variable(override_path)
def render(self, context):
# Handle page number when it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# Calculate the number of items to show on each page.
if self.per_page_variable is None:
per_page = self.per_page
else:
per_page = int(self.per_page_variable.resolve(context))
# Calculate the number of items to show in the first page.
if self.first_page_variable is None:
first_page = self.first_page or per_page
else:
first_page = int(self.first_page_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# Retrieve the override path if used.
if self.override_path_variable is None:
override_path = self.override_path
else:
override_path = self.override_path_variable.resolve(context)
# Retrieve the queryset and create the paginator object.
objects = self.objects.resolve(context)
paginator = self.paginator(
objects, per_page, first_page=first_page, orphans=settings.ORPHANS)
# Normalize the default page number if a negative one is provided.
if default_number < 0:
default_number = utils.normalize_page_number(
default_number, paginator.page_range)
# The current request is used to get the requested page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
# Get the page.
try:
page = paginator.page(page_number)
except EmptyPage:
page = paginator.page(1)
if settings.PAGE_OUT_OF_RANGE_404:
raise Http404('Page out of range')
# Populate the context with required data.
data = {
'default_number': default_number,
'override_path': override_path,
'page': page,
'querystring_key': querystring_key,
}
context.update({'endless': data, self.var_name: page.object_list})
return ''
@register.inclusion_tag('el_pagination/show_more.html', takes_context=True)
def show_more(context, label=None, loading=settings.LOADING, class_name=None):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
You could pass in the extra CSS style class name as a third argument
{% show_more "even more" "working" "class_name" %}
Must be called after ``{% paginate objects %}``.
"""
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the showmore template.
data = utils.get_data_from_context(context)
page = data['page']
# show the template only if there is a next page
if page.has_next():
request = context['request']
page_number = page.next_page_number()
# Generate the querystring.
querystring_key = data['querystring_key']
querystring = utils.get_querystring_for_page(
request, page_number, querystring_key,
default_number=data['default_number'])
return {
'label': label,
'loading': loading,
'class_name': class_name,
'path': iri_to_uri(data['override_path'] or request.path),
'querystring': querystring,
'querystring_key': querystring_key,
'request': request,
}
# No next page, nothing to see.
return {}
@register.tag
def get_pages(parser, token):
"""Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in different ways:
- just print *pages.get_rendered* and you will get Digg-style pagination displayed:
.. code-block:: html+django
{{ pages.get_rendered }}
- display pages count:
.. code-block:: html+django
{{ pages|length }}
- check if the page list contains more than one page:
.. code-block:: html+django
{{ pages.paginated }}
{# the following is equivalent #}
{{ pages|length > 1 }}
- get a specific page:
.. code-block:: html+django
{# the current selected page #}
{{ pages.current }}
{# the first page #}
{{ pages.first }}
{# the last page #}
{{ pages.last }}
{# the previous page (or nothing if you are on first page) #}
{{ pages.previous }}
{# the next page (or nothing if you are in last page) #}
{{ pages.next }}
{# the third page #}
{{ pages.3 }}
{# this means page.1 is the same as page.first #}
{# the 1-based index of the first item on the current page #}
{{ pages.current_start_index }}
{# the 1-based index of the last item on the current page #}
{{ pages.current_end_index }}
{# the total number of objects, across all pages #}
{{ pages.total_count }}
{# the first page represented as an arrow #}
{{ pages.first_as_arrow }}
{# the last page represented as an arrow #}
{{ pages.last_as_arrow }}
- iterate over *pages* to get all pages:
.. code-block:: html+django
{% for page in pages %}
{# display page link #}
{{ page.render_link}}
{# the page url (beginning with "?") #}
{{ page.url }}
{# the page path #}
{{ page.path }}
{# the page number #}
{{ page.number }}
{# a string representing the page (commonly the page number) #}
{{ page.label }}
{# check if the page is the current one #}
{{ page.is_current }}
{# check if the page is the first one #}
{{ page.is_first }}
{# check if the page is the last one #}
{{ page.is_last }}
{% endfor %}
You can change the variable name, e.g.:
.. code-block:: html+django
{% get_pages as page_links %}
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
var_name = 'pages'
else:
args = args.split()
if len(args) == 2 and args[0] == 'as':
var_name = args[1]
else:
msg = 'Invalid arguments for %r tag' % tag_name
raise template.TemplateSyntaxError(msg)
# Call the node.
return GetPagesNode(var_name)
class GetPagesNode(template.Node):
"""Add the page list to context."""
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Add the PageList instance to the context.
context[self.var_name] = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
context=context,
default_number=data['default_number'],
override_path=data['override_path'],
)
return ''
@register.tag
def show_pages(parser, token):
"""Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py*
to a callable, or to a dotted path representing a callable, used to
customize the pages that are displayed.
See the *__unicode__* method of ``endless_pagination.models.PageList`` for
a detailed explanation of how the callable can be used.
Must be called after ``{% paginate objects %}``.
"""
# Validate args.
if len(token.contents.split()) != 1:
msg = '%r tag takes no arguments' % token.contents.split()[0]
raise template.TemplateSyntaxError(msg)
# Call the node.
return ShowPagesNode()
class ShowPagesNode(template.Node):
"""Show the pagination."""
def render(self, context):
# This template tag could raise a PaginationError: you have to call
# *paginate* or *lazy_paginate* before including the getpages template.
data = utils.get_data_from_context(context)
# Return the string representation of the sequence of pages.
pages = models.PageList(
context['request'],
data['page'],
data['querystring_key'],
default_number=data['default_number'],
override_path=data['override_path'],
context=context
)
return pages.get_rendered()
@register.tag
class ShowCurrentNumberNode(template.Node):
"""Show the page number taken from context."""
def __init__(self, number, key, var_name):
# Retrieve the page number.
self.page_number_variable = None
if number is None:
self.page_number = 1
elif number.isdigit():
self.page_number = int(number)
else:
self.page_number_variable = template.Variable(number)
# Get the queystring key.
self.querystring_key_variable = None
if key is None:
self.querystring_key = settings.PAGE_LABEL
elif key[0] in ('"', "'") and key[-1] == key[0]:
self.querystring_key = key[1:-1]
else:
self.querystring_key_variable = template.Variable(key)
# Get the template variable name.
self.var_name = var_name
def render(self, context):
# Get the page number to use if it is not specified in querystring.
if self.page_number_variable is None:
default_number = self.page_number
else:
default_number = int(self.page_number_variable.resolve(context))
# User can override the querystring key to use in the template.
# The default value is defined in the settings file.
if self.querystring_key_variable is None:
querystring_key = self.querystring_key
else:
querystring_key = self.querystring_key_variable.resolve(context)
# The request object is used to retrieve the current page number.
page_number = utils.get_page_number_from_request(
context['request'], querystring_key, default=default_number)
if self.var_name is None:
return utils.text(page_number)
context[self.var_name] = page_number
return ''
|
shtalinberg/django-el-pagination | el_pagination/decorators.py | page_template | python | def page_template(template, key=PAGE_LABEL):
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
if request.is_ajax() and querystring_key == key:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator | Return a view dynamically switching template if the request is Ajax.
Decorate a view that takes a *template* and *extra_context* keyword
arguments (like generic views).
The template is switched to *page_template* if request is ajax and
if *querystring_key* variable passed by the request equals to *key*.
This allows multiple Ajax paginations in the same page.
The name of the page template is given as *page_template* in the
extra context. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L13-L39 | null | """View decorators for Ajax powered pagination."""
from __future__ import unicode_literals
from functools import wraps
from el_pagination.settings import (
PAGE_LABEL,
TEMPLATE_VARNAME,
)
QS_KEY = 'querystring_key'
def _get_template(querystring_key, mapping):
"""Return the template corresponding to the given ``querystring_key``."""
default = None
try:
template_and_keys = mapping.items()
except AttributeError:
template_and_keys = mapping
for template, key in template_and_keys:
if key is None:
key = PAGE_LABEL
default = template
if key == querystring_key:
return template
return default
def page_templates(mapping):
"""Like the *page_template* decorator but manage multiple paginations.
You can map multiple templates to *querystring_keys* using the *mapping*
dict, e.g.::
@page_templates({
'page_contents1.html': None,
'page_contents2.html': 'go_to_page',
})
def myview(request):
...
When the value of the dict is None then the default *querystring_key*
(defined in settings) is used. You can use this decorator instead of
chaining multiple *page_template* calls.
"""
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
template = _get_template(querystring_key, mapping)
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
if request.is_ajax() and template:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator
|
shtalinberg/django-el-pagination | el_pagination/decorators.py | _get_template | python | def _get_template(querystring_key, mapping):
default = None
try:
template_and_keys = mapping.items()
except AttributeError:
template_and_keys = mapping
for template, key in template_and_keys:
if key is None:
key = PAGE_LABEL
default = template
if key == querystring_key:
return template
return default | Return the template corresponding to the given ``querystring_key``. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L42-L55 | null | """View decorators for Ajax powered pagination."""
from __future__ import unicode_literals
from functools import wraps
from el_pagination.settings import (
PAGE_LABEL,
TEMPLATE_VARNAME,
)
QS_KEY = 'querystring_key'
def page_template(template, key=PAGE_LABEL):
"""Return a view dynamically switching template if the request is Ajax.
Decorate a view that takes a *template* and *extra_context* keyword
arguments (like generic views).
The template is switched to *page_template* if request is ajax and
if *querystring_key* variable passed by the request equals to *key*.
This allows multiple Ajax paginations in the same page.
The name of the page template is given as *page_template* in the
extra context.
"""
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
if request.is_ajax() and querystring_key == key:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator
def page_templates(mapping):
"""Like the *page_template* decorator but manage multiple paginations.
You can map multiple templates to *querystring_keys* using the *mapping*
dict, e.g.::
@page_templates({
'page_contents1.html': None,
'page_contents2.html': 'go_to_page',
})
def myview(request):
...
When the value of the dict is None then the default *querystring_key*
(defined in settings) is used. You can use this decorator instead of
chaining multiple *page_template* calls.
"""
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
template = _get_template(querystring_key, mapping)
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
if request.is_ajax() and template:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator
|
shtalinberg/django-el-pagination | el_pagination/decorators.py | page_templates | python | def page_templates(mapping):
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
template = _get_template(querystring_key, mapping)
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
if request.is_ajax() and template:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator | Like the *page_template* decorator but manage multiple paginations.
You can map multiple templates to *querystring_keys* using the *mapping*
dict, e.g.::
@page_templates({
'page_contents1.html': None,
'page_contents2.html': 'go_to_page',
})
def myview(request):
...
When the value of the dict is None then the default *querystring_key*
(defined in settings) is used. You can use this decorator instead of
chaining multiple *page_template* calls. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L58-L91 | null | """View decorators for Ajax powered pagination."""
from __future__ import unicode_literals
from functools import wraps
from el_pagination.settings import (
PAGE_LABEL,
TEMPLATE_VARNAME,
)
QS_KEY = 'querystring_key'
def page_template(template, key=PAGE_LABEL):
"""Return a view dynamically switching template if the request is Ajax.
Decorate a view that takes a *template* and *extra_context* keyword
arguments (like generic views).
The template is switched to *page_template* if request is ajax and
if *querystring_key* variable passed by the request equals to *key*.
This allows multiple Ajax paginations in the same page.
The name of the page template is given as *page_template* in the
extra context.
"""
def decorator(view):
@wraps(view)
def decorated(request, *args, **kwargs):
# Trust the developer: he wrote ``context.update(extra_context)``
# in his view.
extra_context = kwargs.setdefault('extra_context', {})
extra_context['page_template'] = template
# Switch the template when the request is Ajax.
querystring_key = request.GET.get(QS_KEY,
request.POST.get(QS_KEY, PAGE_LABEL))
if request.is_ajax() and querystring_key == key:
kwargs[TEMPLATE_VARNAME] = template
return view(request, *args, **kwargs)
return decorated
return decorator
def _get_template(querystring_key, mapping):
"""Return the template corresponding to the given ``querystring_key``."""
default = None
try:
template_and_keys = mapping.items()
except AttributeError:
template_and_keys = mapping
for template, key in template_and_keys:
if key is None:
key = PAGE_LABEL
default = template
if key == querystring_key:
return template
return default
|
shtalinberg/django-el-pagination | el_pagination/views.py | MultipleObjectMixin.get_queryset | python | def get_queryset(self):
if self.queryset is not None:
queryset = self.queryset
if hasattr(queryset, '_clone'):
queryset = queryset._clone()
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
msg = '{0} must define ``queryset`` or ``model``'
raise ImproperlyConfigured(msg.format(self.__class__.__name__))
return queryset | Get the list of items for this view.
This must be an interable, and may be a queryset
(in which qs-specific behavior will be enabled).
See original in ``django.views.generic.list.MultipleObjectMixin``. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L22-L39 | null | class MultipleObjectMixin(object):
allow_empty = True
context_object_name = None
model = None
queryset = None
def get_allow_empty(self):
"""Returns True if the view should display empty lists.
Return False if a 404 should be raised instead.
See original in ``django.views.generic.list.MultipleObjectMixin``.
"""
return self.allow_empty
def get_context_object_name(self, object_list):
"""Get the name of the item to be used in the context.
See original in ``django.views.generic.list.MultipleObjectMixin``.
"""
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
object_name = object_list.model._meta.object_name.lower()
return smart_str('{0}_list'.format(object_name))
else:
return None
def get_context_data(self, **kwargs):
"""Get the context for this view.
Also adds the *page_template* variable in the context.
If the *page_template* is not given as a kwarg of the *as_view*
method then it is generated using app label, model name
(obviously if the list is a queryset), *self.template_name_suffix*
and *self.page_template_suffix*.
For instance, if the list is a queryset of *blog.Entry*,
the template will be ``blog/entry_list_page.html``.
"""
queryset = kwargs.pop('object_list')
page_template = kwargs.pop('page_template')
context_object_name = self.get_context_object_name(queryset)
context = {'object_list': queryset, 'view': self}
context.update(kwargs)
if context_object_name is not None:
context[context_object_name] = queryset
if page_template is None:
if hasattr(queryset, 'model'):
page_template = self.get_page_template(**kwargs)
else:
raise ImproperlyConfigured(
'AjaxListView requires a page_template')
context['page_template'] = self.page_template = page_template
return context
|
shtalinberg/django-el-pagination | el_pagination/views.py | MultipleObjectMixin.get_context_object_name | python | def get_context_object_name(self, object_list):
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
object_name = object_list.model._meta.object_name.lower()
return smart_str('{0}_list'.format(object_name))
else:
return None | Get the name of the item to be used in the context.
See original in ``django.views.generic.list.MultipleObjectMixin``. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L50-L61 | null | class MultipleObjectMixin(object):
allow_empty = True
context_object_name = None
model = None
queryset = None
def get_queryset(self):
"""Get the list of items for this view.
This must be an interable, and may be a queryset
(in which qs-specific behavior will be enabled).
See original in ``django.views.generic.list.MultipleObjectMixin``.
"""
if self.queryset is not None:
queryset = self.queryset
if hasattr(queryset, '_clone'):
queryset = queryset._clone()
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
msg = '{0} must define ``queryset`` or ``model``'
raise ImproperlyConfigured(msg.format(self.__class__.__name__))
return queryset
def get_allow_empty(self):
"""Returns True if the view should display empty lists.
Return False if a 404 should be raised instead.
See original in ``django.views.generic.list.MultipleObjectMixin``.
"""
return self.allow_empty
def get_context_data(self, **kwargs):
"""Get the context for this view.
Also adds the *page_template* variable in the context.
If the *page_template* is not given as a kwarg of the *as_view*
method then it is generated using app label, model name
(obviously if the list is a queryset), *self.template_name_suffix*
and *self.page_template_suffix*.
For instance, if the list is a queryset of *blog.Entry*,
the template will be ``blog/entry_list_page.html``.
"""
queryset = kwargs.pop('object_list')
page_template = kwargs.pop('page_template')
context_object_name = self.get_context_object_name(queryset)
context = {'object_list': queryset, 'view': self}
context.update(kwargs)
if context_object_name is not None:
context[context_object_name] = queryset
if page_template is None:
if hasattr(queryset, 'model'):
page_template = self.get_page_template(**kwargs)
else:
raise ImproperlyConfigured(
'AjaxListView requires a page_template')
context['page_template'] = self.page_template = page_template
return context
|
shtalinberg/django-el-pagination | el_pagination/views.py | InvalidPaginationListView.get | python | def get(self, request, *args, **kwargs):
response = super().get(request, args, kwargs)
try:
response.render()
except Http404:
request.GET = request.GET.copy()
request.GET['page'] = '1'
response = super().get(request, args, kwargs)
response.status_code = 404
return response | Wraps super().get(...) in order to return 404 status code if
the page parameter is invalid | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L111-L124 | null | class InvalidPaginationListView:
|
shtalinberg/django-el-pagination | el_pagination/views.py | AjaxMultipleObjectTemplateResponseMixin.get_page_template | python | def get_page_template(self, **kwargs):
opts = self.object_list.model._meta
return '{0}/{1}{2}{3}.html'.format(
opts.app_label,
opts.object_name.lower(),
self.template_name_suffix,
self.page_template_suffix,
) | Return the template name used for this request.
Only called if *page_template* is not given as a kwarg of
*self.as_view*. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L135-L147 | null | class AjaxMultipleObjectTemplateResponseMixin(
MultipleObjectTemplateResponseMixin):
key = PAGE_LABEL
page_template = None
page_template_suffix = '_page'
template_name_suffix = '_list'
def get_template_names(self):
"""Switch the templates for Ajax requests."""
request = self.request
key = 'querystring_key'
querystring_key = request.GET.get(key,
request.POST.get(key, PAGE_LABEL))
if request.is_ajax() and querystring_key == self.key:
return [self.page_template or self.get_page_template()]
return super(
AjaxMultipleObjectTemplateResponseMixin, self).get_template_names()
|
shtalinberg/django-el-pagination | el_pagination/views.py | AjaxMultipleObjectTemplateResponseMixin.get_template_names | python | def get_template_names(self):
request = self.request
key = 'querystring_key'
querystring_key = request.GET.get(key,
request.POST.get(key, PAGE_LABEL))
if request.is_ajax() and querystring_key == self.key:
return [self.page_template or self.get_page_template()]
return super(
AjaxMultipleObjectTemplateResponseMixin, self).get_template_names() | Switch the templates for Ajax requests. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L149-L158 | null | class AjaxMultipleObjectTemplateResponseMixin(
MultipleObjectTemplateResponseMixin):
key = PAGE_LABEL
page_template = None
page_template_suffix = '_page'
template_name_suffix = '_list'
def get_page_template(self, **kwargs):
"""Return the template name used for this request.
Only called if *page_template* is not given as a kwarg of
*self.as_view*.
"""
opts = self.object_list.model._meta
return '{0}/{1}{2}{3}.html'.format(
opts.app_label,
opts.object_name.lower(),
self.template_name_suffix,
self.page_template_suffix,
)
|
shtalinberg/django-el-pagination | el_pagination/models.py | ELPage.render_link | python | def render_link(self):
extra_context = {
'add_nofollow': settings.ADD_NOFOLLOW,
'page': self,
'querystring_key': self.querystring_key,
}
if self.is_current:
template_name = 'el_pagination/current_link.html'
else:
template_name = 'el_pagination/page_link.html'
if settings.USE_NEXT_PREVIOUS_LINKS:
if self.is_previous:
template_name = 'el_pagination/previous_link.html'
if self.is_next:
template_name = 'el_pagination/next_link.html'
if template_name not in _template_cache:
_template_cache[template_name] = loader.get_template(template_name)
template = _template_cache[template_name]
with self.context.push(**extra_context):
return template.render(self.context.flatten()) | Render the page as a link. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L63-L83 | null | class ELPage(object):
"""A page link representation.
Interesting attributes:
- *self.number*: the page number;
- *self.label*: the label of the link
(usually the page number as string);
- *self.url*: the url of the page (strting with "?");
- *self.path*: the path of the page;
- *self.is_current*: return True if page is the current page displayed;
- *self.is_first*: return True if page is the first page;
- *self.is_last*: return True if page is the last page.
"""
def __init__(
self, request, number, current_number, total_number,
querystring_key, label=None, default_number=1, override_path=None,
context=None):
self._request = request
self.number = number
self.label = force_text(number) if label is None else label
self.querystring_key = querystring_key
self.context = context or {}
self.context['request'] = request
self.is_current = number == current_number
self.is_first = number == 1
self.is_last = number == total_number
if settings.USE_NEXT_PREVIOUS_LINKS:
self.is_previous = label and number == current_number - 1
self.is_next = label and number == current_number + 1
self.url = utils.get_querystring_for_page(
request, number,
self.querystring_key,
default_number=default_number
)
path = iri_to_uri(override_path or request.path)
self.path = '{0}{1}'.format(path, self.url)
|
shtalinberg/django-el-pagination | el_pagination/models.py | PageList.previous | python | def previous(self):
if self._page.has_previous():
return self._endless_page(
self._page.previous_page_number(),
label=settings.PREVIOUS_LABEL)
return '' | Return the previous page.
The page label is defined in ``settings.PREVIOUS_LABEL``.
Return an empty string if current page is the first. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L243-L253 | null | class PageList(object):
"""A sequence of endless pages."""
def __init__(
self, request, page, querystring_key, context,
default_number=None, override_path=None):
self._request = request
self._page = page
self.context = context
self.context['request'] = request
if default_number is None:
self._default_number = 1
else:
self._default_number = int(default_number)
self._querystring_key = querystring_key
self._override_path = override_path
self._pages_list = []
def _endless_page(self, number, label=None):
"""Factory function that returns a *ELPage* instance.
This method works just like a partial constructor.
"""
return ELPage(
self._request,
number,
self._page.number,
len(self),
self._querystring_key,
label=label,
default_number=self._default_number,
override_path=self._override_path,
context=self.context
)
def __getitem__(self, value):
# The type conversion is required here because in templates Django
# performs a dictionary lookup before the attribute lokups
# (when a dot is encountered).
try:
value = int(value)
except (TypeError, ValueError):
# A TypeError says to django to continue with an attribute lookup.
raise TypeError
if 1 <= value <= len(self):
return self._endless_page(value)
raise IndexError('page list index out of range')
def __len__(self):
"""The length of the sequence is the total number of pages."""
return self._page.paginator.num_pages
def __iter__(self):
"""Iterate over all the endless pages (from first to last)."""
for i in range(len(self)):
yield self[i + 1]
def __str__(self):
"""Return a rendered Digg-style pagination (by default).
The callable *settings.PAGE_LIST_CALLABLE* can be used to customize
how the pages are displayed. The callable takes the current page number
and the total number of pages, and must return a sequence of page
numbers that will be displayed. The sequence can contain other values:
- *'previous'*: will display the previous page in that position;
- *'next'*: will display the next page in that position;
- *'first'*: will display the first page as an arrow;
- *'last'*: will display the last page as an arrow;
- *None*: a separator will be displayed in that position.
Here is an example of custom calable that displays the previous page,
then the first page, then a separator, then the current page, and
finally the last page::
def get_page_numbers(current_page, num_pages):
return ('previous', 1, None, current_page, 'last')
If *settings.PAGE_LIST_CALLABLE* is None an internal callable is used,
generating a Digg-style pagination. The value of
*settings.PAGE_LIST_CALLABLE* can also be a dotted path to a callable.
"""
return ''
def get_pages_list(self):
if not self._pages_list:
callable_or_path = settings.PAGE_LIST_CALLABLE
if callable_or_path:
if callable(callable_or_path):
pages_callable = callable_or_path
else:
pages_callable = loaders.load_object(callable_or_path)
else:
pages_callable = utils.get_page_numbers
pages = []
for item in pages_callable(self._page.number, len(self)):
if item is None:
pages.append(None)
elif item == 'previous':
pages.append(self.previous())
elif item == 'next':
pages.append(self.next())
elif item == 'first':
pages.append(self.first_as_arrow())
elif item == 'last':
pages.append(self.last_as_arrow())
else:
pages.append(self[item])
self._pages_list = pages
return self._pages_list
def get_rendered(self):
if len(self) > 1:
template = loader.get_template('el_pagination/show_pages.html')
with self.context.push(pages=self.get_pages_list()):
return template.render(self.context.flatten())
return ''
def current(self):
"""Return the current page."""
return self._endless_page(self._page.number)
def current_start_index(self):
"""Return the 1-based index of the first item on the current page."""
return self._page.start_index()
def current_end_index(self):
"""Return the 1-based index of the last item on the current page."""
return self._page.end_index()
def total_count(self):
"""Return the total number of objects, across all pages."""
return self._page.paginator.count
def first(self, label=None):
"""Return the first page."""
return self._endless_page(1, label=label)
def last(self, label=None):
"""Return the last page."""
return self._endless_page(len(self), label=label)
def first_as_arrow(self):
"""Return the first page as an arrow.
The page label (arrow) is defined in ``settings.FIRST_LABEL``.
"""
return self.first(label=settings.FIRST_LABEL)
def last_as_arrow(self):
"""Return the last page as an arrow.
The page label (arrow) is defined in ``settings.LAST_LABEL``.
"""
return self.last(label=settings.LAST_LABEL)
def next(self):
"""Return the next page.
The page label is defined in ``settings.NEXT_LABEL``.
Return an empty string if current page is the last.
"""
if self._page.has_next():
return self._endless_page(
self._page.next_page_number(),
label=settings.NEXT_LABEL)
return ''
def paginated(self):
"""Return True if this page list contains more than one page."""
return len(self) > 1
def per_page_number(self):
"""Return the numbers of objects are normally display in per page."""
return self._page.paginator.per_page
|
shtalinberg/django-el-pagination | el_pagination/models.py | PageList.next | python | def next(self):
if self._page.has_next():
return self._endless_page(
self._page.next_page_number(),
label=settings.NEXT_LABEL)
return '' | Return the next page.
The page label is defined in ``settings.NEXT_LABEL``.
Return an empty string if current page is the last. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L255-L265 | null | class PageList(object):
"""A sequence of endless pages."""
def __init__(
self, request, page, querystring_key, context,
default_number=None, override_path=None):
self._request = request
self._page = page
self.context = context
self.context['request'] = request
if default_number is None:
self._default_number = 1
else:
self._default_number = int(default_number)
self._querystring_key = querystring_key
self._override_path = override_path
self._pages_list = []
def _endless_page(self, number, label=None):
"""Factory function that returns a *ELPage* instance.
This method works just like a partial constructor.
"""
return ELPage(
self._request,
number,
self._page.number,
len(self),
self._querystring_key,
label=label,
default_number=self._default_number,
override_path=self._override_path,
context=self.context
)
def __getitem__(self, value):
# The type conversion is required here because in templates Django
# performs a dictionary lookup before the attribute lokups
# (when a dot is encountered).
try:
value = int(value)
except (TypeError, ValueError):
# A TypeError says to django to continue with an attribute lookup.
raise TypeError
if 1 <= value <= len(self):
return self._endless_page(value)
raise IndexError('page list index out of range')
def __len__(self):
"""The length of the sequence is the total number of pages."""
return self._page.paginator.num_pages
def __iter__(self):
"""Iterate over all the endless pages (from first to last)."""
for i in range(len(self)):
yield self[i + 1]
def __str__(self):
"""Return a rendered Digg-style pagination (by default).
The callable *settings.PAGE_LIST_CALLABLE* can be used to customize
how the pages are displayed. The callable takes the current page number
and the total number of pages, and must return a sequence of page
numbers that will be displayed. The sequence can contain other values:
- *'previous'*: will display the previous page in that position;
- *'next'*: will display the next page in that position;
- *'first'*: will display the first page as an arrow;
- *'last'*: will display the last page as an arrow;
- *None*: a separator will be displayed in that position.
Here is an example of custom calable that displays the previous page,
then the first page, then a separator, then the current page, and
finally the last page::
def get_page_numbers(current_page, num_pages):
return ('previous', 1, None, current_page, 'last')
If *settings.PAGE_LIST_CALLABLE* is None an internal callable is used,
generating a Digg-style pagination. The value of
*settings.PAGE_LIST_CALLABLE* can also be a dotted path to a callable.
"""
return ''
def get_pages_list(self):
if not self._pages_list:
callable_or_path = settings.PAGE_LIST_CALLABLE
if callable_or_path:
if callable(callable_or_path):
pages_callable = callable_or_path
else:
pages_callable = loaders.load_object(callable_or_path)
else:
pages_callable = utils.get_page_numbers
pages = []
for item in pages_callable(self._page.number, len(self)):
if item is None:
pages.append(None)
elif item == 'previous':
pages.append(self.previous())
elif item == 'next':
pages.append(self.next())
elif item == 'first':
pages.append(self.first_as_arrow())
elif item == 'last':
pages.append(self.last_as_arrow())
else:
pages.append(self[item])
self._pages_list = pages
return self._pages_list
def get_rendered(self):
if len(self) > 1:
template = loader.get_template('el_pagination/show_pages.html')
with self.context.push(pages=self.get_pages_list()):
return template.render(self.context.flatten())
return ''
def current(self):
"""Return the current page."""
return self._endless_page(self._page.number)
def current_start_index(self):
"""Return the 1-based index of the first item on the current page."""
return self._page.start_index()
def current_end_index(self):
"""Return the 1-based index of the last item on the current page."""
return self._page.end_index()
def total_count(self):
"""Return the total number of objects, across all pages."""
return self._page.paginator.count
def first(self, label=None):
"""Return the first page."""
return self._endless_page(1, label=label)
def last(self, label=None):
"""Return the last page."""
return self._endless_page(len(self), label=label)
def first_as_arrow(self):
"""Return the first page as an arrow.
The page label (arrow) is defined in ``settings.FIRST_LABEL``.
"""
return self.first(label=settings.FIRST_LABEL)
def last_as_arrow(self):
"""Return the last page as an arrow.
The page label (arrow) is defined in ``settings.LAST_LABEL``.
"""
return self.last(label=settings.LAST_LABEL)
def previous(self):
"""Return the previous page.
The page label is defined in ``settings.PREVIOUS_LABEL``.
Return an empty string if current page is the first.
"""
if self._page.has_previous():
return self._endless_page(
self._page.previous_page_number(),
label=settings.PREVIOUS_LABEL)
return ''
def paginated(self):
"""Return True if this page list contains more than one page."""
return len(self) > 1
def per_page_number(self):
"""Return the numbers of objects are normally display in per page."""
return self._page.paginator.per_page
|
shtalinberg/django-el-pagination | el_pagination/paginators.py | CustomPage.start_index | python | def start_index(self):
paginator = self.paginator
# Special case, return zero if no items.
if paginator.count == 0:
return 0
elif self.number == 1:
return 1
return (
(self.number - 2) * paginator.per_page + paginator.first_page + 1) | Return the 1-based index of the first item on this page. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L17-L26 | null | class CustomPage(Page):
"""Handle different number of items on the first page."""
def end_index(self):
"""Return the 1-based index of the last item on this page."""
paginator = self.paginator
# Special case for the last page because there can be orphans.
if self.number == paginator.num_pages:
return paginator.count
return (self.number - 1) * paginator.per_page + paginator.first_page
|
shtalinberg/django-el-pagination | el_pagination/paginators.py | CustomPage.end_index | python | def end_index(self):
paginator = self.paginator
# Special case for the last page because there can be orphans.
if self.number == paginator.num_pages:
return paginator.count
return (self.number - 1) * paginator.per_page + paginator.first_page | Return the 1-based index of the last item on this page. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L28-L34 | null | class CustomPage(Page):
"""Handle different number of items on the first page."""
def start_index(self):
"""Return the 1-based index of the first item on this page."""
paginator = self.paginator
# Special case, return zero if no items.
if paginator.count == 0:
return 0
elif self.number == 1:
return 1
return (
(self.number - 2) * paginator.per_page + paginator.first_page + 1)
|
shtalinberg/django-el-pagination | el_pagination/utils.py | get_page_numbers | python | def get_page_numbers(
current_page, num_pages,
extremes=DEFAULT_CALLABLE_EXTREMES,
arounds=DEFAULT_CALLABLE_AROUNDS,
arrows=DEFAULT_CALLABLE_ARROWS):
page_range = range(1, num_pages + 1)
pages = []
if current_page != 1:
if arrows:
pages.append('first')
pages.append('previous')
# Get first and last pages (extremes).
first = page_range[:extremes]
pages.extend(first)
last = page_range[-extremes:]
# Get the current pages (arounds).
current_start = current_page - 1 - arounds
if current_start < 0:
current_start = 0
current_end = current_page + arounds
if current_end > num_pages:
current_end = num_pages
current = page_range[current_start:current_end]
# Mix first with current pages.
to_add = current
if extremes:
diff = current[0] - first[-1]
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = current[abs(diff) + 1:]
pages.extend(to_add)
# Mix current with last pages.
if extremes:
diff = last[0] - current[-1]
to_add = last
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = last[abs(diff) + 1:]
pages.extend(to_add)
if current_page != num_pages:
pages.append('next')
if arrows:
pages.append('last')
return pages | Default callable for page listing.
Produce a Digg-style pagination. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L50-L104 | null | """Django EL Pagination utility functions."""
from __future__ import unicode_literals
import sys
from el_pagination import exceptions
from el_pagination.settings import (
DEFAULT_CALLABLE_AROUNDS,
DEFAULT_CALLABLE_ARROWS,
DEFAULT_CALLABLE_EXTREMES,
PAGE_LABEL,
)
# Handle the Python 2 to 3 migration.
if sys.version_info[0] >= 3:
PYTHON3 = True
text = str
else:
PYTHON3 = False
# Avoid lint errors under Python 3.
text = unicode # NOQA
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise exceptions.PaginationError(
'Cannot find endless data in context.')
def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
return int(request.GET.get(querystring_key,
request.POST.get(querystring_key)))
except (KeyError, TypeError, ValueError):
return default
def _iter_factors(starting_factor=1):
"""Generator yielding something like 1, 3, 10, 30, 100, 300 etc.
The series starts from starting_factor.
"""
while True:
yield starting_factor
yield starting_factor * 3
starting_factor *= 10
def _make_elastic_range(begin, end):
"""Generate an S-curved range of pages.
Start from both left and right, adding exponentially growing indexes,
until the two trends collide.
"""
# Limit growth for huge numbers of pages.
starting_factor = max(1, (end - begin) // 100)
factor = _iter_factors(starting_factor)
left_half, right_half = [], []
left_val, right_val = begin, end
right_val = end
while left_val < right_val:
left_half.append(left_val)
right_half.append(right_val)
next_factor = next(factor)
left_val = begin + next_factor
right_val = end - next_factor
# If the trends happen to meet exactly at one point, retain it.
if left_val == right_val:
left_half.append(left_val)
right_half.reverse()
return left_half + right_half
def get_elastic_page_numbers(current_page, num_pages):
"""Alternative callable for page listing.
Produce an adaptive pagination, useful for big numbers of pages, by
splitting the num_pages ranges in two parts at current_page. Each part
will have its own S-curve.
"""
if num_pages <= 10:
return list(range(1, num_pages + 1))
if current_page == 1:
pages = [1]
else:
pages = ['first', 'previous']
pages.extend(_make_elastic_range(1, current_page))
if current_page != num_pages:
pages.extend(_make_elastic_range(current_page, num_pages)[1:])
pages.extend(['next', 'last'])
return pages
def get_querystring_for_page(
request, page_number, querystring_key, default_number=1):
"""Return a querystring pointing to *page_number*."""
querydict = request.GET.copy()
querydict[querystring_key] = page_number
# For the default page number (usually 1) the querystring is not required.
if page_number == default_number:
del querydict[querystring_key]
if 'querystring_key' in querydict:
del querydict['querystring_key']
if querydict:
return '?' + querydict.urlencode()
return ''
def normalize_page_number(page_number, page_range):
"""Handle a negative *page_number*.
Return a positive page number contained in *page_range*.
If the negative index is out of range, return the page number 1.
"""
try:
return page_range[page_number]
except IndexError:
return page_range[0]
|
shtalinberg/django-el-pagination | el_pagination/utils.py | _make_elastic_range | python | def _make_elastic_range(begin, end):
# Limit growth for huge numbers of pages.
starting_factor = max(1, (end - begin) // 100)
factor = _iter_factors(starting_factor)
left_half, right_half = [], []
left_val, right_val = begin, end
right_val = end
while left_val < right_val:
left_half.append(left_val)
right_half.append(right_val)
next_factor = next(factor)
left_val = begin + next_factor
right_val = end - next_factor
# If the trends happen to meet exactly at one point, retain it.
if left_val == right_val:
left_half.append(left_val)
right_half.reverse()
return left_half + right_half | Generate an S-curved range of pages.
Start from both left and right, adding exponentially growing indexes,
until the two trends collide. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L118-L140 | [
"def _iter_factors(starting_factor=1):\n \"\"\"Generator yielding something like 1, 3, 10, 30, 100, 300 etc.\n\n The series starts from starting_factor.\n \"\"\"\n while True:\n yield starting_factor\n yield starting_factor * 3\n starting_factor *= 10\n"
] | """Django EL Pagination utility functions."""
from __future__ import unicode_literals
import sys
from el_pagination import exceptions
from el_pagination.settings import (
DEFAULT_CALLABLE_AROUNDS,
DEFAULT_CALLABLE_ARROWS,
DEFAULT_CALLABLE_EXTREMES,
PAGE_LABEL,
)
# Handle the Python 2 to 3 migration.
if sys.version_info[0] >= 3:
PYTHON3 = True
text = str
else:
PYTHON3 = False
# Avoid lint errors under Python 3.
text = unicode # NOQA
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise exceptions.PaginationError(
'Cannot find endless data in context.')
def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
return int(request.GET.get(querystring_key,
request.POST.get(querystring_key)))
except (KeyError, TypeError, ValueError):
return default
def get_page_numbers(
current_page, num_pages,
extremes=DEFAULT_CALLABLE_EXTREMES,
arounds=DEFAULT_CALLABLE_AROUNDS,
arrows=DEFAULT_CALLABLE_ARROWS):
"""Default callable for page listing.
Produce a Digg-style pagination.
"""
page_range = range(1, num_pages + 1)
pages = []
if current_page != 1:
if arrows:
pages.append('first')
pages.append('previous')
# Get first and last pages (extremes).
first = page_range[:extremes]
pages.extend(first)
last = page_range[-extremes:]
# Get the current pages (arounds).
current_start = current_page - 1 - arounds
if current_start < 0:
current_start = 0
current_end = current_page + arounds
if current_end > num_pages:
current_end = num_pages
current = page_range[current_start:current_end]
# Mix first with current pages.
to_add = current
if extremes:
diff = current[0] - first[-1]
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = current[abs(diff) + 1:]
pages.extend(to_add)
# Mix current with last pages.
if extremes:
diff = last[0] - current[-1]
to_add = last
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = last[abs(diff) + 1:]
pages.extend(to_add)
if current_page != num_pages:
pages.append('next')
if arrows:
pages.append('last')
return pages
def _iter_factors(starting_factor=1):
"""Generator yielding something like 1, 3, 10, 30, 100, 300 etc.
The series starts from starting_factor.
"""
while True:
yield starting_factor
yield starting_factor * 3
starting_factor *= 10
def get_elastic_page_numbers(current_page, num_pages):
"""Alternative callable for page listing.
Produce an adaptive pagination, useful for big numbers of pages, by
splitting the num_pages ranges in two parts at current_page. Each part
will have its own S-curve.
"""
if num_pages <= 10:
return list(range(1, num_pages + 1))
if current_page == 1:
pages = [1]
else:
pages = ['first', 'previous']
pages.extend(_make_elastic_range(1, current_page))
if current_page != num_pages:
pages.extend(_make_elastic_range(current_page, num_pages)[1:])
pages.extend(['next', 'last'])
return pages
def get_querystring_for_page(
request, page_number, querystring_key, default_number=1):
"""Return a querystring pointing to *page_number*."""
querydict = request.GET.copy()
querydict[querystring_key] = page_number
# For the default page number (usually 1) the querystring is not required.
if page_number == default_number:
del querydict[querystring_key]
if 'querystring_key' in querydict:
del querydict['querystring_key']
if querydict:
return '?' + querydict.urlencode()
return ''
def normalize_page_number(page_number, page_range):
"""Handle a negative *page_number*.
Return a positive page number contained in *page_range*.
If the negative index is out of range, return the page number 1.
"""
try:
return page_range[page_number]
except IndexError:
return page_range[0]
|
shtalinberg/django-el-pagination | el_pagination/utils.py | get_elastic_page_numbers | python | def get_elastic_page_numbers(current_page, num_pages):
if num_pages <= 10:
return list(range(1, num_pages + 1))
if current_page == 1:
pages = [1]
else:
pages = ['first', 'previous']
pages.extend(_make_elastic_range(1, current_page))
if current_page != num_pages:
pages.extend(_make_elastic_range(current_page, num_pages)[1:])
pages.extend(['next', 'last'])
return pages | Alternative callable for page listing.
Produce an adaptive pagination, useful for big numbers of pages, by
splitting the num_pages ranges in two parts at current_page. Each part
will have its own S-curve. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L143-L160 | [
"def _make_elastic_range(begin, end):\n \"\"\"Generate an S-curved range of pages.\n\n Start from both left and right, adding exponentially growing indexes,\n until the two trends collide.\n \"\"\"\n # Limit growth for huge numbers of pages.\n starting_factor = max(1, (end - begin) // 100)\n factor = _iter_factors(starting_factor)\n left_half, right_half = [], []\n left_val, right_val = begin, end\n right_val = end\n while left_val < right_val:\n left_half.append(left_val)\n right_half.append(right_val)\n next_factor = next(factor)\n left_val = begin + next_factor\n right_val = end - next_factor\n # If the trends happen to meet exactly at one point, retain it.\n if left_val == right_val:\n left_half.append(left_val)\n right_half.reverse()\n return left_half + right_half\n"
] | """Django EL Pagination utility functions."""
from __future__ import unicode_literals
import sys
from el_pagination import exceptions
from el_pagination.settings import (
DEFAULT_CALLABLE_AROUNDS,
DEFAULT_CALLABLE_ARROWS,
DEFAULT_CALLABLE_EXTREMES,
PAGE_LABEL,
)
# Handle the Python 2 to 3 migration.
if sys.version_info[0] >= 3:
PYTHON3 = True
text = str
else:
PYTHON3 = False
# Avoid lint errors under Python 3.
text = unicode # NOQA
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise exceptions.PaginationError(
'Cannot find endless data in context.')
def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
return int(request.GET.get(querystring_key,
request.POST.get(querystring_key)))
except (KeyError, TypeError, ValueError):
return default
def get_page_numbers(
current_page, num_pages,
extremes=DEFAULT_CALLABLE_EXTREMES,
arounds=DEFAULT_CALLABLE_AROUNDS,
arrows=DEFAULT_CALLABLE_ARROWS):
"""Default callable for page listing.
Produce a Digg-style pagination.
"""
page_range = range(1, num_pages + 1)
pages = []
if current_page != 1:
if arrows:
pages.append('first')
pages.append('previous')
# Get first and last pages (extremes).
first = page_range[:extremes]
pages.extend(first)
last = page_range[-extremes:]
# Get the current pages (arounds).
current_start = current_page - 1 - arounds
if current_start < 0:
current_start = 0
current_end = current_page + arounds
if current_end > num_pages:
current_end = num_pages
current = page_range[current_start:current_end]
# Mix first with current pages.
to_add = current
if extremes:
diff = current[0] - first[-1]
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = current[abs(diff) + 1:]
pages.extend(to_add)
# Mix current with last pages.
if extremes:
diff = last[0] - current[-1]
to_add = last
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = last[abs(diff) + 1:]
pages.extend(to_add)
if current_page != num_pages:
pages.append('next')
if arrows:
pages.append('last')
return pages
def _iter_factors(starting_factor=1):
"""Generator yielding something like 1, 3, 10, 30, 100, 300 etc.
The series starts from starting_factor.
"""
while True:
yield starting_factor
yield starting_factor * 3
starting_factor *= 10
def _make_elastic_range(begin, end):
"""Generate an S-curved range of pages.
Start from both left and right, adding exponentially growing indexes,
until the two trends collide.
"""
# Limit growth for huge numbers of pages.
starting_factor = max(1, (end - begin) // 100)
factor = _iter_factors(starting_factor)
left_half, right_half = [], []
left_val, right_val = begin, end
right_val = end
while left_val < right_val:
left_half.append(left_val)
right_half.append(right_val)
next_factor = next(factor)
left_val = begin + next_factor
right_val = end - next_factor
# If the trends happen to meet exactly at one point, retain it.
if left_val == right_val:
left_half.append(left_val)
right_half.reverse()
return left_half + right_half
def get_querystring_for_page(
request, page_number, querystring_key, default_number=1):
"""Return a querystring pointing to *page_number*."""
querydict = request.GET.copy()
querydict[querystring_key] = page_number
# For the default page number (usually 1) the querystring is not required.
if page_number == default_number:
del querydict[querystring_key]
if 'querystring_key' in querydict:
del querydict['querystring_key']
if querydict:
return '?' + querydict.urlencode()
return ''
def normalize_page_number(page_number, page_range):
"""Handle a negative *page_number*.
Return a positive page number contained in *page_range*.
If the negative index is out of range, return the page number 1.
"""
try:
return page_range[page_number]
except IndexError:
return page_range[0]
|
shtalinberg/django-el-pagination | el_pagination/utils.py | get_querystring_for_page | python | def get_querystring_for_page(
request, page_number, querystring_key, default_number=1):
querydict = request.GET.copy()
querydict[querystring_key] = page_number
# For the default page number (usually 1) the querystring is not required.
if page_number == default_number:
del querydict[querystring_key]
if 'querystring_key' in querydict:
del querydict['querystring_key']
if querydict:
return '?' + querydict.urlencode()
return '' | Return a querystring pointing to *page_number*. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L163-L175 | null | """Django EL Pagination utility functions."""
from __future__ import unicode_literals
import sys
from el_pagination import exceptions
from el_pagination.settings import (
DEFAULT_CALLABLE_AROUNDS,
DEFAULT_CALLABLE_ARROWS,
DEFAULT_CALLABLE_EXTREMES,
PAGE_LABEL,
)
# Handle the Python 2 to 3 migration.
if sys.version_info[0] >= 3:
PYTHON3 = True
text = str
else:
PYTHON3 = False
# Avoid lint errors under Python 3.
text = unicode # NOQA
def get_data_from_context(context):
"""Get the django paginator data object from the given *context*.
The context is a dict-like object. If the context key ``endless``
is not found, a *PaginationError* is raised.
"""
try:
return context['endless']
except KeyError:
raise exceptions.PaginationError(
'Cannot find endless data in context.')
def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
return int(request.GET.get(querystring_key,
request.POST.get(querystring_key)))
except (KeyError, TypeError, ValueError):
return default
def get_page_numbers(
current_page, num_pages,
extremes=DEFAULT_CALLABLE_EXTREMES,
arounds=DEFAULT_CALLABLE_AROUNDS,
arrows=DEFAULT_CALLABLE_ARROWS):
"""Default callable for page listing.
Produce a Digg-style pagination.
"""
page_range = range(1, num_pages + 1)
pages = []
if current_page != 1:
if arrows:
pages.append('first')
pages.append('previous')
# Get first and last pages (extremes).
first = page_range[:extremes]
pages.extend(first)
last = page_range[-extremes:]
# Get the current pages (arounds).
current_start = current_page - 1 - arounds
if current_start < 0:
current_start = 0
current_end = current_page + arounds
if current_end > num_pages:
current_end = num_pages
current = page_range[current_start:current_end]
# Mix first with current pages.
to_add = current
if extremes:
diff = current[0] - first[-1]
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = current[abs(diff) + 1:]
pages.extend(to_add)
# Mix current with last pages.
if extremes:
diff = last[0] - current[-1]
to_add = last
if diff > 1:
pages.append(None)
elif diff < 1:
to_add = last[abs(diff) + 1:]
pages.extend(to_add)
if current_page != num_pages:
pages.append('next')
if arrows:
pages.append('last')
return pages
def _iter_factors(starting_factor=1):
"""Generator yielding something like 1, 3, 10, 30, 100, 300 etc.
The series starts from starting_factor.
"""
while True:
yield starting_factor
yield starting_factor * 3
starting_factor *= 10
def _make_elastic_range(begin, end):
"""Generate an S-curved range of pages.
Start from both left and right, adding exponentially growing indexes,
until the two trends collide.
"""
# Limit growth for huge numbers of pages.
starting_factor = max(1, (end - begin) // 100)
factor = _iter_factors(starting_factor)
left_half, right_half = [], []
left_val, right_val = begin, end
right_val = end
while left_val < right_val:
left_half.append(left_val)
right_half.append(right_val)
next_factor = next(factor)
left_val = begin + next_factor
right_val = end - next_factor
# If the trends happen to meet exactly at one point, retain it.
if left_val == right_val:
left_half.append(left_val)
right_half.reverse()
return left_half + right_half
def get_elastic_page_numbers(current_page, num_pages):
"""Alternative callable for page listing.
Produce an adaptive pagination, useful for big numbers of pages, by
splitting the num_pages ranges in two parts at current_page. Each part
will have its own S-curve.
"""
if num_pages <= 10:
return list(range(1, num_pages + 1))
if current_page == 1:
pages = [1]
else:
pages = ['first', 'previous']
pages.extend(_make_elastic_range(1, current_page))
if current_page != num_pages:
pages.extend(_make_elastic_range(current_page, num_pages)[1:])
pages.extend(['next', 'last'])
return pages
def normalize_page_number(page_number, page_range):
"""Handle a negative *page_number*.
Return a positive page number contained in *page_range*.
If the negative index is out of range, return the page number 1.
"""
try:
return page_range[page_number]
except IndexError:
return page_range[0]
|
shtalinberg/django-el-pagination | el_pagination/loaders.py | load_object | python | def load_object(path):
i = path.rfind('.')
module_name, object_name = path[:i], path[i + 1:]
# Load module.
try:
module = import_module(module_name)
except ImportError:
raise ImproperlyConfigured('Module %r not found' % module_name)
except ValueError:
raise ImproperlyConfigured('Invalid module %r' % module_name)
# Load object.
try:
return getattr(module, object_name)
except AttributeError:
msg = 'Module %r does not define an object named %r'
raise ImproperlyConfigured(msg % (module_name, object_name)) | Return the Python object represented by dotted *path*. | train | https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/loaders.py#L12-L28 | null | """Django EL Pagination object loaders."""
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
|
argaen/aiocache | aiocache/serializers/serializers.py | MsgPackSerializer.loads | python | def loads(self, value):
raw = False if self.encoding == "utf-8" else True
if value is None:
return None
return msgpack.loads(value, raw=raw, use_list=self.use_list) | Deserialize value using ``msgpack.loads``.
:param value: bytes
:returns: obj | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/serializers/serializers.py#L178-L188 | null | class MsgPackSerializer(BaseSerializer):
"""
Transform data to bytes using msgpack.dumps and msgpack.loads to retrieve it back. You need
to have ``msgpack`` installed in order to be able to use this serializer.
:param encoding: str. Can be used to change encoding param for ``msg.loads`` method.
Default is utf-8.
:param use_list: bool. Can be used to change use_list param for ``msgpack.loads`` method.
Default is True.
"""
def __init__(self, *args, use_list=True, **kwargs):
self.use_list = use_list
super().__init__(*args, **kwargs)
def dumps(self, value):
"""
Serialize the received value using ``msgpack.dumps``.
:param value: obj
:returns: bytes
"""
return msgpack.dumps(value)
|
argaen/aiocache | aiocache/backends/redis.py | RedisCache.parse_uri_path | python | def parse_uri_path(self, path):
options = {}
db, *_ = path[1:].split("/")
if db:
options["db"] = db
return options | Given a uri path, return the Redis specific configuration
options in that path string according to iana definition
http://www.iana.org/assignments/uri-schemes/prov/redis
:param path: string containing the path. Example: "/0"
:return: mapping containing the options. Example: {"db": "0"} | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/backends/redis.py#L255-L268 | null | class RedisCache(RedisBackend, BaseCache):
"""
Redis cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.JsonSerializer`
- plugins: []
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5.
:param endpoint: str with the endpoint to connect to. Default is "127.0.0.1".
:param port: int with the port to connect to. Default is 6379.
:param db: int indicating database to use. Default is 0.
:param password: str indicating password to use. Default is None.
:param pool_min_size: int minimum pool size for the redis connections pool. Default is 1
:param pool_max_size: int maximum pool size for the redis connections pool. Default is 10
:param create_connection_timeout: int timeout for the creation of connection,
only for aioredis>=1. Default is None
"""
NAME = "redis"
def __init__(self, serializer=None, **kwargs):
super().__init__(**kwargs)
self.serializer = serializer or JsonSerializer()
@classmethod
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}{}".format(namespace, ":" if namespace else "", key)
if self.namespace is not None:
return "{}{}{}".format(self.namespace, ":" if self.namespace else "", key)
return key
def __repr__(self): # pragma: no cover
return "RedisCache ({}:{})".format(self.endpoint, self.port)
|
argaen/aiocache | aiocache/base.py | API.timeout | python | def timeout(cls, func):
NOT_SET = "NOT_SET"
@functools.wraps(func)
async def _timeout(self, *args, timeout=NOT_SET, **kwargs):
timeout = self.timeout if timeout == NOT_SET else timeout
if timeout == 0 or timeout is None:
return await func(self, *args, **kwargs)
return await asyncio.wait_for(func(self, *args, **kwargs), timeout)
return _timeout | This decorator sets a maximum timeout for a coroutine to execute. The timeout can be both
set in the ``self.timeout`` attribute or in the ``timeout`` kwarg of the function call.
I.e if you have a function ``get(self, key)``, if its decorated with this decorator, you
will be able to call it with ``await get(self, "my_key", timeout=4)``.
Use 0 or None to disable the timeout. | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L29-L47 | null | class API:
CMDS = set()
@classmethod
def register(cls, func):
API.CMDS.add(func)
return func
@classmethod
def unregister(cls, func):
API.CMDS.discard(func)
@classmethod
@classmethod
def aiocache_enabled(cls, fake_return=None):
"""
Use this decorator to be able to fake the return of the function by setting the
``AIOCACHE_DISABLE`` environment variable
"""
def enabled(func):
@functools.wraps(func)
async def _enabled(*args, **kwargs):
if os.getenv("AIOCACHE_DISABLE") == "1":
return fake_return
return await func(*args, **kwargs)
return _enabled
return enabled
@classmethod
def plugins(cls, func):
@functools.wraps(func)
async def _plugins(self, *args, **kwargs):
start = time.monotonic()
for plugin in self.plugins:
await getattr(plugin, "pre_{}".format(func.__name__))(self, *args, **kwargs)
ret = await func(self, *args, **kwargs)
end = time.monotonic()
for plugin in self.plugins:
await getattr(plugin, "post_{}".format(func.__name__))(
self, *args, took=end - start, ret=ret, **kwargs
)
return ret
return _plugins
|
argaen/aiocache | aiocache/base.py | API.aiocache_enabled | python | def aiocache_enabled(cls, fake_return=None):
def enabled(func):
@functools.wraps(func)
async def _enabled(*args, **kwargs):
if os.getenv("AIOCACHE_DISABLE") == "1":
return fake_return
return await func(*args, **kwargs)
return _enabled
return enabled | Use this decorator to be able to fake the return of the function by setting the
``AIOCACHE_DISABLE`` environment variable | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L50-L65 | null | class API:
CMDS = set()
@classmethod
def register(cls, func):
API.CMDS.add(func)
return func
@classmethod
def unregister(cls, func):
API.CMDS.discard(func)
@classmethod
def timeout(cls, func):
"""
This decorator sets a maximum timeout for a coroutine to execute. The timeout can be both
set in the ``self.timeout`` attribute or in the ``timeout`` kwarg of the function call.
I.e if you have a function ``get(self, key)``, if its decorated with this decorator, you
will be able to call it with ``await get(self, "my_key", timeout=4)``.
Use 0 or None to disable the timeout.
"""
NOT_SET = "NOT_SET"
@functools.wraps(func)
async def _timeout(self, *args, timeout=NOT_SET, **kwargs):
timeout = self.timeout if timeout == NOT_SET else timeout
if timeout == 0 or timeout is None:
return await func(self, *args, **kwargs)
return await asyncio.wait_for(func(self, *args, **kwargs), timeout)
return _timeout
@classmethod
@classmethod
def plugins(cls, func):
@functools.wraps(func)
async def _plugins(self, *args, **kwargs):
start = time.monotonic()
for plugin in self.plugins:
await getattr(plugin, "pre_{}".format(func.__name__))(self, *args, **kwargs)
ret = await func(self, *args, **kwargs)
end = time.monotonic()
for plugin in self.plugins:
await getattr(plugin, "post_{}".format(func.__name__))(
self, *args, took=end - start, ret=ret, **kwargs
)
return ret
return _plugins
|
argaen/aiocache | aiocache/base.py | BaseCache.add | python | async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True | Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L140-L166 | [
"async def _add(self, key, value, ttl, _conn=None):\n raise NotImplementedError()\n",
"def _get_ttl(self, ttl):\n return ttl if ttl is not SENTINEL else self.ttl\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.get | python | async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default | Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L175-L195 | [
"async def _get(self, key, encoding, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.multi_get | python | async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values | Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L204-L233 | [
"async def _multi_get(self, keys, encoding, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.set | python | async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res | Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L242-L269 | [
"async def _set(self, key, value, ttl, _cas_token=None, _conn=None):\n raise NotImplementedError()\n",
"def _get_ttl(self, ttl):\n return ttl if ttl is not SENTINEL else self.ttl\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.multi_set | python | async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True | Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L278-L308 | [
"async def _multi_set(self, pairs, ttl, _conn=None):\n raise NotImplementedError()\n",
"def _get_ttl(self, ttl):\n return ttl if ttl is not SENTINEL else self.ttl\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.delete | python | async def delete(self, key, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret | Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L317-L332 | [
"async def _delete(self, key, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.exists | python | async def exists(self, key, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret | Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L341-L356 | [
"async def _exists(self, key, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.increment | python | async def increment(self, key, delta=1, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret | Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L365-L383 | [
"async def _increment(self, key, delta, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.expire | python | async def expire(self, key, ttl, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret | Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L392-L408 | [
"async def _expire(self, key, ttl, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.clear | python | async def clear(self, namespace=None, _conn=None):
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret | Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L417-L431 | [
"async def _clear(self, namespace, _conn=None):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.raw | python | async def raw(self, command, *args, _conn=None, **kwargs):
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret | Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L440-L459 | [
"async def _raw(self, command, *args, **kwargs):\n raise NotImplementedError()\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def close(self, *args, _conn=None, **kwargs):
"""
Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/base.py | BaseCache.close | python | async def close(self, *args, _conn=None, **kwargs):
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret | Perform any resource clean up necessary to exit the program safely.
After closing, cmd execution is still possible but you will have to
close again before exiting.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L465-L476 | [
"async def _close(self, *args, **kwargs):\n pass\n"
] | class BaseCache:
"""
Base class that agregates the common logic for the different caches that may exist. Cache
related available options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. Default is
:class:`aiocache.serializers.StringSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. Default is empty
list.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
:param key_builder: alternative callable to build the key. Receives the key and the namespace as
params and should return something that can be used as key by the underlying backend.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5. Use 0 or None if you want to disable it.
:param ttl: int the expiration time in seconds to use as a default in all operations of
the backend. It can be overriden in the specific calls.
"""
def __init__(
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
):
self.timeout = float(timeout) if timeout is not None else timeout
self.namespace = namespace
self.ttl = float(ttl) if ttl is not None else ttl
self.build_key = key_builder or self._build_key
self._serializer = None
self.serializer = serializer or serializers.StringSerializer()
self._plugins = None
self.plugins = plugins or []
@property
def serializer(self):
return self._serializer
@serializer.setter
def serializer(self, value):
self._serializer = value
@property
def plugins(self):
return self._plugins
@plugins.setter
def plugins(self, value):
self._plugins = value
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key is inserted
:raises:
- ValueError if key already exists
- :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug("ADD %s %s (%.4f)s", ns_key, True, time.monotonic() - start)
return True
async def _add(self, key, value, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: obj loaded
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))
logger.debug("GET %s %s (%.4f)s", ns_key, value is not None, time.monotonic() - start)
return value if value is not None else default
async def _get(self, key, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=[])
@API.timeout
@API.plugins
async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: list of objs
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
loads(value)
for value in await self._multi_get(
ns_keys, encoding=self.serializer.encoding, _conn=_conn
)
]
logger.debug(
"MULTI_GET %s %d (%.4f)s",
ns_keys,
len([value for value in values if value is not None]),
time.monotonic() - start,
)
return values
async def _multi_get(self, keys, encoding, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
"""
Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if the value was set
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn
)
logger.debug("SET %s %d (%.4f)s", ns_key, True, time.monotonic() - start)
return res
async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
:param dumps_fn: callable alternative to use as dumps function
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self.build_key(key, namespace=namespace), dumps(value)))
await self._multi_set(tmp_pairs, ttl=self._get_ttl(ttl), _conn=_conn)
logger.debug(
"MULTI_SET %s %d (%.4f)s",
[key for key, value in tmp_pairs],
len(pairs),
time.monotonic() - start,
)
return True
async def _multi_set(self, pairs, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=0)
@API.timeout
@API.plugins
async def delete(self, key, namespace=None, _conn=None):
"""
Deletes the given key.
:param key: Key to be deleted
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: int number of deleted keys
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _delete(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def exists(self, key, namespace=None, _conn=None):
"""
Check key exists in the cache.
:param key: str key to check
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if key exists otherwise False
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _exists(self, key, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=1)
@API.timeout
@API.plugins
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: Value of the key once incremented. -1 if key is not found.
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
:raises: :class:`TypeError` if value is not incrementable
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _increment(self, key, delta, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=False)
@API.timeout
@API.plugins
async def expire(self, key, ttl, namespace=None, _conn=None):
"""
Set the ttl to the given key. By setting it to 0, it will disable it
:param key: str key to expire
:param ttl: int number of seconds for expiration. If 0, ttl is disabled
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True if set, False if key is not found
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, ret, time.monotonic() - start)
return ret
async def _expire(self, key, ttl, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled(fake_return=True)
@API.timeout
@API.plugins
async def clear(self, namespace=None, _conn=None):
"""
Clears the cache in the cache namespace. If an alternative namespace is given, it will
clear those ones instead.
:param namespace: str alternative namespace to use
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: True
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret
async def _clear(self, namespace, _conn=None):
raise NotImplementedError()
@API.register
@API.aiocache_enabled()
@API.timeout
@API.plugins
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeout: int or float in seconds specifying maximum timeout
for the operations to last
:returns: whatever the underlying client returns
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
"""
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time.monotonic() - start)
return ret
async def _raw(self, command, *args, **kwargs):
raise NotImplementedError()
@API.timeout
async def _close(self, *args, **kwargs):
pass
def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}".format(namespace, key)
if self.namespace is not None:
return "{}{}".format(self.namespace, key)
return key
def _get_ttl(self, ttl):
return ttl if ttl is not SENTINEL else self.ttl
def get_connection(self):
return _Conn(self)
async def acquire_conn(self):
return self
async def release_conn(self, conn):
pass
|
argaen/aiocache | aiocache/lock.py | OptimisticLock.cas | python | async def cas(self, value: Any, **kwargs) -> bool:
success = await self.client.set(self.key, value, _cas_token=self._token, **kwargs)
if not success:
raise OptimisticLockError("Value has changed since the lock started")
return True | Checks and sets the specified value for the locked key. If the value has changed
since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError`
exception.
:raises: :class:`aiocache.lock.OptimisticLockError` | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/lock.py#L153-L164 | null | class OptimisticLock:
"""
Implementation of
`optimistic lock <https://en.wikipedia.org/wiki/Optimistic_concurrency_control>`_
Optimistic locking assumes multiple transactions can happen at the same time
and they will only fail if before finish, conflicting modifications with other
transactions are found, producing a roll back.
Finding a conflict will end up raising an `aiocache.lock.OptimisticLockError`
exception. A conflict happens when the value at the storage is different from
the one we retrieved when the lock started.
Example usage::
cache = Cache(Cache.REDIS)
# The value stored in 'key' will be checked here
async with OptimisticLock(cache, 'key') as lock:
result = await super_expensive_call()
await lock.cas(result)
If any other call sets the value of ``key`` before the ``lock.cas`` is called,
an :class:`aiocache.lock.OptimisticLockError` will be raised. A way to make
the same call crash would be to change the value inside the lock like::
cache = Cache(Cache.REDIS)
# The value stored in 'key' will be checked here
async with OptimisticLock(cache, 'key') as lock:
result = await super_expensive_call()
await cache.set('random_value') # This will make the `lock.cas` call fail
await lock.cas(result)
If the lock is created with an unexisting key, there will never be conflicts.
"""
def __init__(self, client: BaseCache, key: str):
self.client = client
self.key = key
self.ns_key = self.client._build_key(key)
self._token = None
async def __aenter__(self):
return await self._acquire()
async def _acquire(self):
self._token = await self.client._gets(self.ns_key)
return self
async def __aexit__(self, exc_type, exc_value, traceback):
pass
|
argaen/aiocache | aiocache/factory.py | Cache.from_url | python | def from_url(cls, url):
parsed_url = urllib.parse.urlparse(url)
kwargs = dict(urllib.parse.parse_qsl(parsed_url.query))
cache_class = Cache.get_scheme_class(parsed_url.scheme)
if parsed_url.path:
kwargs.update(cache_class.parse_uri_path(parsed_url.path))
if parsed_url.hostname:
kwargs["endpoint"] = parsed_url.hostname
if parsed_url.port:
kwargs["port"] = parsed_url.port
if parsed_url.password:
kwargs["password"] = parsed_url.password
return Cache(cache_class, **kwargs) | Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
a more advanced usage using queryparams to configure the cache:
>>> from aiocache import Cache
>>> cache = Cache.from_url('redis://localhost:10/1?pool_min_size=1')
>>> cache
RedisCache (localhost:10)
>>> cache.db
1
>>> cache.pool_min_size
1
:param url: string identifying the resource uri of the cache to connect to | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/factory.py#L88-L126 | [
"def get_scheme_class(cls, scheme):\n try:\n return cls._get_cache_class(scheme)\n except KeyError as e:\n raise InvalidCacheType(\n \"Invalid cache type, you can only use {}\".format(list(AIOCACHE_CACHES.keys()))\n ) from e\n"
] | class Cache:
"""
This class is just a proxy to the specific cache implementations like
:class:`aiocache.SimpleMemoryCache`, :class:`aiocache.RedisCache` and
:class:`aiocache.MemcachedCache`. It is the preferred method of
instantiating new caches over using the backend specific classes.
You can instatiate a new one using the ``cache_type`` attribute like:
>>> from aiocache import Cache
>>> Cache(Cache.REDIS)
RedisCache (127.0.0.1:6379)
If you don't specify anything, ``Cache.MEMORY`` is used.
Only ``Cache.MEMORY``, ``Cache.REDIS`` and ``Cache.MEMCACHED`` types
are allowed. If the type passed is invalid, it will raise a
:class:`aiocache.exceptions.InvalidCacheType` exception.
"""
MEMORY = SimpleMemoryCache
REDIS = RedisCache
MEMCACHED = MemcachedCache
def __new__(cls, cache_class=MEMORY, **kwargs):
try:
assert issubclass(cache_class, BaseCache)
except AssertionError as e:
raise InvalidCacheType(
"Invalid cache type, you can only use {}".format(list(AIOCACHE_CACHES.keys()))
) from e
instance = cache_class.__new__(cache_class, **kwargs)
instance.__init__(**kwargs)
return instance
@classmethod
def _get_cache_class(cls, scheme):
return AIOCACHE_CACHES[scheme]
@classmethod
def get_scheme_class(cls, scheme):
try:
return cls._get_cache_class(scheme)
except KeyError as e:
raise InvalidCacheType(
"Invalid cache type, you can only use {}".format(list(AIOCACHE_CACHES.keys()))
) from e
@classmethod
|
argaen/aiocache | aiocache/factory.py | CacheHandler.add | python | def add(self, alias: str, config: dict) -> None:
self._config[alias] = config | Add a cache to the current config. If the key already exists, it
will overwrite it::
>>> caches.add('default', {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
})
:param alias: The alias for the cache
:param config: Mapping containing the cache configuration | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/factory.py#L141-L156 | null | class CacheHandler:
_config = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def get(self, alias: str):
"""
Retrieve cache identified by alias. Will return always the same instance
If the cache was not instantiated yet, it will do it lazily the first time
this is called.
:param alias: str cache alias
:return: cache instance
"""
try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache
def create(self, alias=None, cache=None, **kwargs):
"""
Create a new cache. Either alias or cache params are required. You can use
kwargs to pass extra parameters to configure the cache.
.. deprecated:: 0.11.0
Only creating a cache passing an alias is supported. If you want to
create a cache passing explicit cache and kwargs use ``aiocache.Cache``.
:param alias: str alias to pull configuration from
:param cache: str or class cache class to use for creating the
new cache (when no alias is used)
:return: New cache instance
"""
if alias:
config = self.get_alias_config(alias)
elif cache:
warnings.warn(
"Creating a cache with an explicit config is deprecated, use 'aiocache.Cache'",
DeprecationWarning,
)
config = {"cache": cache}
else:
raise TypeError("create call needs to receive an alias or a cache")
cache = _create_cache(**{**config, **kwargs})
return cache
def get_alias_config(self, alias):
config = self.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{0}', ensure you include {0} when calling"
"caches.set_config specifying the config for that cache".format(alias)
)
return config[alias]
def get_config(self):
"""
Return copy of current stored config
"""
return deepcopy(self._config)
def set_config(self, config):
"""
Set (override) the default config for cache aliases from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
If a config key already exists, it will be updated with the new values.
"""
if "default" not in config:
raise ValueError("default config must be provided")
for config_name in config.keys():
self._caches.pop(config_name, None)
self._config = config
|
argaen/aiocache | aiocache/factory.py | CacheHandler.get | python | def get(self, alias: str):
try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache | Retrieve cache identified by alias. Will return always the same instance
If the cache was not instantiated yet, it will do it lazily the first time
this is called.
:param alias: str cache alias
:return: cache instance | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/factory.py#L158-L176 | [
"def _create_cache(cache, serializer=None, plugins=None, **kwargs):\n\n if serializer is not None:\n cls = serializer.pop(\"class\")\n cls = _class_from_string(cls) if isinstance(cls, str) else cls\n serializer = cls(**serializer)\n\n plugins_instances = []\n if plugins is not None:\n for plugin in plugins:\n cls = plugin.pop(\"class\")\n cls = _class_from_string(cls) if isinstance(cls, str) else cls\n plugins_instances.append(cls(**plugin))\n\n cache = _class_from_string(cache) if isinstance(cache, str) else cache\n instance = cache(serializer=serializer, plugins=plugins_instances, **kwargs)\n return instance\n",
"def get_alias_config(self, alias):\n config = self.get_config()\n if alias not in config:\n raise KeyError(\n \"Could not find config for '{0}', ensure you include {0} when calling\"\n \"caches.set_config specifying the config for that cache\".format(alias)\n )\n\n return config[alias]\n"
] | class CacheHandler:
_config = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def add(self, alias: str, config: dict) -> None:
"""
Add a cache to the current config. If the key already exists, it
will overwrite it::
>>> caches.add('default', {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
})
:param alias: The alias for the cache
:param config: Mapping containing the cache configuration
"""
self._config[alias] = config
def create(self, alias=None, cache=None, **kwargs):
"""
Create a new cache. Either alias or cache params are required. You can use
kwargs to pass extra parameters to configure the cache.
.. deprecated:: 0.11.0
Only creating a cache passing an alias is supported. If you want to
create a cache passing explicit cache and kwargs use ``aiocache.Cache``.
:param alias: str alias to pull configuration from
:param cache: str or class cache class to use for creating the
new cache (when no alias is used)
:return: New cache instance
"""
if alias:
config = self.get_alias_config(alias)
elif cache:
warnings.warn(
"Creating a cache with an explicit config is deprecated, use 'aiocache.Cache'",
DeprecationWarning,
)
config = {"cache": cache}
else:
raise TypeError("create call needs to receive an alias or a cache")
cache = _create_cache(**{**config, **kwargs})
return cache
def get_alias_config(self, alias):
config = self.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{0}', ensure you include {0} when calling"
"caches.set_config specifying the config for that cache".format(alias)
)
return config[alias]
def get_config(self):
"""
Return copy of current stored config
"""
return deepcopy(self._config)
def set_config(self, config):
"""
Set (override) the default config for cache aliases from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
If a config key already exists, it will be updated with the new values.
"""
if "default" not in config:
raise ValueError("default config must be provided")
for config_name in config.keys():
self._caches.pop(config_name, None)
self._config = config
|
argaen/aiocache | aiocache/factory.py | CacheHandler.create | python | def create(self, alias=None, cache=None, **kwargs):
if alias:
config = self.get_alias_config(alias)
elif cache:
warnings.warn(
"Creating a cache with an explicit config is deprecated, use 'aiocache.Cache'",
DeprecationWarning,
)
config = {"cache": cache}
else:
raise TypeError("create call needs to receive an alias or a cache")
cache = _create_cache(**{**config, **kwargs})
return cache | Create a new cache. Either alias or cache params are required. You can use
kwargs to pass extra parameters to configure the cache.
.. deprecated:: 0.11.0
Only creating a cache passing an alias is supported. If you want to
create a cache passing explicit cache and kwargs use ``aiocache.Cache``.
:param alias: str alias to pull configuration from
:param cache: str or class cache class to use for creating the
new cache (when no alias is used)
:return: New cache instance | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/factory.py#L178-L203 | [
"def _create_cache(cache, serializer=None, plugins=None, **kwargs):\n\n if serializer is not None:\n cls = serializer.pop(\"class\")\n cls = _class_from_string(cls) if isinstance(cls, str) else cls\n serializer = cls(**serializer)\n\n plugins_instances = []\n if plugins is not None:\n for plugin in plugins:\n cls = plugin.pop(\"class\")\n cls = _class_from_string(cls) if isinstance(cls, str) else cls\n plugins_instances.append(cls(**plugin))\n\n cache = _class_from_string(cache) if isinstance(cache, str) else cache\n instance = cache(serializer=serializer, plugins=plugins_instances, **kwargs)\n return instance\n",
"def get_alias_config(self, alias):\n config = self.get_config()\n if alias not in config:\n raise KeyError(\n \"Could not find config for '{0}', ensure you include {0} when calling\"\n \"caches.set_config specifying the config for that cache\".format(alias)\n )\n\n return config[alias]\n"
] | class CacheHandler:
_config = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def add(self, alias: str, config: dict) -> None:
"""
Add a cache to the current config. If the key already exists, it
will overwrite it::
>>> caches.add('default', {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
})
:param alias: The alias for the cache
:param config: Mapping containing the cache configuration
"""
self._config[alias] = config
def get(self, alias: str):
"""
Retrieve cache identified by alias. Will return always the same instance
If the cache was not instantiated yet, it will do it lazily the first time
this is called.
:param alias: str cache alias
:return: cache instance
"""
try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache
def get_alias_config(self, alias):
config = self.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{0}', ensure you include {0} when calling"
"caches.set_config specifying the config for that cache".format(alias)
)
return config[alias]
def get_config(self):
"""
Return copy of current stored config
"""
return deepcopy(self._config)
def set_config(self, config):
"""
Set (override) the default config for cache aliases from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
If a config key already exists, it will be updated with the new values.
"""
if "default" not in config:
raise ValueError("default config must be provided")
for config_name in config.keys():
self._caches.pop(config_name, None)
self._config = config
|
argaen/aiocache | aiocache/factory.py | CacheHandler.set_config | python | def set_config(self, config):
if "default" not in config:
raise ValueError("default config must be provided")
for config_name in config.keys():
self._caches.pop(config_name, None)
self._config = config | Set (override) the default config for cache aliases from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
If a config key already exists, it will be updated with the new values. | train | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/factory.py#L221-L271 | null | class CacheHandler:
_config = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def add(self, alias: str, config: dict) -> None:
"""
Add a cache to the current config. If the key already exists, it
will overwrite it::
>>> caches.add('default', {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
})
:param alias: The alias for the cache
:param config: Mapping containing the cache configuration
"""
self._config[alias] = config
def get(self, alias: str):
"""
Retrieve cache identified by alias. Will return always the same instance
If the cache was not instantiated yet, it will do it lazily the first time
this is called.
:param alias: str cache alias
:return: cache instance
"""
try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache
def create(self, alias=None, cache=None, **kwargs):
"""
Create a new cache. Either alias or cache params are required. You can use
kwargs to pass extra parameters to configure the cache.
.. deprecated:: 0.11.0
Only creating a cache passing an alias is supported. If you want to
create a cache passing explicit cache and kwargs use ``aiocache.Cache``.
:param alias: str alias to pull configuration from
:param cache: str or class cache class to use for creating the
new cache (when no alias is used)
:return: New cache instance
"""
if alias:
config = self.get_alias_config(alias)
elif cache:
warnings.warn(
"Creating a cache with an explicit config is deprecated, use 'aiocache.Cache'",
DeprecationWarning,
)
config = {"cache": cache}
else:
raise TypeError("create call needs to receive an alias or a cache")
cache = _create_cache(**{**config, **kwargs})
return cache
def get_alias_config(self, alias):
config = self.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{0}', ensure you include {0} when calling"
"caches.set_config specifying the config for that cache".format(alias)
)
return config[alias]
def get_config(self):
"""
Return copy of current stored config
"""
return deepcopy(self._config)
|
SwoopSearch/pyaddress | address/dstk.py | post_multipart | python | def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
return h.file.read() | Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's response page. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/dstk.py#L208-L223 | [
"def encode_multipart_formdata(fields, files):\n \"\"\"\n fields is a sequence of (name, value) elements for regular form fields.\n files is a sequence of (name, filename, value) elements for data to be uploaded as files\n Return (content_type, body) ready for httplib.HTTP instance\n \"\"\"\n BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'\n CRLF = '\\r\\n'\n L = []\n for (key, value) in fields:\n L.append('--' + BOUNDARY)\n L.append('Content-Disposition: form-data; name=\"%s\"' % key)\n L.append('')\n L.append(value)\n for (key, filename, value) in files:\n L.append('--' + BOUNDARY)\n L.append('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (key, filename))\n L.append('Content-Type: %s' % guess_content_type(filename))\n L.append('')\n L.append(value)\n L.append('--' + BOUNDARY + '--')\n L.append('')\n body = CRLF.join(L)\n content_type = 'multipart/form-data; boundary=%s' % BOUNDARY\n return content_type, body\n"
] | #!/usr/bin/env python
# Python interface to the Data Science Toolkit Plugin
# version: 1.30 (2011-03-16)
#
# See http://www.datasciencetoolkit.org/developerdocs#python for full details
#
# All code (C) Pete Warden, 2011
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urllib
try:
import simplejson as json
except ImportError:
import json
import os
import httplib
import mimetypes
import re
import csv
# This is the main interface class. You can see an example of it in use
# below, implementing a command-line tool, but you basically just instantiate
# dstk = DSTK()
# and then call the method you want
# coordinates = dstk.ip2coordinates('12.34.56.78')
# The full documentation is at http://www.datasciencetoolkit.org/developerdocs
class DSTK:
api_base = None
def __init__(self, options=None):
if options is None:
options = {}
defaultOptions = {
'apiBase': 'http://www.datasciencetoolkit.org',
'checkVersion': True
}
if 'DSTK_API_BASE' in os.environ:
defaultOptions['apiBase'] = os.environ['DSTK_API_BASE']
for key, value in defaultOptions.items():
if key not in options:
options[key] = value
self.api_base = options['apiBase']
if options['checkVersion']:
self.check_version()
def check_version(self):
required_version = 40
api_url = self.api_base+'/info'
try:
response_string = urllib.urlopen(api_url).read()
response = json.loads(response_string)
except:
raise Exception('The server at "'+self.api_base+'" doesn\'t seem to be running DSTK, no version information found.')
actual_version = response['version']
if actual_version < required_version:
raise Exception('DSTK: Version '+str(actual_version)+' found at "'+api_url+'" but '+str(required_version)+' is required')
def ip2coordinates(self, ips):
if not isinstance(ips, (list, tuple)):
ips = [ips]
api_url = self.api_base+'/ip2coordinates'
api_body = json.dumps(ips)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def street2coordinates(self, addresses):
if not isinstance(addresses, (list, tuple)):
addresses = [addresses]
api_url = self.api_base+'/street2coordinates'
api_body = json.dumps(addresses)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def coordinates2politics(self, coordinates):
api_url = self.api_base+'/coordinates2politics'
api_body = json.dumps(coordinates)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2places(self, text):
api_url = self.api_base+'/text2places'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def file2text(self, file_name, file_data):
host = self.api_base.replace('http://', '')
response = post_multipart(host,
'/file2text',[],[('inputfile', file_name, file_data)])
return response
def text2sentences(self, text):
api_url = self.api_base+'/text2sentences'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def html2text(self, html):
api_url = self.api_base+'/html2text'
api_body = html
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def html2story(self, html):
api_url = self.api_base+'/html2story'
api_body = html
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2people(self, text):
api_url = self.api_base+'/text2people'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2times(self, text):
api_url = self.api_base+'/text2times'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
# We need to post files as multipart form data, and Python has no native function for
# that, so these utility functions implement what we need.
# See http://code.activestate.com/recipes/146306/
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % guess_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def guess_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# End of the interface. The rest of this file is an example implementation of a
# command line client.
def ip2coordinates_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
input_ips = []
for input_line in inputs:
ip_match = re.match(r'[12]?\d?\d\.[12]?\d?\d\.[12]?\d?\d\.[12]?\d?\d', input_line)
if ip_match is not None:
input_ips.append(ip_match.group(0))
else:
print 'No match'
result = dstk.ip2coordinates(input_ips)
if options['showHeaders']:
for ip, info in result.items():
if info is None:
continue
row = ['ip_address']
for key, value in info.items():
row.append(str(key))
writer.writerow(row)
break
for ip, info in result.items():
if info is None:
info = {}
row = [ip]
for key, value in info.items():
row.append(str(value))
writer.writerow(row)
return
def street2coordinates_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
result = dstk.street2coordinates(inputs)
if options['showHeaders']:
for ip, info in result.items():
if info is None:
continue
row = ['address']
for key, value in info.items():
row.append(str(key))
writer.writerow(row)
break
for ip, info in result.items():
if info is None:
info = {}
row = [ip]
for key, value in info.items():
row.append(str(value))
writer.writerow(row)
return
def coordinates2politics_cli(dstk, options, inputs, output):
writer = csv.writer(output)
coordinates_list = []
for input in inputs:
coordinates = input.split(',')
if len(coordinates)!=2:
output.write('You must enter coordinates as a series of comma-separated pairs, eg 37.76,-122.42')
exit(-1)
coordinates_list.append([coordinates[0], coordinates[1]])
result = dstk.coordinates2politics(coordinates_list)
if options['showHeaders']:
row = ['latitude', 'longitude', 'name', 'code', 'type', 'friendly_type']
writer.writerow(row)
for info in result:
location = info['location']
politics = info['politics']
for politic in politics:
row = [location['latitude'],
location['longitude'],
politic['name'],
politic['code'],
politic['type'],
politic['friendly_type'],
]
writer.writerow(row)
return
def file2text_cli(dstk, options, inputs, output):
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
file2text_cli(dstk, options, full_children)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.file2text(file_name, file_data)
print result
return
def text2places_cli(dstk, options, inputs, output):
writer = csv.writer(output)
if options['showHeaders']:
row = ['latitude', 'longitude', 'name', 'type', 'start_index', 'end_index', 'matched_string', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2places("\n".join(inputs))
text2places_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2places_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2places(file_data)
text2places_format(result, file_name, writer)
return
def text2places_format(result, file_name, writer):
for info in result:
row = [info['latitude'],
info['longitude'],
info['name'],
info['type'],
info['start_index'],
info['end_index'],
info['matched_string'],
file_name
]
writer.writerow(row)
return
def html2text_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.html2text("\n".join(inputs))
print result['text']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
html2text_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.html2text(file_data)
print result['text']
return
def text2sentences_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.text2sentences("\n".join(inputs))
print result['sentences']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2sentences_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.text2sentences(file_data)
print result['sentences']
return
def html2story_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.html2story("\n".join(inputs))
print result['story']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
html2story_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.html2story(file_data)
print result['story']
return
def text2people_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
if options['showHeaders']:
row = ['matched_string', 'first_name', 'surnames', 'title', 'gender', 'start_index', 'end_index', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2people("\n".join(inputs))
text2people_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2places_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2people(file_data)
text2people_format(result, file_name, writer)
return
def text2people_format(result, file_name, writer):
for info in result:
row = [
info['matched_string'],
info['first_name'],
info['surnames'],
info['title'],
info['gender'],
str(info['start_index']),
str(info['end_index']),
file_name
]
writer.writerow(row)
return
def text2times_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
if options['showHeaders']:
row = ['matched_string', 'time_string', 'time_seconds', 'is_relative', 'start_index', 'end_index', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2times("\n".join(inputs))
text2times_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2times_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2times(file_data)
text2times_format(result, file_name, writer)
return
def text2times_format(result, file_name, writer):
for info in result:
row = [
info['matched_string'],
info['time_string'],
info['time_seconds'],
info['is_relative'],
str(info['start_index']),
str(info['end_index']),
file_name
]
writer.writerow(row)
return
def get_file_or_url_contents(file_name):
if re.match(r'http://', file_name):
file_data = urllib.urlopen(file_name).read()
else:
file_data = open(file_name).read()
return file_data
def print_usage(message=''):
print message
print "Usage:"
print "python dstk.py <command> [-a/--api_base 'http://yourhost.com'] [-h/--show_headers] <inputs>"
print "Where <command> is one of:"
print " ip2coordinates (lat/lons for IP addresses)"
print " street2coordinates (lat/lons for postal addresses)"
print " coordinates2politics (country/state/county/constituency/etc for lat/lon)"
print " text2places (lat/lons for places mentioned in unstructured text)"
print " file2text (PDF/Excel/Word to text, and OCR on PNG/Jpeg/Tiff images)"
print " text2sentences (parts of the text that look like proper sentences)"
print " html2text (text version of the HTML document)"
print " html2story (text version of the HTML with no boilerplate)"
print " text2people (gender for people mentioned in unstructured text)"
print " text2times (times and dates mentioned in unstructured text)"
print "If no inputs are specified, then standard input will be read and used"
print "See http://www.datasciencetoolkit.org/developerdocs for more details"
print "Examples:"
print "python dstk.py ip2coordinates 67.169.73.113"
print "python dstk.py street2coordinates \"2543 Graystone Place, Simi Valley, CA 93065\""
print "python dstk.py file2text scanned.jpg"
exit(-1)
if __name__ == '__main__':
import sys
commands = {
'ip2coordinates': { 'handler': ip2coordinates_cli },
'street2coordinates': { 'handler': street2coordinates_cli },
'coordinates2politics': { 'handler': coordinates2politics_cli },
'text2places': { 'handler': text2places_cli },
'file2text': { 'handler': file2text_cli },
'text2sentences': { 'handler': text2sentences_cli },
'html2text': { 'handler': html2text_cli },
'html2story': { 'handler': html2story_cli },
'text2people': { 'handler': text2people_cli },
'text2times': { 'handler': text2times_cli },
}
switches = {
'api_base': True,
'show_headers': True
}
command = None
options = {'showHeaders': False}
inputs = []
ignore_next = False
for index, arg in enumerate(sys.argv[1:]):
if ignore_next:
ignore_next = False
continue
if arg[0]=='-' and len(arg)>1:
if len(arg) == 2:
letter = arg[1]
if letter == 'a':
option = 'api_base'
elif letter == 'h':
option = 'show_headers'
else:
option = arg[2:]
if option not in switches:
print_usage('Unknown option "'+arg+'"')
if option == 'api_base':
if (index+2) >= len(sys.argv):
print_usage('Missing argument for option "'+arg+'"')
options['apiBase'] = sys.argv[index+2]
ignore_next = True
elif option == 'show_headers':
options['showHeaders'] = True
else:
if command is None:
command = arg
if command not in commands:
print_usage('Unknown command "'+arg+'"')
else:
inputs.append(arg)
if command is None:
print_usage('No command specified')
if len(inputs)<1:
options['from_stdin'] = True
inputs = sys.stdin.readlines()
else:
options['from_stdin'] = False
command_info = commands[command]
dstk = DSTK(options)
command_info['handler'](dstk, options, inputs, sys.stdout) |
SwoopSearch/pyaddress | address/dstk.py | encode_multipart_formdata | python | def encode_multipart_formdata(fields, files):
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % guess_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body | fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/dstk.py#L225-L249 | [
"def guess_content_type(filename):\n return mimetypes.guess_type(filename)[0] or 'application/octet-stream'\n"
] | #!/usr/bin/env python
# Python interface to the Data Science Toolkit Plugin
# version: 1.30 (2011-03-16)
#
# See http://www.datasciencetoolkit.org/developerdocs#python for full details
#
# All code (C) Pete Warden, 2011
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urllib
try:
import simplejson as json
except ImportError:
import json
import os
import httplib
import mimetypes
import re
import csv
# This is the main interface class. You can see an example of it in use
# below, implementing a command-line tool, but you basically just instantiate
# dstk = DSTK()
# and then call the method you want
# coordinates = dstk.ip2coordinates('12.34.56.78')
# The full documentation is at http://www.datasciencetoolkit.org/developerdocs
class DSTK:
api_base = None
def __init__(self, options=None):
if options is None:
options = {}
defaultOptions = {
'apiBase': 'http://www.datasciencetoolkit.org',
'checkVersion': True
}
if 'DSTK_API_BASE' in os.environ:
defaultOptions['apiBase'] = os.environ['DSTK_API_BASE']
for key, value in defaultOptions.items():
if key not in options:
options[key] = value
self.api_base = options['apiBase']
if options['checkVersion']:
self.check_version()
def check_version(self):
required_version = 40
api_url = self.api_base+'/info'
try:
response_string = urllib.urlopen(api_url).read()
response = json.loads(response_string)
except:
raise Exception('The server at "'+self.api_base+'" doesn\'t seem to be running DSTK, no version information found.')
actual_version = response['version']
if actual_version < required_version:
raise Exception('DSTK: Version '+str(actual_version)+' found at "'+api_url+'" but '+str(required_version)+' is required')
def ip2coordinates(self, ips):
if not isinstance(ips, (list, tuple)):
ips = [ips]
api_url = self.api_base+'/ip2coordinates'
api_body = json.dumps(ips)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def street2coordinates(self, addresses):
if not isinstance(addresses, (list, tuple)):
addresses = [addresses]
api_url = self.api_base+'/street2coordinates'
api_body = json.dumps(addresses)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def coordinates2politics(self, coordinates):
api_url = self.api_base+'/coordinates2politics'
api_body = json.dumps(coordinates)
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2places(self, text):
api_url = self.api_base+'/text2places'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def file2text(self, file_name, file_data):
host = self.api_base.replace('http://', '')
response = post_multipart(host,
'/file2text',[],[('inputfile', file_name, file_data)])
return response
def text2sentences(self, text):
api_url = self.api_base+'/text2sentences'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def html2text(self, html):
api_url = self.api_base+'/html2text'
api_body = html
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def html2story(self, html):
api_url = self.api_base+'/html2story'
api_body = html
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2people(self, text):
api_url = self.api_base+'/text2people'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
def text2times(self, text):
api_url = self.api_base+'/text2times'
api_body = text
response_string = urllib.urlopen(api_url, api_body).read()
response = json.loads(response_string)
if 'error' in response:
raise Exception(response['error'])
return response
# We need to post files as multipart form data, and Python has no native function for
# that, so these utility functions implement what we need.
# See http://code.activestate.com/recipes/146306/
def post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's response page.
"""
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
return h.file.read()
def guess_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# End of the interface. The rest of this file is an example implementation of a
# command line client.
def ip2coordinates_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
input_ips = []
for input_line in inputs:
ip_match = re.match(r'[12]?\d?\d\.[12]?\d?\d\.[12]?\d?\d\.[12]?\d?\d', input_line)
if ip_match is not None:
input_ips.append(ip_match.group(0))
else:
print 'No match'
result = dstk.ip2coordinates(input_ips)
if options['showHeaders']:
for ip, info in result.items():
if info is None:
continue
row = ['ip_address']
for key, value in info.items():
row.append(str(key))
writer.writerow(row)
break
for ip, info in result.items():
if info is None:
info = {}
row = [ip]
for key, value in info.items():
row.append(str(value))
writer.writerow(row)
return
def street2coordinates_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
result = dstk.street2coordinates(inputs)
if options['showHeaders']:
for ip, info in result.items():
if info is None:
continue
row = ['address']
for key, value in info.items():
row.append(str(key))
writer.writerow(row)
break
for ip, info in result.items():
if info is None:
info = {}
row = [ip]
for key, value in info.items():
row.append(str(value))
writer.writerow(row)
return
def coordinates2politics_cli(dstk, options, inputs, output):
writer = csv.writer(output)
coordinates_list = []
for input in inputs:
coordinates = input.split(',')
if len(coordinates)!=2:
output.write('You must enter coordinates as a series of comma-separated pairs, eg 37.76,-122.42')
exit(-1)
coordinates_list.append([coordinates[0], coordinates[1]])
result = dstk.coordinates2politics(coordinates_list)
if options['showHeaders']:
row = ['latitude', 'longitude', 'name', 'code', 'type', 'friendly_type']
writer.writerow(row)
for info in result:
location = info['location']
politics = info['politics']
for politic in politics:
row = [location['latitude'],
location['longitude'],
politic['name'],
politic['code'],
politic['type'],
politic['friendly_type'],
]
writer.writerow(row)
return
def file2text_cli(dstk, options, inputs, output):
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
file2text_cli(dstk, options, full_children)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.file2text(file_name, file_data)
print result
return
def text2places_cli(dstk, options, inputs, output):
writer = csv.writer(output)
if options['showHeaders']:
row = ['latitude', 'longitude', 'name', 'type', 'start_index', 'end_index', 'matched_string', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2places("\n".join(inputs))
text2places_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2places_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2places(file_data)
text2places_format(result, file_name, writer)
return
def text2places_format(result, file_name, writer):
for info in result:
row = [info['latitude'],
info['longitude'],
info['name'],
info['type'],
info['start_index'],
info['end_index'],
info['matched_string'],
file_name
]
writer.writerow(row)
return
def html2text_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.html2text("\n".join(inputs))
print result['text']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
html2text_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.html2text(file_data)
print result['text']
return
def text2sentences_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.text2sentences("\n".join(inputs))
print result['sentences']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2sentences_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.text2sentences(file_data)
print result['sentences']
return
def html2story_cli(dstk, options, inputs, output):
if options['from_stdin']:
result = dstk.html2story("\n".join(inputs))
print result['story']
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
html2story_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
if options['showHeaders']:
output.write('--File--: '+file_name+"\n")
result = dstk.html2story(file_data)
print result['story']
return
def text2people_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
if options['showHeaders']:
row = ['matched_string', 'first_name', 'surnames', 'title', 'gender', 'start_index', 'end_index', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2people("\n".join(inputs))
text2people_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2places_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2people(file_data)
text2people_format(result, file_name, writer)
return
def text2people_format(result, file_name, writer):
for info in result:
row = [
info['matched_string'],
info['first_name'],
info['surnames'],
info['title'],
info['gender'],
str(info['start_index']),
str(info['end_index']),
file_name
]
writer.writerow(row)
return
def text2times_cli(dstk, options, inputs, output):
writer = csv.writer(sys.stdout)
if options['showHeaders']:
row = ['matched_string', 'time_string', 'time_seconds', 'is_relative', 'start_index', 'end_index', 'file_name']
writer.writerow(row)
options['showHeaders'] = False
if options['from_stdin']:
result = dstk.text2times("\n".join(inputs))
text2times_format(result, 'stdin', writer)
return
for file_name in inputs:
if os.path.isdir(file_name):
children = os.listdir(file_name)
full_children = []
for child in children:
full_children.append(os.path.join(file_name, child))
text2times_cli(dstk, options, full_children, output)
else:
file_data = get_file_or_url_contents(file_name)
result = dstk.text2times(file_data)
text2times_format(result, file_name, writer)
return
def text2times_format(result, file_name, writer):
for info in result:
row = [
info['matched_string'],
info['time_string'],
info['time_seconds'],
info['is_relative'],
str(info['start_index']),
str(info['end_index']),
file_name
]
writer.writerow(row)
return
def get_file_or_url_contents(file_name):
if re.match(r'http://', file_name):
file_data = urllib.urlopen(file_name).read()
else:
file_data = open(file_name).read()
return file_data
def print_usage(message=''):
print message
print "Usage:"
print "python dstk.py <command> [-a/--api_base 'http://yourhost.com'] [-h/--show_headers] <inputs>"
print "Where <command> is one of:"
print " ip2coordinates (lat/lons for IP addresses)"
print " street2coordinates (lat/lons for postal addresses)"
print " coordinates2politics (country/state/county/constituency/etc for lat/lon)"
print " text2places (lat/lons for places mentioned in unstructured text)"
print " file2text (PDF/Excel/Word to text, and OCR on PNG/Jpeg/Tiff images)"
print " text2sentences (parts of the text that look like proper sentences)"
print " html2text (text version of the HTML document)"
print " html2story (text version of the HTML with no boilerplate)"
print " text2people (gender for people mentioned in unstructured text)"
print " text2times (times and dates mentioned in unstructured text)"
print "If no inputs are specified, then standard input will be read and used"
print "See http://www.datasciencetoolkit.org/developerdocs for more details"
print "Examples:"
print "python dstk.py ip2coordinates 67.169.73.113"
print "python dstk.py street2coordinates \"2543 Graystone Place, Simi Valley, CA 93065\""
print "python dstk.py file2text scanned.jpg"
exit(-1)
if __name__ == '__main__':
import sys
commands = {
'ip2coordinates': { 'handler': ip2coordinates_cli },
'street2coordinates': { 'handler': street2coordinates_cli },
'coordinates2politics': { 'handler': coordinates2politics_cli },
'text2places': { 'handler': text2places_cli },
'file2text': { 'handler': file2text_cli },
'text2sentences': { 'handler': text2sentences_cli },
'html2text': { 'handler': html2text_cli },
'html2story': { 'handler': html2story_cli },
'text2people': { 'handler': text2people_cli },
'text2times': { 'handler': text2times_cli },
}
switches = {
'api_base': True,
'show_headers': True
}
command = None
options = {'showHeaders': False}
inputs = []
ignore_next = False
for index, arg in enumerate(sys.argv[1:]):
if ignore_next:
ignore_next = False
continue
if arg[0]=='-' and len(arg)>1:
if len(arg) == 2:
letter = arg[1]
if letter == 'a':
option = 'api_base'
elif letter == 'h':
option = 'show_headers'
else:
option = arg[2:]
if option not in switches:
print_usage('Unknown option "'+arg+'"')
if option == 'api_base':
if (index+2) >= len(sys.argv):
print_usage('Missing argument for option "'+arg+'"')
options['apiBase'] = sys.argv[index+2]
ignore_next = True
elif option == 'show_headers':
options['showHeaders'] = True
else:
if command is None:
command = arg
if command not in commands:
print_usage('Unknown command "'+arg+'"')
else:
inputs.append(arg)
if command is None:
print_usage('No command specified')
if len(inputs)<1:
options['from_stdin'] = True
inputs = sys.stdin.readlines()
else:
options['from_stdin'] = False
command_info = commands[command]
dstk = DSTK(options)
command_info['handler'](dstk, options, inputs, sys.stdout) |
SwoopSearch/pyaddress | address/address.py | create_cities_csv | python | def create_cities_csv(filename="places2k.txt", output="cities.csv"):
with open(filename, 'r') as city_file:
with open(output, 'w') as out:
for line in city_file:
# Drop Puerto Rico (just looking for the 50 states)
if line[0:2] == "PR":
continue
# Per census.gov, characters 9-72 are the name of the city or place. Cut ,off the last part, which is city, town, etc.
# print " ".join(line[9:72].split()[:-1])
out.write(" ".join(line[9:72].split()[:-1]) + '\n') | Takes the places2k.txt from USPS and creates a simple file of all cities. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L674-L686 | null | # Meant to parse out address lines, minus city,state,zip into a usable dict for address matching
# Ignores periods and commas, because no one cares.
import re
import csv
import os
import dstk
import sys
# Keep lowercase, no periods
# Requires numbers first, then option dash plus numbers.
street_num_regex = r'^(\d+)(-?)(\d*)$'
apartment_regex_number = r'(#?)(\d*)(\w*)'
cwd = os.path.dirname(os.path.realpath(__file__))
class AddressParser(object):
"""
AddressParser will be use to create Address objects. It contains a list of preseeded cities, states, prefixes,
suffixes, and street names that will help the Address object correctly parse the given string. It is loaded
with defaults that work in the average case, but can be adjusted for specific cases.
"""
suffixes = {}
# Lower case list of cities, used as a hint
cities = []
# Lower case list of streets, used as a hint
streets = []
prefixes = {
"n": "N.", "e": "E.", "s": "S.", "w": "W.", "ne": "NE.", "nw": "NW.", 'se': "SE.", 'sw': "SW.", 'north': "N.",
'east': "E.", 'south': "S.",
'west': "W.", 'northeast': "NE.", 'northwest': "NW.", 'southeast': "SE.", 'southwest': "SW."}
states = {
'Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY',
'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA',
'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH',
'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA',
'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO',
'Ohio': 'OH', 'Alabama': 'AL', 'New York': 'NY', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ',
'Washington': 'WA', 'North Carolina': 'NC', 'District of Columbia': 'DC', 'Texas': 'TX', 'Nevada': 'NV',
'Maine': 'ME', 'Rhode Island': 'RI'}
def __init__(self, suffixes=None, cities=None, streets=None, backend="default", dstk_api_base=None, logger=None, required_confidence=0.65):
"""
suffixes, cities and streets provide a chance to use different lists than the provided lists.
suffixes is probably good for most users, unless you have some suffixes not recognized by USPS.
cities is a very expansive list that may lead to false positives in some cases. If you only have a few cities
you know will show up, provide your own list for better accuracy. If you are doing addresses across the US,
the provided list is probably better.
streets can be used to limit the list of possible streets the address are on. It comes blank by default and
uses positional clues instead. If you are instead just doing a couple cities, a list of all possible streets
will decrease incorrect street names.
Valid backends include "default" and "dstk". If backend is dstk, it requires a dstk_api_base. Example of
dstk_api_base would be 'http://example.com'.
"""
self.logger = logger
self.backend = backend
self.dstk_api_base = dstk_api_base
self.required_confidence = required_confidence
if suffixes:
self.suffixes = suffixes
else:
self.load_suffixes(os.path.join(cwd, "suffixes.csv"))
if cities:
self.cities = cities
else:
self.load_cities(os.path.join(cwd, "cities.csv"))
if streets:
self.streets = streets
else:
self.load_streets(os.path.join(cwd, "streets.csv"))
if backend == "dstk":
if dstk_api_base is None:
raise ValueError("dstk_api_base is required for dstk backend.")
self.dstk = dstk.DSTK({'apiBase': dstk_api_base})
elif backend == "default":
pass
else:
raise ValueError("backend must be either 'default' or 'dstk'.")
def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger)
def dstk_multi_address(self, address_list):
if self.backend != "dstk":
raise ValueError("Only allowed for DSTK backends.")
if self.logger: self.logger.debug("Sending {0} possible addresses to DSTK".format(len(address_list)))
multi_address = self.dstk.street2coordinates(address_list)
if self.logger: self.logger.debug("Received {0} addresses from DSTK".format(len(multi_address)))
# if self.logger: self.logger.debug("End street2coords")
addresses = []
# if self.logger: self.logger.debug("Multi Addresses: {0}".format(multi_address))
for address, dstk_return in multi_address.items():
try:
if dstk_return is None:
# if self.logger: self.logger.debug("DSTK None return for: {0}".format(address))
continue
addresses.append(Address(address, self, -1, self.logger, dstk_pre_parse=dstk_return))
if self.logger: self.logger.debug("DSTK Address Appended: {0}".format(dstk_return))
except InvalidAddressException as e:
# if self.logger: self.logger.debug("Error from dstk Address: {0}".format(e.message))
continue
except DSTKConfidenceTooLowException as e:
continue
return addresses
def load_suffixes(self, filename):
"""
Build the suffix dictionary. The keys will be possible long versions, and the values will be the
accepted abbreviations. Everything should be stored using the value version, and you can search all
by using building a set of self.suffixes.keys() and self.suffixes.values().
"""
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines.
self.suffixes[line.strip().split(',')[0]] = line.strip().split(',')[1]
def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower())
def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower())
# Procedure: Go through backwards. First check for apartment number, then
# street suffix, street name, street prefix, then building. For each sub,
# check if that spot is already filled in the dict.
class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
class InvalidAddressException(Exception):
pass
class DSTKConfidenceTooLowException(Exception):
pass
if __name__ == "__main__":
ap = AddressParser()
print ap.parse_address(" ".join(sys.argv[1:]))
|
SwoopSearch/pyaddress | address/address.py | AddressParser.parse_address | python | def parse_address(self, address, line_number=-1):
return Address(address, self, line_number, self.logger) | Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L83-L88 | null | class AddressParser(object):
"""
AddressParser will be use to create Address objects. It contains a list of preseeded cities, states, prefixes,
suffixes, and street names that will help the Address object correctly parse the given string. It is loaded
with defaults that work in the average case, but can be adjusted for specific cases.
"""
suffixes = {}
# Lower case list of cities, used as a hint
cities = []
# Lower case list of streets, used as a hint
streets = []
prefixes = {
"n": "N.", "e": "E.", "s": "S.", "w": "W.", "ne": "NE.", "nw": "NW.", 'se': "SE.", 'sw': "SW.", 'north': "N.",
'east': "E.", 'south': "S.",
'west': "W.", 'northeast': "NE.", 'northwest': "NW.", 'southeast': "SE.", 'southwest': "SW."}
states = {
'Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY',
'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA',
'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH',
'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA',
'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO',
'Ohio': 'OH', 'Alabama': 'AL', 'New York': 'NY', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ',
'Washington': 'WA', 'North Carolina': 'NC', 'District of Columbia': 'DC', 'Texas': 'TX', 'Nevada': 'NV',
'Maine': 'ME', 'Rhode Island': 'RI'}
def __init__(self, suffixes=None, cities=None, streets=None, backend="default", dstk_api_base=None, logger=None, required_confidence=0.65):
"""
suffixes, cities and streets provide a chance to use different lists than the provided lists.
suffixes is probably good for most users, unless you have some suffixes not recognized by USPS.
cities is a very expansive list that may lead to false positives in some cases. If you only have a few cities
you know will show up, provide your own list for better accuracy. If you are doing addresses across the US,
the provided list is probably better.
streets can be used to limit the list of possible streets the address are on. It comes blank by default and
uses positional clues instead. If you are instead just doing a couple cities, a list of all possible streets
will decrease incorrect street names.
Valid backends include "default" and "dstk". If backend is dstk, it requires a dstk_api_base. Example of
dstk_api_base would be 'http://example.com'.
"""
self.logger = logger
self.backend = backend
self.dstk_api_base = dstk_api_base
self.required_confidence = required_confidence
if suffixes:
self.suffixes = suffixes
else:
self.load_suffixes(os.path.join(cwd, "suffixes.csv"))
if cities:
self.cities = cities
else:
self.load_cities(os.path.join(cwd, "cities.csv"))
if streets:
self.streets = streets
else:
self.load_streets(os.path.join(cwd, "streets.csv"))
if backend == "dstk":
if dstk_api_base is None:
raise ValueError("dstk_api_base is required for dstk backend.")
self.dstk = dstk.DSTK({'apiBase': dstk_api_base})
elif backend == "default":
pass
else:
raise ValueError("backend must be either 'default' or 'dstk'.")
def dstk_multi_address(self, address_list):
if self.backend != "dstk":
raise ValueError("Only allowed for DSTK backends.")
if self.logger: self.logger.debug("Sending {0} possible addresses to DSTK".format(len(address_list)))
multi_address = self.dstk.street2coordinates(address_list)
if self.logger: self.logger.debug("Received {0} addresses from DSTK".format(len(multi_address)))
# if self.logger: self.logger.debug("End street2coords")
addresses = []
# if self.logger: self.logger.debug("Multi Addresses: {0}".format(multi_address))
for address, dstk_return in multi_address.items():
try:
if dstk_return is None:
# if self.logger: self.logger.debug("DSTK None return for: {0}".format(address))
continue
addresses.append(Address(address, self, -1, self.logger, dstk_pre_parse=dstk_return))
if self.logger: self.logger.debug("DSTK Address Appended: {0}".format(dstk_return))
except InvalidAddressException as e:
# if self.logger: self.logger.debug("Error from dstk Address: {0}".format(e.message))
continue
except DSTKConfidenceTooLowException as e:
continue
return addresses
def load_suffixes(self, filename):
"""
Build the suffix dictionary. The keys will be possible long versions, and the values will be the
accepted abbreviations. Everything should be stored using the value version, and you can search all
by using building a set of self.suffixes.keys() and self.suffixes.values().
"""
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines.
self.suffixes[line.strip().split(',')[0]] = line.strip().split(',')[1]
def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower())
def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower())
|
SwoopSearch/pyaddress | address/address.py | AddressParser.load_suffixes | python | def load_suffixes(self, filename):
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines.
self.suffixes[line.strip().split(',')[0]] = line.strip().split(',')[1] | Build the suffix dictionary. The keys will be possible long versions, and the values will be the
accepted abbreviations. Everything should be stored using the value version, and you can search all
by using building a set of self.suffixes.keys() and self.suffixes.values(). | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L114-L126 | null | class AddressParser(object):
"""
AddressParser will be use to create Address objects. It contains a list of preseeded cities, states, prefixes,
suffixes, and street names that will help the Address object correctly parse the given string. It is loaded
with defaults that work in the average case, but can be adjusted for specific cases.
"""
suffixes = {}
# Lower case list of cities, used as a hint
cities = []
# Lower case list of streets, used as a hint
streets = []
prefixes = {
"n": "N.", "e": "E.", "s": "S.", "w": "W.", "ne": "NE.", "nw": "NW.", 'se': "SE.", 'sw': "SW.", 'north': "N.",
'east': "E.", 'south': "S.",
'west': "W.", 'northeast': "NE.", 'northwest': "NW.", 'southeast': "SE.", 'southwest': "SW."}
states = {
'Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY',
'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA',
'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH',
'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA',
'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO',
'Ohio': 'OH', 'Alabama': 'AL', 'New York': 'NY', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ',
'Washington': 'WA', 'North Carolina': 'NC', 'District of Columbia': 'DC', 'Texas': 'TX', 'Nevada': 'NV',
'Maine': 'ME', 'Rhode Island': 'RI'}
def __init__(self, suffixes=None, cities=None, streets=None, backend="default", dstk_api_base=None, logger=None, required_confidence=0.65):
"""
suffixes, cities and streets provide a chance to use different lists than the provided lists.
suffixes is probably good for most users, unless you have some suffixes not recognized by USPS.
cities is a very expansive list that may lead to false positives in some cases. If you only have a few cities
you know will show up, provide your own list for better accuracy. If you are doing addresses across the US,
the provided list is probably better.
streets can be used to limit the list of possible streets the address are on. It comes blank by default and
uses positional clues instead. If you are instead just doing a couple cities, a list of all possible streets
will decrease incorrect street names.
Valid backends include "default" and "dstk". If backend is dstk, it requires a dstk_api_base. Example of
dstk_api_base would be 'http://example.com'.
"""
self.logger = logger
self.backend = backend
self.dstk_api_base = dstk_api_base
self.required_confidence = required_confidence
if suffixes:
self.suffixes = suffixes
else:
self.load_suffixes(os.path.join(cwd, "suffixes.csv"))
if cities:
self.cities = cities
else:
self.load_cities(os.path.join(cwd, "cities.csv"))
if streets:
self.streets = streets
else:
self.load_streets(os.path.join(cwd, "streets.csv"))
if backend == "dstk":
if dstk_api_base is None:
raise ValueError("dstk_api_base is required for dstk backend.")
self.dstk = dstk.DSTK({'apiBase': dstk_api_base})
elif backend == "default":
pass
else:
raise ValueError("backend must be either 'default' or 'dstk'.")
def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger)
def dstk_multi_address(self, address_list):
if self.backend != "dstk":
raise ValueError("Only allowed for DSTK backends.")
if self.logger: self.logger.debug("Sending {0} possible addresses to DSTK".format(len(address_list)))
multi_address = self.dstk.street2coordinates(address_list)
if self.logger: self.logger.debug("Received {0} addresses from DSTK".format(len(multi_address)))
# if self.logger: self.logger.debug("End street2coords")
addresses = []
# if self.logger: self.logger.debug("Multi Addresses: {0}".format(multi_address))
for address, dstk_return in multi_address.items():
try:
if dstk_return is None:
# if self.logger: self.logger.debug("DSTK None return for: {0}".format(address))
continue
addresses.append(Address(address, self, -1, self.logger, dstk_pre_parse=dstk_return))
if self.logger: self.logger.debug("DSTK Address Appended: {0}".format(dstk_return))
except InvalidAddressException as e:
# if self.logger: self.logger.debug("Error from dstk Address: {0}".format(e.message))
continue
except DSTKConfidenceTooLowException as e:
continue
return addresses
def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower())
def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower())
|
SwoopSearch/pyaddress | address/address.py | AddressParser.load_cities | python | def load_cities(self, filename):
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower()) | Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L128-L135 | null | class AddressParser(object):
"""
AddressParser will be use to create Address objects. It contains a list of preseeded cities, states, prefixes,
suffixes, and street names that will help the Address object correctly parse the given string. It is loaded
with defaults that work in the average case, but can be adjusted for specific cases.
"""
suffixes = {}
# Lower case list of cities, used as a hint
cities = []
# Lower case list of streets, used as a hint
streets = []
prefixes = {
"n": "N.", "e": "E.", "s": "S.", "w": "W.", "ne": "NE.", "nw": "NW.", 'se': "SE.", 'sw': "SW.", 'north': "N.",
'east': "E.", 'south': "S.",
'west': "W.", 'northeast': "NE.", 'northwest': "NW.", 'southeast': "SE.", 'southwest': "SW."}
states = {
'Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY',
'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA',
'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH',
'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA',
'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO',
'Ohio': 'OH', 'Alabama': 'AL', 'New York': 'NY', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ',
'Washington': 'WA', 'North Carolina': 'NC', 'District of Columbia': 'DC', 'Texas': 'TX', 'Nevada': 'NV',
'Maine': 'ME', 'Rhode Island': 'RI'}
def __init__(self, suffixes=None, cities=None, streets=None, backend="default", dstk_api_base=None, logger=None, required_confidence=0.65):
"""
suffixes, cities and streets provide a chance to use different lists than the provided lists.
suffixes is probably good for most users, unless you have some suffixes not recognized by USPS.
cities is a very expansive list that may lead to false positives in some cases. If you only have a few cities
you know will show up, provide your own list for better accuracy. If you are doing addresses across the US,
the provided list is probably better.
streets can be used to limit the list of possible streets the address are on. It comes blank by default and
uses positional clues instead. If you are instead just doing a couple cities, a list of all possible streets
will decrease incorrect street names.
Valid backends include "default" and "dstk". If backend is dstk, it requires a dstk_api_base. Example of
dstk_api_base would be 'http://example.com'.
"""
self.logger = logger
self.backend = backend
self.dstk_api_base = dstk_api_base
self.required_confidence = required_confidence
if suffixes:
self.suffixes = suffixes
else:
self.load_suffixes(os.path.join(cwd, "suffixes.csv"))
if cities:
self.cities = cities
else:
self.load_cities(os.path.join(cwd, "cities.csv"))
if streets:
self.streets = streets
else:
self.load_streets(os.path.join(cwd, "streets.csv"))
if backend == "dstk":
if dstk_api_base is None:
raise ValueError("dstk_api_base is required for dstk backend.")
self.dstk = dstk.DSTK({'apiBase': dstk_api_base})
elif backend == "default":
pass
else:
raise ValueError("backend must be either 'default' or 'dstk'.")
def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger)
def dstk_multi_address(self, address_list):
if self.backend != "dstk":
raise ValueError("Only allowed for DSTK backends.")
if self.logger: self.logger.debug("Sending {0} possible addresses to DSTK".format(len(address_list)))
multi_address = self.dstk.street2coordinates(address_list)
if self.logger: self.logger.debug("Received {0} addresses from DSTK".format(len(multi_address)))
# if self.logger: self.logger.debug("End street2coords")
addresses = []
# if self.logger: self.logger.debug("Multi Addresses: {0}".format(multi_address))
for address, dstk_return in multi_address.items():
try:
if dstk_return is None:
# if self.logger: self.logger.debug("DSTK None return for: {0}".format(address))
continue
addresses.append(Address(address, self, -1, self.logger, dstk_pre_parse=dstk_return))
if self.logger: self.logger.debug("DSTK Address Appended: {0}".format(dstk_return))
except InvalidAddressException as e:
# if self.logger: self.logger.debug("Error from dstk Address: {0}".format(e.message))
continue
except DSTKConfidenceTooLowException as e:
continue
return addresses
def load_suffixes(self, filename):
"""
Build the suffix dictionary. The keys will be possible long versions, and the values will be the
accepted abbreviations. Everything should be stored using the value version, and you can search all
by using building a set of self.suffixes.keys() and self.suffixes.values().
"""
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines.
self.suffixes[line.strip().split(',')[0]] = line.strip().split(',')[1]
def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower())
|
SwoopSearch/pyaddress | address/address.py | AddressParser.load_streets | python | def load_streets(self, filename):
with open(filename, 'r') as f:
for line in f:
self.streets.append(line.strip().lower()) | Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L137-L144 | null | class AddressParser(object):
"""
AddressParser will be use to create Address objects. It contains a list of preseeded cities, states, prefixes,
suffixes, and street names that will help the Address object correctly parse the given string. It is loaded
with defaults that work in the average case, but can be adjusted for specific cases.
"""
suffixes = {}
# Lower case list of cities, used as a hint
cities = []
# Lower case list of streets, used as a hint
streets = []
prefixes = {
"n": "N.", "e": "E.", "s": "S.", "w": "W.", "ne": "NE.", "nw": "NW.", 'se': "SE.", 'sw': "SW.", 'north': "N.",
'east': "E.", 'south': "S.",
'west': "W.", 'northeast': "NE.", 'northwest': "NW.", 'southeast': "SE.", 'southwest': "SW."}
states = {
'Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY',
'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA',
'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH',
'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA',
'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO',
'Ohio': 'OH', 'Alabama': 'AL', 'New York': 'NY', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ',
'Washington': 'WA', 'North Carolina': 'NC', 'District of Columbia': 'DC', 'Texas': 'TX', 'Nevada': 'NV',
'Maine': 'ME', 'Rhode Island': 'RI'}
def __init__(self, suffixes=None, cities=None, streets=None, backend="default", dstk_api_base=None, logger=None, required_confidence=0.65):
"""
suffixes, cities and streets provide a chance to use different lists than the provided lists.
suffixes is probably good for most users, unless you have some suffixes not recognized by USPS.
cities is a very expansive list that may lead to false positives in some cases. If you only have a few cities
you know will show up, provide your own list for better accuracy. If you are doing addresses across the US,
the provided list is probably better.
streets can be used to limit the list of possible streets the address are on. It comes blank by default and
uses positional clues instead. If you are instead just doing a couple cities, a list of all possible streets
will decrease incorrect street names.
Valid backends include "default" and "dstk". If backend is dstk, it requires a dstk_api_base. Example of
dstk_api_base would be 'http://example.com'.
"""
self.logger = logger
self.backend = backend
self.dstk_api_base = dstk_api_base
self.required_confidence = required_confidence
if suffixes:
self.suffixes = suffixes
else:
self.load_suffixes(os.path.join(cwd, "suffixes.csv"))
if cities:
self.cities = cities
else:
self.load_cities(os.path.join(cwd, "cities.csv"))
if streets:
self.streets = streets
else:
self.load_streets(os.path.join(cwd, "streets.csv"))
if backend == "dstk":
if dstk_api_base is None:
raise ValueError("dstk_api_base is required for dstk backend.")
self.dstk = dstk.DSTK({'apiBase': dstk_api_base})
elif backend == "default":
pass
else:
raise ValueError("backend must be either 'default' or 'dstk'.")
def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger)
def dstk_multi_address(self, address_list):
if self.backend != "dstk":
raise ValueError("Only allowed for DSTK backends.")
if self.logger: self.logger.debug("Sending {0} possible addresses to DSTK".format(len(address_list)))
multi_address = self.dstk.street2coordinates(address_list)
if self.logger: self.logger.debug("Received {0} addresses from DSTK".format(len(multi_address)))
# if self.logger: self.logger.debug("End street2coords")
addresses = []
# if self.logger: self.logger.debug("Multi Addresses: {0}".format(multi_address))
for address, dstk_return in multi_address.items():
try:
if dstk_return is None:
# if self.logger: self.logger.debug("DSTK None return for: {0}".format(address))
continue
addresses.append(Address(address, self, -1, self.logger, dstk_pre_parse=dstk_return))
if self.logger: self.logger.debug("DSTK Address Appended: {0}".format(dstk_return))
except InvalidAddressException as e:
# if self.logger: self.logger.debug("Error from dstk Address: {0}".format(e.message))
continue
except DSTKConfidenceTooLowException as e:
continue
return addresses
def load_suffixes(self, filename):
"""
Build the suffix dictionary. The keys will be possible long versions, and the values will be the
accepted abbreviations. Everything should be stored using the value version, and you can search all
by using building a set of self.suffixes.keys() and self.suffixes.values().
"""
with open(filename, 'r') as f:
for line in f:
# Make sure we have key and value
if len(line.split(',')) != 2:
continue
# Strip off newlines.
self.suffixes[line.strip().split(',')[0]] = line.strip().split(',')[1]
def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
self.cities.append(line.strip().lower())
|
SwoopSearch/pyaddress | address/address.py | Address.preprocess_address | python | def preprocess_address(self, address):
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address | Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L250-L279 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_zip | python | def check_zip(self, token):
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False | Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L281-L295 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_state | python | def check_state(self, token):
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False | Check if state is in either the keys or values of our states list. Must come before the suffix. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L297-L316 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_city | python | def check_city(self, token):
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True | Check if there is a known city from our city list. Must come before the suffix. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L318-L346 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_apartment_number | python | def check_apartment_number(self, token):
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False | Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L348-L375 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_street_suffix | python | def check_street_suffix(self, token):
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False | Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave." | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L377-L393 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_street | python | def check_street(self, token):
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False | Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L395-L413 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_street_prefix | python | def check_street_prefix(self, token):
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False | Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L415-L423 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_house_number | python | def check_house_number(self, token):
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False | Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L425-L437 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.check_building | python | def check_building(self, token):
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False | Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L439-L450 | [
"def _clean(self, item):\n if item is None:\n return None\n else:\n return item.encode(\"utf-8\", \"replace\")\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.guess_unmatched | python | def guess_unmatched(self, token):
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False | When we find something that doesn't match, we can make an educated guess and log it as such. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L452-L477 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.full_address | python | def full_address(self):
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr | Print the address in a human readable format | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L479-L502 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address.dstk_parse | python | def dstk_parse(self, address, parser, pre_parsed_address=None):
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street)) | Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L532-L635 | [
"def _get_dstk_intersections(self, address, dstk_address):\n \"\"\"\n Find the unique tokens in the original address and the returned address.\n \"\"\"\n # Normalize both addresses\n normalized_address = self._normalize(address)\n normalized_dstk_address = self._normalize(dstk_address)\n address_uniques = set(normalized_address) - set(normalized_dstk_address)\n dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)\n if self.logger: self.logger.debug(\"Address Uniques {0}\".format(address_uniques))\n if self.logger: self.logger.debug(\"DSTK Address Uniques {0}\".format(dstk_address_uniques))\n return (len(address_uniques), len(dstk_address_uniques))\n"
] | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address._get_dstk_intersections | python | def _get_dstk_intersections(self, address, dstk_address):
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques)) | Find the unique tokens in the original address and the returned address. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L637-L648 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address
|
SwoopSearch/pyaddress | address/address.py | Address._normalize | python | def _normalize(self, address):
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if token.upper() in self.parser.suffixes.keys():
normalized_address.append(self.parser.suffixes[token.upper()].lower())
elif token.upper() in self.parser.suffixes.values():
normalized_address.append(token.lower())
elif token.upper().replace('.', '') in self.parser.suffixes.values():
normalized_address.append(token.lower().replace('.', ''))
elif token.lower() in self.parser.prefixes.keys():
normalized_address.append(self.parser.prefixes[token.lower()].lower())
elif token.upper() in self.parser.prefixes.values():
normalized_address.append(token.lower()[:-1])
elif token.upper() + '.' in self.parser.prefixes.values():
normalized_address.append(token.lower())
else:
normalized_address.append(token.lower())
return normalized_address | Normalize prefixes, suffixes and other to make matching original to returned easier. | train | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L650-L671 | null | class Address:
unmatched = False
house_number = None
street_prefix = None
street = None
street_suffix = None
apartment = None
# building = None
city = None
state = None
zip = None
original = None
# Only set for dstk
lat = None
lng = None
last_matched = None
unmatched = False
# Only used for debug
line_number = -1
# Confidence value from DSTK. 0 - 1, -1 for not set.
confidence = -1
def __init__(self, address, parser, line_number=-1, logger=None, dstk_pre_parse=None):
"""
@dstk_pre_parse: a single value from a dstk multiple street2coordinates return. @address would be the key then.
"""
self.parser = parser
self.line_number = line_number
self.original = self._clean(address)
self.logger = logger
if address is None:
return
address = self.preprocess_address(address)
if parser.backend == "dstk":
# if self.logger: self.logger.debug("Preparsed: {0}".format(dstk_pre_parse))
self.dstk_parse(address, parser, pre_parsed_address=dstk_pre_parse)
elif parser.backend == "default":
self.parse_address(address)
else:
raise ValueError("Parser gave invalid backend, must be either 'default' or 'dstk'.")
if self.house_number is None or self.house_number <= 0:
raise InvalidAddressException("Addresses must have house numbers.")
elif self.street is None or self.street == "":
raise InvalidAddressException("Addresses must have streets.")
# if self.house_number is None or self.street is None or self.street_suffix is None:
# raise ValueError("Street addresses require house_number, street, and street_suffix")
def parse_address(self, address):
# print "YOU ARE PARSING AN ADDRESS"
# Save the original string
# Get rid of periods and commas, split by spaces, reverse.
# Periods should not exist, remove them. Commas separate tokens. It's possible we can use commas for better guessing.
address = address.strip().replace('.', '')
# We'll use this for guessing.
self.comma_separated_address = address.split(',')
address = address.replace(',', '')
# First, do some preprocessing
# address = self.preprocess_address(address)
# Try all our address regexes. USPS says parse from the back.
address = reversed(address.split())
# Save unmatched to process after the rest is processed.
unmatched = []
# Use for contextual data
for token in address:
# print token, self
# Check zip code first
if self.check_zip(token):
continue
if self.check_state(token):
continue
if self.check_city(token):
continue
if self.check_street_suffix(token):
continue
if self.check_house_number(token):
continue
if self.check_street_prefix(token):
continue
if self.check_street(token):
continue
# if self.check_building(token):
# continue
if self.guess_unmatched(token):
continue
unmatched.append(token)
# Post processing
for token in unmatched:
# print "Unmatched token: ", token
if self.check_apartment_number(token):
continue
# print "Unmatched token: ", token
# print "Original address: ", self.original
self.unmatched = True
def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
address = address.replace(" & ", "&")
# Clear the address of things like 'X units', which shouldn't be in an address anyway. We won't save this for now.
if re.search(r"-?-?\w+ units", address, re.IGNORECASE):
address = re.sub(r"-?-?\w+ units", "", address, flags=re.IGNORECASE)
# Sometimes buildings are put in parantheses.
# building_match = re.search(r"\(.*\)", address, re.IGNORECASE)
# if building_match:
# self.building = self._clean(building_match.group().replace('(', '').replace(')', ''))
# address = re.sub(r"\(.*\)", "", address, flags=re.IGNORECASE)
# Now let's get the apartment stuff out of the way. Using only sure match regexes, delete apartment parts from
# the address. This prevents things like "Unit" being the street name.
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'townhouse style\s\w{1,2}']
for regex in apartment_regexes:
apartment_match = re.search(regex, address, re.IGNORECASE)
if apartment_match:
# print "Matched regex: ", regex, apartment_match.group()
self.apartment = self._clean(apartment_match.group())
address = re.sub(regex, "", address, flags=re.IGNORECASE)
# Now check for things like ", ," which throw off dstk
address = re.sub(r"\,\s*\,", ",", address)
return address
def check_zip(self, token):
"""
Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything
removed during preprocessing such as --2 units.
"""
if self.zip is None:
# print "last matched", self.last_matched
if self.last_matched is not None:
return False
# print "zip check", len(token) == 5, re.match(r"\d{5}", token)
if len(token) == 5 and re.match(r"\d{5}", token):
self.zip = self._clean(token)
return True
return False
def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
if self.state is None and self.street_suffix is None and len(self.comma_separated_address) > 1:
if token.capitalize() in self.parser.states.keys():
self.state = self._clean(self.parser.states[token.capitalize()])
return True
elif token.upper() in self.parser.states.values():
self.state = self._clean(token.upper())
return True
return False
def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Check that we're in the correct location, and that we have at least one comma in the address
if self.city is None and self.apartment is None and self.street_suffix is None and len(
self.comma_separated_address) > 1:
if token.lower() in self.parser.cities:
self.city = self._clean(token.capitalize())
return True
return False
# Multi word cities
if self.city is not None and self.street_suffix is None and self.street is None:
print "Checking for multi part city", token.lower(), token.lower() in shortened_cities.keys()
if token.lower() + ' ' + self.city in self.parser.cities:
self.city = self._clean((token.lower() + ' ' + self.city).capitalize())
return True
if token.lower() in shortened_cities.keys():
token = shortened_cities[token.lower()]
print "Checking for shorted multi part city", token.lower() + ' ' + self.city
if token.lower() + ' ' + self.city.lower() in self.parser.cities:
self.city = self._clean(token.capitalize() + ' ' + self.city.capitalize())
return True
def check_apartment_number(self, token):
"""
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out,
because it has a lot of false positives.
"""
apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt #{0,1}\w+', r'apartment #{0,1}\w+', r'#\w+',
r'# \w+', r'rm \w+', r'unit #?\w+', r'units #?\w+', r'- #{0,1}\w+', r'no\s?\d+\w*',
r'style\s\w{1,2}', r'\d{1,4}/\d{1,4}', r'\d{1,4}', r'\w{1,2}']
for regex in apartment_regexes:
if re.match(regex, token.lower()):
self.apartment = self._clean(token)
return True
# if self.apartment is None and re.match(apartment_regex_number, token.lower()):
## print "Apt regex"
# self.apartment = token
# return True
## If we come on apt or apartment and already have an apartment number, add apt or apartment to the front
if self.apartment and token.lower() in ['apt', 'apartment']:
# print "Apt in a_n"
self.apartment = self._clean(token + ' ' + self.apartment)
return True
if not self.street_suffix and not self.street and not self.apartment:
# print "Searching for unmatched term: ", token, token.lower(),
if re.match(r'\d?\w?', token.lower()):
self.apartment = self._clean(token)
return True
return False
def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffix", self.street_suffix, "street", self.street
if self.street_suffix is None and self.street is None:
# print "upper", token.upper()
if token.upper() in self.parser.suffixes.keys():
suffix = self.parser.suffixes[token.upper()]
self.street_suffix = self._clean(suffix.capitalize() + '.')
return True
elif token.upper() in self.parser.suffixes.values():
self.street_suffix = self._clean(token.capitalize() + '.')
return True
return False
def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets.
"""
# First check for single word streets between a prefix and a suffix
if self.street is None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize())
return True
# Now check for multiple word streets. This check must come after the check for street_prefix and house_number for this reason.
elif self.street is not None and self.street_suffix is not None and self.street_prefix is None and self.house_number is None:
self.street = self._clean(token.capitalize() + ' ' + self.street)
return True
if not self.street_suffix and not self.street and token.lower() in self.parser.streets:
self.street = self._clean(token)
return True
return False
def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():
self.street_prefix = self._clean(self.parser.prefixes[token.lower().replace('.', '')])
return True
return False
def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
if '/' in token:
token = token.split('/')[0]
if '-' in token:
token = token.split('-')[0]
self.house_number = self._clean(str(token))
return True
return False
def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = self._clean(token)
else:
self.building = self._clean(token + ' ' + self.building)
return True
return False
def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likely useless
if token.strip() == '-':
return True
# Almost definitely not a street if it is one or two characters long.
if len(token) <= 2:
return False
# Let's check for a suffix-less street.
if self.street_suffix is None and self.street is None and self.street_prefix is None and self.house_number is None:
# Streets will just be letters
if re.match(r"[A-Za-z]", token):
if self.line_number >= 0:
pass
# print "{0}: Guessing suffix-less street: ".format(self.line_number), token
else:
# print "Guessing suffix-less street: ", token
pass
self.street = self._clean(token.capitalize())
return True
return False
def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
addr = addr + " " + self.street_prefix
if self.street:
addr = addr + " " + self.street
if self.street_suffix:
addr = addr + " " + self.street_suffix
if self.apartment:
addr = addr + " " + self.apartment
if self.city:
addr = addr + ", " + self.city
if self.state:
addr = addr + ", " + self.state
if self.zip:
addr = addr + " " + self.zip
return addr
def _clean(self, item):
if item is None:
return None
else:
return item.encode("utf-8", "replace")
def __repr__(self):
return unicode(self)
def __str__(self):
return unicode(self)
def __unicode__(self):
address_dict = {
"house_number": self.house_number,
"street_prefix": self.street_prefix,
"street": self.street,
"street_suffix": self.street_suffix,
"apartment": self.apartment,
# "building": self.building,
"city": self.city,
"state": self.state,
"zip": self.zip
}
# print "Address Dict", address_dict
return u"Address - House number: {house_number} Prefix: {street_prefix} Street: {street} Suffix: {street_suffix}" \
u" Apartment: {apartment} City,State,Zip: {city}, {state} {zip}".format(**address_dict)
def dstk_parse(self, address, parser, pre_parsed_address=None):
"""
Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.
pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If
pre_parsed_address is None, parse it via dstk on its own.
"""
if pre_parsed_address:
dstk_address = pre_parsed_address
else:
if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii", "ignore")))
dstk_address = parser.dstk.street2coordinates(address)
# if self.logger: self.logger.debug("dstk return: {0}".format(dstk_address))
if 'confidence' not in dstk_address:
raise InvalidAddressException("Could not deal with DSTK return: {0}".format(dstk_address))
if dstk_address['street_address'] == "":
raise InvalidAddressException("Empty street address in DSTK return: {0}".format(dstk_address))
if dstk_address['street_number'] is None or dstk_address['street_name'] is None:
raise InvalidAddressException("House number or street name was Non in DSTK return: {0}".format(dstk_address))
if dstk_address['confidence'] < parser.required_confidence:
raise DSTKConfidenceTooLowException("Required confidence: {0}. Got confidence: {1}. Address: {2}. Return: {3}.".format(parser.required_confidence, dstk_address['confidence'], address.encode("ascii", "ignore"), dstk_address))
self.confidence = dstk_address['confidence']
if 'street_address' in dstk_address:
intersections = self._get_dstk_intersections(address, dstk_address['street_address'])
if self.logger: self.logger.debug("Confidence: {0}.".format(dstk_address['confidence']))
if self.logger: self.logger.debug("Address: {0}.".format(address))
if self.logger: self.logger.debug("Return: {0}.".format(dstk_address))
# if self.logger: self.logger.debug("")
addr = dstk_address
if addr is None:
raise InvalidAddressException("DSTK could not parse address: {0}".format(self.original))
if "street_number" in addr:
if addr["street_number"] not in address:
raise InvalidAddressException("DSTK returned a house number not in the original address: {0}".format(addr))
self.house_number = addr["street_number"]
else:
raise InvalidAddressException("(dstk) Addresses must have house numbers: {0}".format(addr))
if "locality" in addr:
self.city = addr["locality"]
# DSTK shouldn't be returning unknown cities
if addr["locality"] not in address:
raise InvalidAddressException("DSTK returned a city not in the address. City: {0}, Address: {1}.".format(self.city, address))
if "region" in addr:
self.state = addr["region"]
# if "fips_county" in addr:
# self.zip = addr["fips_county"]
if "latitude" in addr:
self.lat = addr["latitude"]
if "longitude" in addr:
self.lng = addr["longitude"]
# Try and find the apartment
# First remove the street_address (this doesn't include apartment)
if "street_address" in addr:
apartment = address.replace(addr["street_address"], '')
# Make sure the city doesn't somehow come before the street in the original string.
# try:
# end_pos = re.search("(" + addr["locality"] + ")", apartment).start(1) - 1
# # self.apartment = apartment[:end_pos]
# except Exception:
# pass
# self.apartment = None
# Now that we have an address, try to parse out street suffix, prefix, and street
if self.apartment:
street_addr = addr["street_address"].replace(self.apartment, '')
else:
street_addr = addr["street_address"]
# We should be left with only prefix, street, suffix. Go for suffix first.
split_addr = street_addr.split()
if len(split_addr) == 0:
if self.logger: self.logger.debug("Could not split street_address: {0}".format(addr))
raise InvalidAddressException("Could not split street_address: {0}".format(addr))
# Get rid of house_number
if split_addr[0] == self.house_number:
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Checking {0} for suffixes".format(split_addr[-1].upper()))
if split_addr[-1].upper() in parser.suffixes.keys() or split_addr[-1].upper() in parser.suffixes.values():
self.street_suffix = split_addr[-1]
split_addr = split_addr[:-1]
if self.logger: self.logger.debug("Checking {0} for prefixes".format(split_addr[0].lower()))
if split_addr[0].lower() in parser.prefixes.keys() or split_addr[0].upper() in parser.prefixes.values() or \
split_addr[0].upper() + '.' in parser.prefixes.values():
if split_addr[0][-1] == '.':
self.street_prefix = split_addr[0].upper()
else:
self.street_prefix = split_addr[0].upper() + '.'
if self.logger: self.logger.debug("Saving prefix: {0}".format(self.street_prefix))
split_addr = split_addr[1:]
if self.logger: self.logger.debug("Saving street: {0}".format(split_addr))
self.street = " ".join(split_addr)
# DSTK shouldn't be guessing cities that come before streets.
match = re.search(self.street, address)
if match is None:
raise InvalidAddressException("DSTK picked a street not in the original address. Street: {0}. Address: {1}.".format(self.street, address))
street_position = match
match = re.search(self.city, address)
if match is None:
raise InvalidAddressException("DSTK picked a city not in the original address. City: {0}. Address: {1}.".format(self.city, address))
city_position = match
if city_position.start(0) < street_position.end(0):
raise InvalidAddressException("DSTK picked a street that comes after the city. Street: {0}. City: {1}. Address: {2}.".format(self.street, self.city, address))
if self.logger: self.logger.debug("Successful DSTK address: {0}, house: {1}, street: {2}\n".format(self.original, self.house_number, self.street))
def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
address_uniques = set(normalized_address) - set(normalized_dstk_address)
dstk_address_uniques = set(normalized_dstk_address) - set(normalized_address)
if self.logger: self.logger.debug("Address Uniques {0}".format(address_uniques))
if self.logger: self.logger.debug("DSTK Address Uniques {0}".format(dstk_address_uniques))
return (len(address_uniques), len(dstk_address_uniques))
|
KxSystems/pyq | setup.py | add_data_file | python | def add_data_file(data_files, target, source):
for t, f in data_files:
if t == target:
break
else:
data_files.append((target, []))
f = data_files[-1][1]
if source not in f:
f.append(source) | Add an entry to data_files | train | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L145-L154 | null | """PyQ - Python for kdb+
|Documentation Status| |PyPI Version|
PyQ_ brings the `Python programming language`_ to the `kdb+ database`_. It
allows developers to seamlessly integrate Python and q codes in one
application. This is achieved by bringing the Python and q interpreters in
the same process so that codes written in either of the languages operate on
the same data. In PyQ, Python and q objects live in the same memory space
and share the same data.
.. |Documentation Status|
image:: https://readthedocs.org/projects/pyq/badge/?version=latest
:target: http://pyq.readthedocs.io/en/latest/?badge=latest
.. |PyPI Version| image:: https://img.shields.io/pypi/v/pyq.svg
:target: https://pypi.python.org/pypi/pyq
.. _PyQ: https://code.kx.com/q/interfaces/pyq/
.. _`Python programming language`: https://www.python.org/about
.. _`kdb+ database`: https://kx.com
"""
import os
import platform
import subprocess
import sys
from distutils.command.build import build
from distutils.command.build_ext import build_ext
from distutils.command.config import config
from distutils.command.install import install
from distutils.command.install_data import install_data
from distutils.command.install_scripts import install_scripts
import sysconfig
WINDOWS = platform.system() == 'Windows'
if WINDOWS:
from setuptools import Command, Distribution, Extension, setup
else:
from distutils.core import Command, Distribution, Extension, setup
VERSION = '4.2.1'
IS_RELEASE = True
VERSION_FILE = 'src/pyq/version.py'
VERSION_PY = """\
# generated by setup.py
version = '{}'
"""
CFLAGS = ['/WX', '/wd4090'] if WINDOWS else ['-fno-strict-aliasing']
if sys.version_info >= (3, ) and not WINDOWS:
CFLAGS.append('-Werror')
LDFLAGS = []
if (sys.maxsize + 1).bit_length() == 32 and platform.machine() == 'x86_64':
# Building 32-bit pyq on a 64-bit host
config_vars = sysconfig.get_config_vars()
CFLAGS.append('-m32')
LDFLAGS.append('-m32')
def split_replace(string, a, b, sep):
x = string.split(sep)
for i, part in enumerate(x):
if part == a:
x[i] = b
return sep.join(x)
for k, v in config_vars.items():
if isinstance(v, str):
config_vars[k] = split_replace(v, 'x86_64', 'i386', '-')
TEST_REQUIREMENTS = [
'pytest>=2.6.4,!=3.2.0,!=3.3.0',
'pytest-pyq',
'pytest-cov>=2.4',
'coverage>=4.2'
] + (['pathlib2>=2.0'] if sys.version_info[0] < 3 else [])
IPYTHON_REQUIREMENTS = ['ipython']
Executable = Extension
METADATA = dict(
name='pyq',
packages=['pyq', 'pyq.tests', ],
package_dir={'': 'src'},
qlib_scripts=['python.q', 'p.k', 'pyq-operators.q', 'pyq-print.q', ],
ext_modules=[
Extension('pyq._k', sources=['src/pyq/_k.c', ],
extra_compile_args=CFLAGS,
extra_link_args=LDFLAGS),
],
qext_modules=[
Extension('pyq', sources=['src/pyq/pyq.c', ],
extra_compile_args=CFLAGS,
extra_link_args=LDFLAGS),
],
executables=[] if WINDOWS else [
Executable('pyq', sources=['src/pyq.c'],
extra_compile_args=CFLAGS,
extra_link_args=LDFLAGS),
],
scripts=['src/scripts/pyq-runtests',
'src/scripts/pyq-coverage',
'src/scripts/ipyq',
'src/scripts/pq',
'src/scripts/qp',
],
data_files=[
('q', ['src/pyq/p.k',
'src/pyq/pyq-operators.q',
'src/pyq/python.q',
]
),
],
url='https://github.com/KxSystems/pyq',
maintainer='PyQ Authors',
maintainer_email='pyq@enlnt.com',
license='Apache License',
platforms=['Linux', 'MacOS X', 'Windows'],
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Financial and Insurance Industry',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows :: Windows 10',
'Programming Language :: C',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Database',
'Topic :: Software Development :: Libraries' +
' :: Python Modules'],
)
def get_version():
write_version_file = True
if IS_RELEASE:
version = VERSION
elif os.path.exists('.git'):
try:
out = subprocess.check_output(['git', 'describe'])
_, commits, revision = decode(out).strip().split('-')
version = '{}.dev{}+{}'.format(VERSION, commits, revision[1:])
except (OSError, ValueError):
version = VERSION + '.dev0+unknown'
else:
try:
f = open(VERSION_FILE)
except OSError:
version = VERSION + '.dev0+unknown'
else:
with f:
g = {}
exec(f.read(), g)
version = g['version']
write_version_file = False
if write_version_file:
with open(VERSION_FILE, 'w') as f:
f.write(VERSION_PY.format(version))
return version
def get_q_home(env):
"""Derive q home from the environment"""
q_home = env.get('QHOME')
if q_home:
return q_home
for v in ['VIRTUAL_ENV', 'HOME']:
prefix = env.get(v)
if prefix:
q_home = os.path.join(prefix, 'q')
if os.path.isdir(q_home):
return q_home
if WINDOWS:
q_home = os.path.join(env['SystemDrive'], r'\q')
if os.path.isdir(q_home):
return q_home
raise RuntimeError('No suitable QHOME.')
def get_q_os_letter(sysname, machine):
if sysname == 'Linux':
return 'l'
if sysname == 'SunOS':
return 'v' if machine == 'i86pc' else 's'
if sysname == 'Darwin':
return 'm'
if sysname == 'Windows':
return 'w'
raise RuntimeError('"Unknown platform: %s %s.' % (sysname, machine))
def get_q_arch(q_home):
bits = (sys.maxsize + 1).bit_length()
sysname = platform.system()
machine = platform.machine()
os_letter = get_q_os_letter(sysname, machine)
if bits == 64:
# In case we're on 64-bit platform, but 64-bit kdb+ is not available
# we will fallback to the 32-bit version.
x64dir = os.path.join(q_home, '%s64' % os_letter)
if not os.path.isdir(x64dir):
bits = 32
return '%s%d' % (os_letter, bits)
def get_q_version(q_home):
"""Return version of q installed at q_home"""
with open(os.path.join(q_home, 'q.k')) as f:
for line in f:
if line.startswith('k:'):
return line[2:5]
return '2.2'
decode = (lambda x: x) if str is bytes else lambda x: x.decode()
def get_python_dll(executable):
sysname = platform.system()
if sysname.startswith(('Linux', 'SunOS')):
output = subprocess.check_output(['ldd', executable])
for line in output.splitlines():
if b'libpython' in line:
return decode(line.split()[2])
# This is for systems which have statically linked Python
# (i.e Ubuntu), but provide dynamic libraries in a separate
# package.
libpython = 'libpython{}.{}'.format(*sys.version_info[:2]).encode()
try:
output = subprocess.check_output(['ldconfig', '-p'])
except subprocess.CalledProcessError:
output = subprocess.check_output(['/sbin/ldconfig', '-p'])
for line in output.splitlines():
if libpython in line:
return decode(line.split()[-1])
elif sysname == 'Darwin':
output = subprocess.check_output(['otool', '-L', executable])
for line in output.splitlines()[1:]:
if b'Python' in line:
python_dll = decode(line.split()[0])
return python_dll.replace('@executable_path',
os.path.dirname(executable))
elif sysname == 'Windows':
return 'python{}{}.dll'.format(*sys.version_info[:2])
# This is known to work for Anaconda
ldlibrary = sysconfig.get_config_var('LDLIBRARY')
libdir = sysconfig.get_config_var('LIBDIR')
if ldlibrary and libdir:
libfile = os.path.join(libdir, ldlibrary)
if os.path.exists(libfile):
return libfile
raise RuntimeError('no python dll')
SETUP_CFG = """\
[config]
q_home = {q_home}
q_version = {q_version}
q_arch = {q_arch}
python_dll = {python_dll}
"""
class Config(config):
user_options = [
('q-home=', None, 'q home directory'),
('q-version=', None, 'q version'),
('q-arch=', None, 'q architecture, e.g. l64'),
('python-dll=', None, 'path to the python dynamic library'),
('dest=', None, "path to the config file (default: setup.cfg)"),
('write', None, 'write the config file')
]
q_home = None
q_arch = None
q_version = None
python_dll = None
dest = None
write = None
extra_link_args = []
def initialize_options(self):
config.initialize_options(self)
def finalize_options(self):
if self.q_home is None:
self.q_home = get_q_home(os.environ)
if self.q_arch is None:
self.q_arch = get_q_arch(self.q_home)
if self.q_version is None:
self.q_version = get_q_version(self.q_home)
if self.python_dll is None:
self.python_dll = get_python_dll(sys.executable)
if self.dest is None:
self.dest = 'setup.cfg'
if WINDOWS:
self.extra_link_args = [r'src\pyq\kx\%s\q.lib' % self.q_arch]
def run(self):
setup_cfg = SETUP_CFG.format(**vars(self))
self.announce(setup_cfg.rstrip(), 2)
if self.write:
with open(self.dest, 'w') as f:
f.write(setup_cfg)
self.announce('^^^ Written to %s.' % self.dest, 2)
else:
self.announce('^^^ Use --write options'
' to write this to %s.' % self.dest, 2)
PYQ_CONFIG = """\
\\d .pyq
python_dll:"{python_dll}\\000"
pyq_executable:"{pyq_executable}"
"""
class BuildQLib(Command):
description = "build q/k scripts"
user_options = [
('build-lib=', 'd', "build directory"),
('force', 'f', "forcibly build everything (ignore file timestamps)"),
]
q_home = None
build_base = None
build_lib = None
python_dll = None
pyq_executable = None
def initialize_options(self):
pass
def finalize_options(self):
self.set_undefined_options('config',
('q_home', 'q_home'),
('python_dll', 'python_dll'))
self.set_undefined_options('build',
('build_base', 'build_base'))
self.build_lib = os.path.join(self.build_base, 'qlib')
cmd = self.get_finalized_command('install_exe')
pyq_path = os.path.join(cmd.install_dir, 'pyq')
self.pyq_executable = pyq_path.replace('\\', '\\\\')
def run(self):
self.mkpath(self.build_lib)
for script in self.distribution.qlib_scripts:
outfile = os.path.join(self.build_lib, script)
script_file = os.path.join('src', 'pyq', script)
self.write_pyq_config()
self.copy_file(script_file, outfile, preserve_mode=0)
def write_pyq_config(self):
pyq_config_file = os.path.join(self.build_lib, 'pyq-config.q')
with open(pyq_config_file, 'w') as f:
f.write(PYQ_CONFIG.format(**vars(self)))
add_data_file(self.distribution.data_files, 'q', pyq_config_file)
class BuildQExt(Command):
description = "build q extension modules"
user_options = [
('build-lib=', 'd', "build directory"),
('force', 'f', "forcibly build everything (ignore file timestamps)"),
]
q_home = None
q_arch = None
q_version = None
build_base = None
build_temp = None
build_lib = None
compiler = None
define = None
debug = None
force = None
plat_name = None
extensions = None
def initialize_options(self):
pass
def finalize_options(self):
self.set_undefined_options('config',
('q_home', 'q_home'),
('q_arch', 'q_arch'),
('q_version', 'q_version'))
self.set_undefined_options('build',
('build_base', 'build_base'),
('compiler', 'compiler'),
('debug', 'debug'),
('force', 'force'),
('plat_name', 'plat_name'))
if self.build_lib is None:
self.build_lib = os.path.join(self.build_base,
'qext.' + self.plat_name)
if self.build_temp is None:
self.build_temp = os.path.join(self.build_base,
'temp.' + self.plat_name)
if self.extensions is None:
self.extensions = self.distribution.qext_modules
if self.define is None:
split_version = self.q_version.split('.')
self.define = [('KXVER', split_version[0]),
('KXVER2', split_version[1]), ]
def run(self):
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
include_dirs = ['src/pyq/kx', ]
conf = self.get_finalized_command("config")
for ext in self.extensions:
sources = ext.sources
ext_path = os.path.join(self.build_lib,
ext.name + ('.dll' if WINDOWS else '.so'))
compiler = new_compiler(compiler=self.compiler,
verbose=self.verbose,
dry_run=self.dry_run,
force=self.force)
customize_compiler(compiler)
define = self.define[:]
if sys.version_info >= (3,):
py3k = '{:d}{:d}'.format(*sys.version_info[:2])
define.append(('PY3K', py3k))
if WINDOWS:
compiler.initialize()
compiler.compile_options.remove('/MD')
extra_args = ext.extra_compile_args or []
objects = compiler.compile(sources,
output_dir=self.build_temp,
macros=define,
extra_postargs=extra_args,
include_dirs=include_dirs)
extra_args = conf.extra_link_args[:] + ext.extra_link_args
if WINDOWS:
extra_args.extend([r'/DEF:src\pyq\%s.def' % ext.name])
compiler.link_shared_object(objects, ext_path,
extra_postargs=extra_args)
add_data_file(self.distribution.data_files,
os.path.join('q', self.q_arch), ext_path)
class BuildPyExt(build_ext):
q_arch = None
def finalize_options(self):
build_ext.finalize_options(self)
self.set_undefined_options('build_qext',
('define', 'define'))
self.set_undefined_options('config',
('q_arch', 'q_arch'))
conf = self.get_finalized_command("config")
if conf.extra_link_args:
for ext in self.extensions:
ext.extra_link_args = [a.format(**vars(ext))
for a in conf.extra_link_args]
if WINDOWS:
def build_extensions(self):
self.compiler.initialize()
self.compiler.compile_options.remove('/MD')
build_ext.build_extensions(self)
class BuildExe(Command):
description = "build executables"
user_options = []
q_home = None
q_arch = None
q_version = None
build_temp = None
build_exe = None
build_base = None
compiler = None
debug = None
define = None
plat_name = None
def initialize_options(self):
pass
def finalize_options(self):
self.set_undefined_options('config',
('q_home', 'q_home'),
('q_arch', 'q_arch'),
('q_version', 'q_version'))
self.set_undefined_options('build',
('build_base', 'build_base'),
('compiler', 'compiler'),
('debug', 'debug'),
('force', 'force'),
('plat_name', 'plat_name'))
if self.build_exe is None:
self.build_exe = os.path.join(self.build_base,
'exe.{}-{}'.format(self.plat_name,
sys.version[:3]))
if self.define is None:
self.define = [
('KXVER', self.q_version[0]),
('QARCH', self.q_arch),
]
def run(self):
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
for exe in self.distribution.executables:
compiler = new_compiler(
compiler=self.compiler,
verbose=self.verbose,
dry_run=self.dry_run,
force=self.force)
customize_compiler(compiler)
extra_args = exe.extra_compile_args or []
objects = compiler.compile(exe.sources,
macros=self.define,
extra_postargs=extra_args,
output_dir=self.build_temp)
compiler.link_executable(objects,
extra_preargs=LDFLAGS,
output_progname=exe.name,
output_dir=self.build_exe)
class InstallQLib(install_data):
description = "install q/k scripts"
build_dir = None
skip_build = None
outfiles = None
def finalize_options(self):
self.set_undefined_options('config', ('q_home', 'install_dir'))
self.set_undefined_options('build_qlib', ('build_lib', 'build_dir'))
self.set_undefined_options('install', ('skip_build', 'skip_build'))
def run(self):
if not self.skip_build:
self.run_command('build_qlib')
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
class InstallQExt(install_data):
description = "install q/k scripts"
q_home = None
q_arch = None
build_dir = None
skip_build = None
install_dir = None
outfiles = None
def finalize_options(self):
self.set_undefined_options('config',
('q_home', 'q_home'),
('q_arch', 'q_arch'))
self.set_undefined_options('build_qext', ('build_lib', 'build_dir'))
self.set_undefined_options('install', ('skip_build', 'skip_build'))
self.install_dir = os.path.join(self.q_home, self.q_arch)
def run(self):
if not self.skip_build:
self.run_command('build_qext')
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
class InstallExe(install_scripts):
description = "install executables"
outfiles = None
def finalize_options(self):
self.set_undefined_options('build_exe', ('build_exe', 'build_dir'))
self.set_undefined_options('install',
('install_scripts', 'install_dir'),
('force', 'force'),
('skip_build', 'skip_build'),
)
def run(self):
if not self.skip_build:
self.run_command('build_exe')
from stat import ST_MODE
if not self.get_inputs():
return
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
if os.name == 'posix':
# Set the executable bits (owner, group, and world) on
# all the executables we just installed.
for file in self.get_outputs():
if self.dry_run:
self.announce("changing mode of %s" % file, 2)
else:
mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
self.announce("changing mode of %s to %o" %
(file, mode), 2)
os.chmod(file, mode)
def get_inputs(self):
return self.distribution.executables or []
class PyqDistribution(Distribution):
qlib_scripts = None
qext_modules = None
executables = None
build.sub_commands.extend([
('build_qlib', None),
('build_qext', None),
('build_exe', None),
])
install.sub_commands.extend([
('install_qlib', None),
('install_qext', None),
('install_exe', None),
])
def run_setup(metadata):
summary, details = __doc__.split('\n\n', 1)
rst_description = '\n'.join([summary, '=' * len(summary), '\n' + details])
keywords = metadata.copy()
keywords.update(
version=get_version(),
description=summary,
long_description=rst_description,
distclass=PyqDistribution,
cmdclass={
'config': Config,
'build_qlib': BuildQLib,
'build_qext': BuildQExt,
'build_ext': BuildPyExt,
'build_exe': BuildExe,
'install_qlib': InstallQLib,
'install_qext': InstallQExt,
'install_exe': InstallExe,
},
)
if 'setuptools' in sys.modules:
keywords['extras_require'] = {
'test': TEST_REQUIREMENTS,
'ipython': IPYTHON_REQUIREMENTS,
'all': TEST_REQUIREMENTS + IPYTHON_REQUIREMENTS + [
'py', 'numpy', 'prompt-toolkit', 'pygments-q'],
}
if (sys.version_info >= (3,) and not WINDOWS and
'CONDA_PREFIX' not in os.environ and
os.path.exists('embedPy/p.q')):
try:
import numpy
except ImportError:
pass
else:
add_embedpy_components(keywords)
setup(**keywords)
def add_embedpy_components(keywords):
keywords['qlib_scripts'].append('../../embedPy/p.q')
keywords['qext_modules'].append(
Extension('p', sources=['embedPy/py.c', ]),
)
add_data_file(keywords['data_files'], 'q', 'embedPy/p.q')
if __name__ == '__main__':
run_setup(METADATA)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.