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
klen/python-scss
scss/function.py
_hue
python
def _hue(color, **kwargs): h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0)
Get hue value of HSL color.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/function.py#L133-L137
null
from __future__ import print_function import base64 import colorsys import math import mimetypes import os.path import sys from .compat import PY3 try: from itertools import product except ImportError: def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) from . import OPRT, CONV_TYPE, ELEMENTS_OF_TYPE from .value import ( NumberValue, StringValue, QuotedStringValue, ColorValue, BooleanValue, hsl_op, rgba_op) try: from PIL import Image except ImportError: Image = None IMAGES = dict() def warn(warning): """ Write warning messages in stderr. """ print("\nWarning: %s" % str(warning), file=sys.stderr) def unknown(*args, **kwargs): """ Unknow scss function handler. Simple return 'funcname(args)' """ name = kwargs.get('name', '') return "%s(%s)" % (name, ', '.join(str(a) for a in args)) def check_pil(func): """ PIL module checking decorator. """ def __wrapper(*args, **kwargs): root = kwargs.get('root') if not Image: if root and root.get_opt('warn'): warn("Images manipulation require PIL") return 'none' return func(*args, **kwargs) return __wrapper # RGB functions # ============= def _rgb(r, g, b, **kwargs): """ Converts an rgb(red, green, blue) triplet into a color. """ return _rgba(r, g, b, 1.0) def _rgba(r, g, b, a, **kwargs): """ Converts an rgba(red, green, blue, alpha) quadruplet into a color. """ return ColorValue((float(r), float(g), float(b), float(a))) def _red(color, **kwargs): """ Gets the red component of a color. """ return NumberValue(color.value[0]) def _green(color, **kwargs): """ Gets the green component of a color. """ return NumberValue(color.value[1]) def _blue(color, **kwargs): """ Gets the blue component of a color. """ return NumberValue(color.value[2]) def _mix(color1, color2, weight=0.5, **kwargs): """ Mixes two colors together. """ weight = float(weight) c1 = color1.value c2 = color2.value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1[3] - c2[3] w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0 w2 = 1 - w1 q = [w1, w1, w1, p] r = [w2, w2, w2, 1 - p] return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) # HSL functions # ============= def _hsl(h, s, l, **kwargs): """ HSL color value. """ return _hsla(h, s, l, 1.0) def _hsla(h, s, l, a, **kwargs): """ HSL with alpha channel color value. """ res = colorsys.hls_to_rgb(float(h), float(l), float(s)) return ColorValue([x * 255.0 for x in res] + [float(a)]) def _lightness(color, **kwargs): """ Get lightness value of HSL color. """ l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1] return NumberValue((l * 100, '%')) def _saturation(color, **kwargs): """ Get saturation value of HSL color. """ s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2] return NumberValue((s * 100, '%')) def _adjust_hue(color, degrees, **kwargs): return hsl_op(OPRT['+'], color, degrees, 0, 0) def _lighten(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _darken(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, 0, amount) def _saturate(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _desaturate(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, amount, 0) def _grayscale(color, **kwargs): return hsl_op(OPRT['-'], color, 0, 100, 0) def _complement(color, **kwargs): return hsl_op(OPRT['+'], color, 180.0, 0, 0) # Opacity functions # ================= def _alpha(color, **kwargs): c = ColorValue(color).value return NumberValue(c[3]) def _opacify(color, amount, **kwargs): return rgba_op(OPRT['+'], color, 0, 0, 0, amount) def _transparentize(color, amount, **kwargs): return rgba_op(OPRT['-'], color, 0, 0, 0, amount) # String functions # ================= def _unquote(*args, **kwargs): return StringValue(' '.join(str(s).strip("\"'") for s in args)) def _quote(*args, **kwargs): return QuotedStringValue(' '.join(str(s) for s in args)) # Number functions # ================= def _percentage(value, **kwargs): value = NumberValue(value) if not value.units == '%': value.value *= 100 value.units = '%' return value def _abs(value, **kwargs): return abs(float(value)) def _pi(**kwargs): return NumberValue(math.pi) def _sin(value, **kwargs): return math.sin(value) def _cos(value, **kwargs): return math.cos(value) def _tan(value, **kwargs): return math.tan(value) def _round(value, **kwargs): return float(round(value)) def _ceil(value, **kwargs): return float(math.ceil(value)) def _floor(value, **kwargs): return float(math.floor(value)) # Introspection functions # ======================= def _type_of(obj, **kwargs): if isinstance(obj, BooleanValue): return StringValue('bool') if isinstance(obj, NumberValue): return StringValue('number') if isinstance(obj, QuotedStringValue): return StringValue('string') if isinstance(obj, ColorValue): return StringValue('color') if isinstance(obj, dict): return StringValue('list') return 'unknown' def _unit(value, **kwargs): return NumberValue(value).units def _unitless(value, **kwargs): if NumberValue(value).units: return BooleanValue(False) return BooleanValue(True) def _comparable(n1, n2, **kwargs): n1, n2 = NumberValue(n1), NumberValue(n2) type1 = CONV_TYPE.get(n1.units) type2 = CONV_TYPE.get(n2.units) return BooleanValue(type1 == type2) # Color functions # ================ def _adjust_color( color, saturation=0.0, lightness=0.0, red=0.0, green=0.0, blue=0.0, alpha=0.0, **kwargs): return __asc_color( OPRT['+'], color, saturation, lightness, red, green, blue, alpha) def _scale_color( color, saturation=1.0, lightness=1.0, red=1.0, green=1.0, blue=1.0, alpha=1.0, **kwargs): return __asc_color( OPRT['*'], color, saturation, lightness, red, green, blue, alpha) def _change_color( color, saturation=None, lightness=None, red=None, green=None, blue=None, alpha=None, **kwargs): return __asc_color( None, color, saturation, lightness, red, green, blue, alpha) def _invert(color, **kwargs): """ Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone. """ col = ColorValue(color) args = [ 255.0 - col.value[0], 255.0 - col.value[1], 255.0 - col.value[2], col.value[3], ] inverted = ColorValue(args) return inverted def _adjust_lightness(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _adjust_saturation(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _scale_lightness(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, 0, amount) def _scale_saturation(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, amount, 0) # Compass helpers # ================ def _color_stops(*args, **kwargs): raise NotImplementedError def _elements_of_type(display, **kwargs): return StringValue(ELEMENTS_OF_TYPE.get(StringValue(display).value, '')) def _enumerate(s, b, e, **kwargs): return ', '.join( "%s%d" % (StringValue(s).value, x) for x in range(int(b.value), int(e.value + 1))) def _font_files(*args, **kwargs): raise NotImplementedError def _headings(a=None, b=None, **kwargs): h = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] if not a or StringValue(a).value == 'all': a, b = 1, 6 elif b is None: b, a = a.value + 1, 1 return ', '.join(h[int(float(a) - 1):int(float(b))]) def _nest(*args, **kwargs): return ', '.join( ' '.join(s.strip() for s in p) if '&' not in p[1] else p[1].replace('&', p[0].strip()) for p in product( *(StringValue(sel).value.split(',') for sel in args) ) ) @check_pil def _image_width(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[0], 'px']) @check_pil def _image_height(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[1], 'px']) def _image_url(image, **kwargs): return QuotedStringValue(image).value def _inline_image(image, mimetype=None, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) if os.path.exists(path): mimetype = StringValue(mimetype).value or mimetypes.guess_type(path)[0] f = open(path, 'rb') if PY3: data = base64.b64encode(f.read()).decode('utf-8') else: data = base64.b64encode(f.read()) url = 'data:' + mimetype + ';base64,' + data else: if root and root.get_opt('warn'): warn("Not found image: %s" % path) url = '%s?_=NA' % QuotedStringValue(image).value inline = 'url("%s")' % url return StringValue(inline) # Misc # ==== def _if(cond, body, els, **kwargs): if BooleanValue(cond).value: return body return els def _sprite_position(*args): pass def _sprite_file(*args): pass def _sprite(*args): pass def _sprite_map(*args): pass def _sprite_map_name(*args): pass def _sprite_url(*args): pass def _opposite_position(*args): pass def _grad_point(*args): pass def _grad_color_stops(*args): pass def _nth(*args): pass def _join(*args): pass def _append(*args): pass FUNCTION_LIST = { # RGB functions 'rgb:3': _rgb, 'rgba:4': _rgba, 'red:1': _red, 'green:1': _green, 'blue:1': _blue, 'mix:2': _mix, 'mix:3': _mix, # HSL functions 'hsl:3': _hsl, 'hsla:4': _hsla, 'hue:1': _hue, 'saturation:1': _saturation, 'lightness:1': _lightness, 'adjust-hue:2': _adjust_hue, 'spin:2': _adjust_hue, 'lighten:2': _lighten, 'darken:2': _darken, 'saturate:2': _saturate, 'desaturate:2': _desaturate, 'grayscale:1': _grayscale, 'complement:1': _complement, # Opacity functions 'alpha:1': _alpha, 'opacity:1': _alpha, 'opacify:2': _opacify, 'fadein:2': _opacify, 'fade-in:2': _opacify, 'transparentize:2': _transparentize, 'fadeout:2': _transparentize, 'fade-out:2': _transparentize, # String functions 'quote:n': _quote, 'unquote:n': _unquote, # Number functions 'percentage:1': _percentage, 'sin:1': _sin, 'cos:1': _cos, 'tan:1': _tan, 'abs:1': _abs, 'round:1': _round, 'ceil:1': _ceil, 'floor:1': _floor, 'pi:0': _pi, # Introspection functions 'type-of:1': _type_of, 'unit:1': _unit, 'unitless:1': _unitless, 'comparable:2': _comparable, # Color functions 'adjust-color:n': _adjust_color, 'scale-color:n': _scale_color, 'change-color:n': _change_color, 'adjust-lightness:2': _adjust_lightness, 'adjust-saturation:2': _adjust_saturation, 'scale-lightness:2': _scale_lightness, 'scale-saturation:2': _scale_saturation, 'invert:1': _invert, # Compass helpers 'append-selector:2': _nest, 'color-stops:n': _color_stops, 'enumerate:3': _enumerate, 'elements-of-type:1': _elements_of_type, 'font-files:n': _font_files, 'headings:n': _headings, 'nest:n': _nest, # Images functions 'image-url:1': _image_url, 'image-width:1': _image_width, 'image-height:1': _image_height, 'inline-image:1': _inline_image, 'inline-image:2': _inline_image, # Not implemented 'sprite-map:1': _sprite_map, 'sprite:2': _sprite, 'sprite:3': _sprite, 'sprite:4': _sprite, 'sprite-map-name:1': _sprite_map_name, 'sprite-file:2': _sprite_file, 'sprite-url:1': _sprite_url, 'sprite-position:2': _sprite_position, 'sprite-position:3': _sprite_position, 'sprite-position:4': _sprite_position, 'opposite-position:n': _opposite_position, 'grad-point:n': _grad_point, 'grad-color-stops:n': _grad_color_stops, 'nth:2': _nth, 'first-value-of:1': _nth, 'join:2': _join, 'join:3': _join, 'append:2': _append, 'append:3': _append, 'if:3': _if, 'escape:1': _unquote, 'e:1': _unquote, } def __asc_color(op, color, saturation, lightness, red, green, blue, alpha): if lightness or saturation: color = hsl_op(op, color, 0, saturation, lightness) if red or green or blue or alpha: color = rgba_op(op, color, red, green, blue, alpha) return color def __get_size(path, **kwargs): root = kwargs.get('root') if path not in IMAGES: if not os.path.exists(path): if root and root.get_opt('warn'): warn("Not found image: %s" % path) return 0, 0 image = Image.open(path) IMAGES[path] = image.size return IMAGES[path] # pylama:ignore=F0401,D
klen/python-scss
scss/function.py
_lightness
python
def _lightness(color, **kwargs): l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1] return NumberValue((l * 100, '%'))
Get lightness value of HSL color.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/function.py#L140-L144
null
from __future__ import print_function import base64 import colorsys import math import mimetypes import os.path import sys from .compat import PY3 try: from itertools import product except ImportError: def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) from . import OPRT, CONV_TYPE, ELEMENTS_OF_TYPE from .value import ( NumberValue, StringValue, QuotedStringValue, ColorValue, BooleanValue, hsl_op, rgba_op) try: from PIL import Image except ImportError: Image = None IMAGES = dict() def warn(warning): """ Write warning messages in stderr. """ print("\nWarning: %s" % str(warning), file=sys.stderr) def unknown(*args, **kwargs): """ Unknow scss function handler. Simple return 'funcname(args)' """ name = kwargs.get('name', '') return "%s(%s)" % (name, ', '.join(str(a) for a in args)) def check_pil(func): """ PIL module checking decorator. """ def __wrapper(*args, **kwargs): root = kwargs.get('root') if not Image: if root and root.get_opt('warn'): warn("Images manipulation require PIL") return 'none' return func(*args, **kwargs) return __wrapper # RGB functions # ============= def _rgb(r, g, b, **kwargs): """ Converts an rgb(red, green, blue) triplet into a color. """ return _rgba(r, g, b, 1.0) def _rgba(r, g, b, a, **kwargs): """ Converts an rgba(red, green, blue, alpha) quadruplet into a color. """ return ColorValue((float(r), float(g), float(b), float(a))) def _red(color, **kwargs): """ Gets the red component of a color. """ return NumberValue(color.value[0]) def _green(color, **kwargs): """ Gets the green component of a color. """ return NumberValue(color.value[1]) def _blue(color, **kwargs): """ Gets the blue component of a color. """ return NumberValue(color.value[2]) def _mix(color1, color2, weight=0.5, **kwargs): """ Mixes two colors together. """ weight = float(weight) c1 = color1.value c2 = color2.value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1[3] - c2[3] w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0 w2 = 1 - w1 q = [w1, w1, w1, p] r = [w2, w2, w2, 1 - p] return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) # HSL functions # ============= def _hsl(h, s, l, **kwargs): """ HSL color value. """ return _hsla(h, s, l, 1.0) def _hsla(h, s, l, a, **kwargs): """ HSL with alpha channel color value. """ res = colorsys.hls_to_rgb(float(h), float(l), float(s)) return ColorValue([x * 255.0 for x in res] + [float(a)]) def _hue(color, **kwargs): """ Get hue value of HSL color. """ h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0) def _saturation(color, **kwargs): """ Get saturation value of HSL color. """ s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2] return NumberValue((s * 100, '%')) def _adjust_hue(color, degrees, **kwargs): return hsl_op(OPRT['+'], color, degrees, 0, 0) def _lighten(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _darken(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, 0, amount) def _saturate(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _desaturate(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, amount, 0) def _grayscale(color, **kwargs): return hsl_op(OPRT['-'], color, 0, 100, 0) def _complement(color, **kwargs): return hsl_op(OPRT['+'], color, 180.0, 0, 0) # Opacity functions # ================= def _alpha(color, **kwargs): c = ColorValue(color).value return NumberValue(c[3]) def _opacify(color, amount, **kwargs): return rgba_op(OPRT['+'], color, 0, 0, 0, amount) def _transparentize(color, amount, **kwargs): return rgba_op(OPRT['-'], color, 0, 0, 0, amount) # String functions # ================= def _unquote(*args, **kwargs): return StringValue(' '.join(str(s).strip("\"'") for s in args)) def _quote(*args, **kwargs): return QuotedStringValue(' '.join(str(s) for s in args)) # Number functions # ================= def _percentage(value, **kwargs): value = NumberValue(value) if not value.units == '%': value.value *= 100 value.units = '%' return value def _abs(value, **kwargs): return abs(float(value)) def _pi(**kwargs): return NumberValue(math.pi) def _sin(value, **kwargs): return math.sin(value) def _cos(value, **kwargs): return math.cos(value) def _tan(value, **kwargs): return math.tan(value) def _round(value, **kwargs): return float(round(value)) def _ceil(value, **kwargs): return float(math.ceil(value)) def _floor(value, **kwargs): return float(math.floor(value)) # Introspection functions # ======================= def _type_of(obj, **kwargs): if isinstance(obj, BooleanValue): return StringValue('bool') if isinstance(obj, NumberValue): return StringValue('number') if isinstance(obj, QuotedStringValue): return StringValue('string') if isinstance(obj, ColorValue): return StringValue('color') if isinstance(obj, dict): return StringValue('list') return 'unknown' def _unit(value, **kwargs): return NumberValue(value).units def _unitless(value, **kwargs): if NumberValue(value).units: return BooleanValue(False) return BooleanValue(True) def _comparable(n1, n2, **kwargs): n1, n2 = NumberValue(n1), NumberValue(n2) type1 = CONV_TYPE.get(n1.units) type2 = CONV_TYPE.get(n2.units) return BooleanValue(type1 == type2) # Color functions # ================ def _adjust_color( color, saturation=0.0, lightness=0.0, red=0.0, green=0.0, blue=0.0, alpha=0.0, **kwargs): return __asc_color( OPRT['+'], color, saturation, lightness, red, green, blue, alpha) def _scale_color( color, saturation=1.0, lightness=1.0, red=1.0, green=1.0, blue=1.0, alpha=1.0, **kwargs): return __asc_color( OPRT['*'], color, saturation, lightness, red, green, blue, alpha) def _change_color( color, saturation=None, lightness=None, red=None, green=None, blue=None, alpha=None, **kwargs): return __asc_color( None, color, saturation, lightness, red, green, blue, alpha) def _invert(color, **kwargs): """ Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone. """ col = ColorValue(color) args = [ 255.0 - col.value[0], 255.0 - col.value[1], 255.0 - col.value[2], col.value[3], ] inverted = ColorValue(args) return inverted def _adjust_lightness(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _adjust_saturation(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _scale_lightness(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, 0, amount) def _scale_saturation(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, amount, 0) # Compass helpers # ================ def _color_stops(*args, **kwargs): raise NotImplementedError def _elements_of_type(display, **kwargs): return StringValue(ELEMENTS_OF_TYPE.get(StringValue(display).value, '')) def _enumerate(s, b, e, **kwargs): return ', '.join( "%s%d" % (StringValue(s).value, x) for x in range(int(b.value), int(e.value + 1))) def _font_files(*args, **kwargs): raise NotImplementedError def _headings(a=None, b=None, **kwargs): h = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] if not a or StringValue(a).value == 'all': a, b = 1, 6 elif b is None: b, a = a.value + 1, 1 return ', '.join(h[int(float(a) - 1):int(float(b))]) def _nest(*args, **kwargs): return ', '.join( ' '.join(s.strip() for s in p) if '&' not in p[1] else p[1].replace('&', p[0].strip()) for p in product( *(StringValue(sel).value.split(',') for sel in args) ) ) @check_pil def _image_width(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[0], 'px']) @check_pil def _image_height(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[1], 'px']) def _image_url(image, **kwargs): return QuotedStringValue(image).value def _inline_image(image, mimetype=None, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) if os.path.exists(path): mimetype = StringValue(mimetype).value or mimetypes.guess_type(path)[0] f = open(path, 'rb') if PY3: data = base64.b64encode(f.read()).decode('utf-8') else: data = base64.b64encode(f.read()) url = 'data:' + mimetype + ';base64,' + data else: if root and root.get_opt('warn'): warn("Not found image: %s" % path) url = '%s?_=NA' % QuotedStringValue(image).value inline = 'url("%s")' % url return StringValue(inline) # Misc # ==== def _if(cond, body, els, **kwargs): if BooleanValue(cond).value: return body return els def _sprite_position(*args): pass def _sprite_file(*args): pass def _sprite(*args): pass def _sprite_map(*args): pass def _sprite_map_name(*args): pass def _sprite_url(*args): pass def _opposite_position(*args): pass def _grad_point(*args): pass def _grad_color_stops(*args): pass def _nth(*args): pass def _join(*args): pass def _append(*args): pass FUNCTION_LIST = { # RGB functions 'rgb:3': _rgb, 'rgba:4': _rgba, 'red:1': _red, 'green:1': _green, 'blue:1': _blue, 'mix:2': _mix, 'mix:3': _mix, # HSL functions 'hsl:3': _hsl, 'hsla:4': _hsla, 'hue:1': _hue, 'saturation:1': _saturation, 'lightness:1': _lightness, 'adjust-hue:2': _adjust_hue, 'spin:2': _adjust_hue, 'lighten:2': _lighten, 'darken:2': _darken, 'saturate:2': _saturate, 'desaturate:2': _desaturate, 'grayscale:1': _grayscale, 'complement:1': _complement, # Opacity functions 'alpha:1': _alpha, 'opacity:1': _alpha, 'opacify:2': _opacify, 'fadein:2': _opacify, 'fade-in:2': _opacify, 'transparentize:2': _transparentize, 'fadeout:2': _transparentize, 'fade-out:2': _transparentize, # String functions 'quote:n': _quote, 'unquote:n': _unquote, # Number functions 'percentage:1': _percentage, 'sin:1': _sin, 'cos:1': _cos, 'tan:1': _tan, 'abs:1': _abs, 'round:1': _round, 'ceil:1': _ceil, 'floor:1': _floor, 'pi:0': _pi, # Introspection functions 'type-of:1': _type_of, 'unit:1': _unit, 'unitless:1': _unitless, 'comparable:2': _comparable, # Color functions 'adjust-color:n': _adjust_color, 'scale-color:n': _scale_color, 'change-color:n': _change_color, 'adjust-lightness:2': _adjust_lightness, 'adjust-saturation:2': _adjust_saturation, 'scale-lightness:2': _scale_lightness, 'scale-saturation:2': _scale_saturation, 'invert:1': _invert, # Compass helpers 'append-selector:2': _nest, 'color-stops:n': _color_stops, 'enumerate:3': _enumerate, 'elements-of-type:1': _elements_of_type, 'font-files:n': _font_files, 'headings:n': _headings, 'nest:n': _nest, # Images functions 'image-url:1': _image_url, 'image-width:1': _image_width, 'image-height:1': _image_height, 'inline-image:1': _inline_image, 'inline-image:2': _inline_image, # Not implemented 'sprite-map:1': _sprite_map, 'sprite:2': _sprite, 'sprite:3': _sprite, 'sprite:4': _sprite, 'sprite-map-name:1': _sprite_map_name, 'sprite-file:2': _sprite_file, 'sprite-url:1': _sprite_url, 'sprite-position:2': _sprite_position, 'sprite-position:3': _sprite_position, 'sprite-position:4': _sprite_position, 'opposite-position:n': _opposite_position, 'grad-point:n': _grad_point, 'grad-color-stops:n': _grad_color_stops, 'nth:2': _nth, 'first-value-of:1': _nth, 'join:2': _join, 'join:3': _join, 'append:2': _append, 'append:3': _append, 'if:3': _if, 'escape:1': _unquote, 'e:1': _unquote, } def __asc_color(op, color, saturation, lightness, red, green, blue, alpha): if lightness or saturation: color = hsl_op(op, color, 0, saturation, lightness) if red or green or blue or alpha: color = rgba_op(op, color, red, green, blue, alpha) return color def __get_size(path, **kwargs): root = kwargs.get('root') if path not in IMAGES: if not os.path.exists(path): if root and root.get_opt('warn'): warn("Not found image: %s" % path) return 0, 0 image = Image.open(path) IMAGES[path] = image.size return IMAGES[path] # pylama:ignore=F0401,D
klen/python-scss
scss/function.py
_saturation
python
def _saturation(color, **kwargs): s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2] return NumberValue((s * 100, '%'))
Get saturation value of HSL color.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/function.py#L147-L151
null
from __future__ import print_function import base64 import colorsys import math import mimetypes import os.path import sys from .compat import PY3 try: from itertools import product except ImportError: def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) from . import OPRT, CONV_TYPE, ELEMENTS_OF_TYPE from .value import ( NumberValue, StringValue, QuotedStringValue, ColorValue, BooleanValue, hsl_op, rgba_op) try: from PIL import Image except ImportError: Image = None IMAGES = dict() def warn(warning): """ Write warning messages in stderr. """ print("\nWarning: %s" % str(warning), file=sys.stderr) def unknown(*args, **kwargs): """ Unknow scss function handler. Simple return 'funcname(args)' """ name = kwargs.get('name', '') return "%s(%s)" % (name, ', '.join(str(a) for a in args)) def check_pil(func): """ PIL module checking decorator. """ def __wrapper(*args, **kwargs): root = kwargs.get('root') if not Image: if root and root.get_opt('warn'): warn("Images manipulation require PIL") return 'none' return func(*args, **kwargs) return __wrapper # RGB functions # ============= def _rgb(r, g, b, **kwargs): """ Converts an rgb(red, green, blue) triplet into a color. """ return _rgba(r, g, b, 1.0) def _rgba(r, g, b, a, **kwargs): """ Converts an rgba(red, green, blue, alpha) quadruplet into a color. """ return ColorValue((float(r), float(g), float(b), float(a))) def _red(color, **kwargs): """ Gets the red component of a color. """ return NumberValue(color.value[0]) def _green(color, **kwargs): """ Gets the green component of a color. """ return NumberValue(color.value[1]) def _blue(color, **kwargs): """ Gets the blue component of a color. """ return NumberValue(color.value[2]) def _mix(color1, color2, weight=0.5, **kwargs): """ Mixes two colors together. """ weight = float(weight) c1 = color1.value c2 = color2.value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1[3] - c2[3] w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0 w2 = 1 - w1 q = [w1, w1, w1, p] r = [w2, w2, w2, 1 - p] return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) # HSL functions # ============= def _hsl(h, s, l, **kwargs): """ HSL color value. """ return _hsla(h, s, l, 1.0) def _hsla(h, s, l, a, **kwargs): """ HSL with alpha channel color value. """ res = colorsys.hls_to_rgb(float(h), float(l), float(s)) return ColorValue([x * 255.0 for x in res] + [float(a)]) def _hue(color, **kwargs): """ Get hue value of HSL color. """ h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0) def _lightness(color, **kwargs): """ Get lightness value of HSL color. """ l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1] return NumberValue((l * 100, '%')) def _adjust_hue(color, degrees, **kwargs): return hsl_op(OPRT['+'], color, degrees, 0, 0) def _lighten(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _darken(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, 0, amount) def _saturate(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _desaturate(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, amount, 0) def _grayscale(color, **kwargs): return hsl_op(OPRT['-'], color, 0, 100, 0) def _complement(color, **kwargs): return hsl_op(OPRT['+'], color, 180.0, 0, 0) # Opacity functions # ================= def _alpha(color, **kwargs): c = ColorValue(color).value return NumberValue(c[3]) def _opacify(color, amount, **kwargs): return rgba_op(OPRT['+'], color, 0, 0, 0, amount) def _transparentize(color, amount, **kwargs): return rgba_op(OPRT['-'], color, 0, 0, 0, amount) # String functions # ================= def _unquote(*args, **kwargs): return StringValue(' '.join(str(s).strip("\"'") for s in args)) def _quote(*args, **kwargs): return QuotedStringValue(' '.join(str(s) for s in args)) # Number functions # ================= def _percentage(value, **kwargs): value = NumberValue(value) if not value.units == '%': value.value *= 100 value.units = '%' return value def _abs(value, **kwargs): return abs(float(value)) def _pi(**kwargs): return NumberValue(math.pi) def _sin(value, **kwargs): return math.sin(value) def _cos(value, **kwargs): return math.cos(value) def _tan(value, **kwargs): return math.tan(value) def _round(value, **kwargs): return float(round(value)) def _ceil(value, **kwargs): return float(math.ceil(value)) def _floor(value, **kwargs): return float(math.floor(value)) # Introspection functions # ======================= def _type_of(obj, **kwargs): if isinstance(obj, BooleanValue): return StringValue('bool') if isinstance(obj, NumberValue): return StringValue('number') if isinstance(obj, QuotedStringValue): return StringValue('string') if isinstance(obj, ColorValue): return StringValue('color') if isinstance(obj, dict): return StringValue('list') return 'unknown' def _unit(value, **kwargs): return NumberValue(value).units def _unitless(value, **kwargs): if NumberValue(value).units: return BooleanValue(False) return BooleanValue(True) def _comparable(n1, n2, **kwargs): n1, n2 = NumberValue(n1), NumberValue(n2) type1 = CONV_TYPE.get(n1.units) type2 = CONV_TYPE.get(n2.units) return BooleanValue(type1 == type2) # Color functions # ================ def _adjust_color( color, saturation=0.0, lightness=0.0, red=0.0, green=0.0, blue=0.0, alpha=0.0, **kwargs): return __asc_color( OPRT['+'], color, saturation, lightness, red, green, blue, alpha) def _scale_color( color, saturation=1.0, lightness=1.0, red=1.0, green=1.0, blue=1.0, alpha=1.0, **kwargs): return __asc_color( OPRT['*'], color, saturation, lightness, red, green, blue, alpha) def _change_color( color, saturation=None, lightness=None, red=None, green=None, blue=None, alpha=None, **kwargs): return __asc_color( None, color, saturation, lightness, red, green, blue, alpha) def _invert(color, **kwargs): """ Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone. """ col = ColorValue(color) args = [ 255.0 - col.value[0], 255.0 - col.value[1], 255.0 - col.value[2], col.value[3], ] inverted = ColorValue(args) return inverted def _adjust_lightness(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _adjust_saturation(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _scale_lightness(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, 0, amount) def _scale_saturation(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, amount, 0) # Compass helpers # ================ def _color_stops(*args, **kwargs): raise NotImplementedError def _elements_of_type(display, **kwargs): return StringValue(ELEMENTS_OF_TYPE.get(StringValue(display).value, '')) def _enumerate(s, b, e, **kwargs): return ', '.join( "%s%d" % (StringValue(s).value, x) for x in range(int(b.value), int(e.value + 1))) def _font_files(*args, **kwargs): raise NotImplementedError def _headings(a=None, b=None, **kwargs): h = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] if not a or StringValue(a).value == 'all': a, b = 1, 6 elif b is None: b, a = a.value + 1, 1 return ', '.join(h[int(float(a) - 1):int(float(b))]) def _nest(*args, **kwargs): return ', '.join( ' '.join(s.strip() for s in p) if '&' not in p[1] else p[1].replace('&', p[0].strip()) for p in product( *(StringValue(sel).value.split(',') for sel in args) ) ) @check_pil def _image_width(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[0], 'px']) @check_pil def _image_height(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[1], 'px']) def _image_url(image, **kwargs): return QuotedStringValue(image).value def _inline_image(image, mimetype=None, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) if os.path.exists(path): mimetype = StringValue(mimetype).value or mimetypes.guess_type(path)[0] f = open(path, 'rb') if PY3: data = base64.b64encode(f.read()).decode('utf-8') else: data = base64.b64encode(f.read()) url = 'data:' + mimetype + ';base64,' + data else: if root and root.get_opt('warn'): warn("Not found image: %s" % path) url = '%s?_=NA' % QuotedStringValue(image).value inline = 'url("%s")' % url return StringValue(inline) # Misc # ==== def _if(cond, body, els, **kwargs): if BooleanValue(cond).value: return body return els def _sprite_position(*args): pass def _sprite_file(*args): pass def _sprite(*args): pass def _sprite_map(*args): pass def _sprite_map_name(*args): pass def _sprite_url(*args): pass def _opposite_position(*args): pass def _grad_point(*args): pass def _grad_color_stops(*args): pass def _nth(*args): pass def _join(*args): pass def _append(*args): pass FUNCTION_LIST = { # RGB functions 'rgb:3': _rgb, 'rgba:4': _rgba, 'red:1': _red, 'green:1': _green, 'blue:1': _blue, 'mix:2': _mix, 'mix:3': _mix, # HSL functions 'hsl:3': _hsl, 'hsla:4': _hsla, 'hue:1': _hue, 'saturation:1': _saturation, 'lightness:1': _lightness, 'adjust-hue:2': _adjust_hue, 'spin:2': _adjust_hue, 'lighten:2': _lighten, 'darken:2': _darken, 'saturate:2': _saturate, 'desaturate:2': _desaturate, 'grayscale:1': _grayscale, 'complement:1': _complement, # Opacity functions 'alpha:1': _alpha, 'opacity:1': _alpha, 'opacify:2': _opacify, 'fadein:2': _opacify, 'fade-in:2': _opacify, 'transparentize:2': _transparentize, 'fadeout:2': _transparentize, 'fade-out:2': _transparentize, # String functions 'quote:n': _quote, 'unquote:n': _unquote, # Number functions 'percentage:1': _percentage, 'sin:1': _sin, 'cos:1': _cos, 'tan:1': _tan, 'abs:1': _abs, 'round:1': _round, 'ceil:1': _ceil, 'floor:1': _floor, 'pi:0': _pi, # Introspection functions 'type-of:1': _type_of, 'unit:1': _unit, 'unitless:1': _unitless, 'comparable:2': _comparable, # Color functions 'adjust-color:n': _adjust_color, 'scale-color:n': _scale_color, 'change-color:n': _change_color, 'adjust-lightness:2': _adjust_lightness, 'adjust-saturation:2': _adjust_saturation, 'scale-lightness:2': _scale_lightness, 'scale-saturation:2': _scale_saturation, 'invert:1': _invert, # Compass helpers 'append-selector:2': _nest, 'color-stops:n': _color_stops, 'enumerate:3': _enumerate, 'elements-of-type:1': _elements_of_type, 'font-files:n': _font_files, 'headings:n': _headings, 'nest:n': _nest, # Images functions 'image-url:1': _image_url, 'image-width:1': _image_width, 'image-height:1': _image_height, 'inline-image:1': _inline_image, 'inline-image:2': _inline_image, # Not implemented 'sprite-map:1': _sprite_map, 'sprite:2': _sprite, 'sprite:3': _sprite, 'sprite:4': _sprite, 'sprite-map-name:1': _sprite_map_name, 'sprite-file:2': _sprite_file, 'sprite-url:1': _sprite_url, 'sprite-position:2': _sprite_position, 'sprite-position:3': _sprite_position, 'sprite-position:4': _sprite_position, 'opposite-position:n': _opposite_position, 'grad-point:n': _grad_point, 'grad-color-stops:n': _grad_color_stops, 'nth:2': _nth, 'first-value-of:1': _nth, 'join:2': _join, 'join:3': _join, 'append:2': _append, 'append:3': _append, 'if:3': _if, 'escape:1': _unquote, 'e:1': _unquote, } def __asc_color(op, color, saturation, lightness, red, green, blue, alpha): if lightness or saturation: color = hsl_op(op, color, 0, saturation, lightness) if red or green or blue or alpha: color = rgba_op(op, color, red, green, blue, alpha) return color def __get_size(path, **kwargs): root = kwargs.get('root') if path not in IMAGES: if not os.path.exists(path): if root and root.get_opt('warn'): warn("Not found image: %s" % path) return 0, 0 image = Image.open(path) IMAGES[path] = image.size return IMAGES[path] # pylama:ignore=F0401,D
klen/python-scss
scss/function.py
_invert
python
def _invert(color, **kwargs): col = ColorValue(color) args = [ 255.0 - col.value[0], 255.0 - col.value[1], 255.0 - col.value[2], col.value[3], ] inverted = ColorValue(args) return inverted
Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/function.py#L349-L361
null
from __future__ import print_function import base64 import colorsys import math import mimetypes import os.path import sys from .compat import PY3 try: from itertools import product except ImportError: def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) from . import OPRT, CONV_TYPE, ELEMENTS_OF_TYPE from .value import ( NumberValue, StringValue, QuotedStringValue, ColorValue, BooleanValue, hsl_op, rgba_op) try: from PIL import Image except ImportError: Image = None IMAGES = dict() def warn(warning): """ Write warning messages in stderr. """ print("\nWarning: %s" % str(warning), file=sys.stderr) def unknown(*args, **kwargs): """ Unknow scss function handler. Simple return 'funcname(args)' """ name = kwargs.get('name', '') return "%s(%s)" % (name, ', '.join(str(a) for a in args)) def check_pil(func): """ PIL module checking decorator. """ def __wrapper(*args, **kwargs): root = kwargs.get('root') if not Image: if root and root.get_opt('warn'): warn("Images manipulation require PIL") return 'none' return func(*args, **kwargs) return __wrapper # RGB functions # ============= def _rgb(r, g, b, **kwargs): """ Converts an rgb(red, green, blue) triplet into a color. """ return _rgba(r, g, b, 1.0) def _rgba(r, g, b, a, **kwargs): """ Converts an rgba(red, green, blue, alpha) quadruplet into a color. """ return ColorValue((float(r), float(g), float(b), float(a))) def _red(color, **kwargs): """ Gets the red component of a color. """ return NumberValue(color.value[0]) def _green(color, **kwargs): """ Gets the green component of a color. """ return NumberValue(color.value[1]) def _blue(color, **kwargs): """ Gets the blue component of a color. """ return NumberValue(color.value[2]) def _mix(color1, color2, weight=0.5, **kwargs): """ Mixes two colors together. """ weight = float(weight) c1 = color1.value c2 = color2.value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1[3] - c2[3] w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0 w2 = 1 - w1 q = [w1, w1, w1, p] r = [w2, w2, w2, 1 - p] return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) # HSL functions # ============= def _hsl(h, s, l, **kwargs): """ HSL color value. """ return _hsla(h, s, l, 1.0) def _hsla(h, s, l, a, **kwargs): """ HSL with alpha channel color value. """ res = colorsys.hls_to_rgb(float(h), float(l), float(s)) return ColorValue([x * 255.0 for x in res] + [float(a)]) def _hue(color, **kwargs): """ Get hue value of HSL color. """ h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0) def _lightness(color, **kwargs): """ Get lightness value of HSL color. """ l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1] return NumberValue((l * 100, '%')) def _saturation(color, **kwargs): """ Get saturation value of HSL color. """ s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2] return NumberValue((s * 100, '%')) def _adjust_hue(color, degrees, **kwargs): return hsl_op(OPRT['+'], color, degrees, 0, 0) def _lighten(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _darken(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, 0, amount) def _saturate(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _desaturate(color, amount, **kwargs): return hsl_op(OPRT['-'], color, 0, amount, 0) def _grayscale(color, **kwargs): return hsl_op(OPRT['-'], color, 0, 100, 0) def _complement(color, **kwargs): return hsl_op(OPRT['+'], color, 180.0, 0, 0) # Opacity functions # ================= def _alpha(color, **kwargs): c = ColorValue(color).value return NumberValue(c[3]) def _opacify(color, amount, **kwargs): return rgba_op(OPRT['+'], color, 0, 0, 0, amount) def _transparentize(color, amount, **kwargs): return rgba_op(OPRT['-'], color, 0, 0, 0, amount) # String functions # ================= def _unquote(*args, **kwargs): return StringValue(' '.join(str(s).strip("\"'") for s in args)) def _quote(*args, **kwargs): return QuotedStringValue(' '.join(str(s) for s in args)) # Number functions # ================= def _percentage(value, **kwargs): value = NumberValue(value) if not value.units == '%': value.value *= 100 value.units = '%' return value def _abs(value, **kwargs): return abs(float(value)) def _pi(**kwargs): return NumberValue(math.pi) def _sin(value, **kwargs): return math.sin(value) def _cos(value, **kwargs): return math.cos(value) def _tan(value, **kwargs): return math.tan(value) def _round(value, **kwargs): return float(round(value)) def _ceil(value, **kwargs): return float(math.ceil(value)) def _floor(value, **kwargs): return float(math.floor(value)) # Introspection functions # ======================= def _type_of(obj, **kwargs): if isinstance(obj, BooleanValue): return StringValue('bool') if isinstance(obj, NumberValue): return StringValue('number') if isinstance(obj, QuotedStringValue): return StringValue('string') if isinstance(obj, ColorValue): return StringValue('color') if isinstance(obj, dict): return StringValue('list') return 'unknown' def _unit(value, **kwargs): return NumberValue(value).units def _unitless(value, **kwargs): if NumberValue(value).units: return BooleanValue(False) return BooleanValue(True) def _comparable(n1, n2, **kwargs): n1, n2 = NumberValue(n1), NumberValue(n2) type1 = CONV_TYPE.get(n1.units) type2 = CONV_TYPE.get(n2.units) return BooleanValue(type1 == type2) # Color functions # ================ def _adjust_color( color, saturation=0.0, lightness=0.0, red=0.0, green=0.0, blue=0.0, alpha=0.0, **kwargs): return __asc_color( OPRT['+'], color, saturation, lightness, red, green, blue, alpha) def _scale_color( color, saturation=1.0, lightness=1.0, red=1.0, green=1.0, blue=1.0, alpha=1.0, **kwargs): return __asc_color( OPRT['*'], color, saturation, lightness, red, green, blue, alpha) def _change_color( color, saturation=None, lightness=None, red=None, green=None, blue=None, alpha=None, **kwargs): return __asc_color( None, color, saturation, lightness, red, green, blue, alpha) def _adjust_lightness(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, 0, amount) def _adjust_saturation(color, amount, **kwargs): return hsl_op(OPRT['+'], color, 0, amount, 0) def _scale_lightness(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, 0, amount) def _scale_saturation(color, amount, **kwargs): return hsl_op(OPRT['*'], color, 0, amount, 0) # Compass helpers # ================ def _color_stops(*args, **kwargs): raise NotImplementedError def _elements_of_type(display, **kwargs): return StringValue(ELEMENTS_OF_TYPE.get(StringValue(display).value, '')) def _enumerate(s, b, e, **kwargs): return ', '.join( "%s%d" % (StringValue(s).value, x) for x in range(int(b.value), int(e.value + 1))) def _font_files(*args, **kwargs): raise NotImplementedError def _headings(a=None, b=None, **kwargs): h = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] if not a or StringValue(a).value == 'all': a, b = 1, 6 elif b is None: b, a = a.value + 1, 1 return ', '.join(h[int(float(a) - 1):int(float(b))]) def _nest(*args, **kwargs): return ', '.join( ' '.join(s.strip() for s in p) if '&' not in p[1] else p[1].replace('&', p[0].strip()) for p in product( *(StringValue(sel).value.split(',') for sel in args) ) ) @check_pil def _image_width(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[0], 'px']) @check_pil def _image_height(image, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) size = __get_size(path, root=root) return NumberValue([size[1], 'px']) def _image_url(image, **kwargs): return QuotedStringValue(image).value def _inline_image(image, mimetype=None, **kwargs): root = kwargs.get('root') path = os.path.abspath( os.path.join( root.get_opt('path'), StringValue(image).value)) if os.path.exists(path): mimetype = StringValue(mimetype).value or mimetypes.guess_type(path)[0] f = open(path, 'rb') if PY3: data = base64.b64encode(f.read()).decode('utf-8') else: data = base64.b64encode(f.read()) url = 'data:' + mimetype + ';base64,' + data else: if root and root.get_opt('warn'): warn("Not found image: %s" % path) url = '%s?_=NA' % QuotedStringValue(image).value inline = 'url("%s")' % url return StringValue(inline) # Misc # ==== def _if(cond, body, els, **kwargs): if BooleanValue(cond).value: return body return els def _sprite_position(*args): pass def _sprite_file(*args): pass def _sprite(*args): pass def _sprite_map(*args): pass def _sprite_map_name(*args): pass def _sprite_url(*args): pass def _opposite_position(*args): pass def _grad_point(*args): pass def _grad_color_stops(*args): pass def _nth(*args): pass def _join(*args): pass def _append(*args): pass FUNCTION_LIST = { # RGB functions 'rgb:3': _rgb, 'rgba:4': _rgba, 'red:1': _red, 'green:1': _green, 'blue:1': _blue, 'mix:2': _mix, 'mix:3': _mix, # HSL functions 'hsl:3': _hsl, 'hsla:4': _hsla, 'hue:1': _hue, 'saturation:1': _saturation, 'lightness:1': _lightness, 'adjust-hue:2': _adjust_hue, 'spin:2': _adjust_hue, 'lighten:2': _lighten, 'darken:2': _darken, 'saturate:2': _saturate, 'desaturate:2': _desaturate, 'grayscale:1': _grayscale, 'complement:1': _complement, # Opacity functions 'alpha:1': _alpha, 'opacity:1': _alpha, 'opacify:2': _opacify, 'fadein:2': _opacify, 'fade-in:2': _opacify, 'transparentize:2': _transparentize, 'fadeout:2': _transparentize, 'fade-out:2': _transparentize, # String functions 'quote:n': _quote, 'unquote:n': _unquote, # Number functions 'percentage:1': _percentage, 'sin:1': _sin, 'cos:1': _cos, 'tan:1': _tan, 'abs:1': _abs, 'round:1': _round, 'ceil:1': _ceil, 'floor:1': _floor, 'pi:0': _pi, # Introspection functions 'type-of:1': _type_of, 'unit:1': _unit, 'unitless:1': _unitless, 'comparable:2': _comparable, # Color functions 'adjust-color:n': _adjust_color, 'scale-color:n': _scale_color, 'change-color:n': _change_color, 'adjust-lightness:2': _adjust_lightness, 'adjust-saturation:2': _adjust_saturation, 'scale-lightness:2': _scale_lightness, 'scale-saturation:2': _scale_saturation, 'invert:1': _invert, # Compass helpers 'append-selector:2': _nest, 'color-stops:n': _color_stops, 'enumerate:3': _enumerate, 'elements-of-type:1': _elements_of_type, 'font-files:n': _font_files, 'headings:n': _headings, 'nest:n': _nest, # Images functions 'image-url:1': _image_url, 'image-width:1': _image_width, 'image-height:1': _image_height, 'inline-image:1': _inline_image, 'inline-image:2': _inline_image, # Not implemented 'sprite-map:1': _sprite_map, 'sprite:2': _sprite, 'sprite:3': _sprite, 'sprite:4': _sprite, 'sprite-map-name:1': _sprite_map_name, 'sprite-file:2': _sprite_file, 'sprite-url:1': _sprite_url, 'sprite-position:2': _sprite_position, 'sprite-position:3': _sprite_position, 'sprite-position:4': _sprite_position, 'opposite-position:n': _opposite_position, 'grad-point:n': _grad_point, 'grad-color-stops:n': _grad_color_stops, 'nth:2': _nth, 'first-value-of:1': _nth, 'join:2': _join, 'join:3': _join, 'append:2': _append, 'append:3': _append, 'if:3': _if, 'escape:1': _unquote, 'e:1': _unquote, } def __asc_color(op, color, saturation, lightness, red, green, blue, alpha): if lightness or saturation: color = hsl_op(op, color, 0, saturation, lightness) if red or green or blue or alpha: color = rgba_op(op, color, red, green, blue, alpha) return color def __get_size(path, **kwargs): root = kwargs.get('root') if path not in IMAGES: if not os.path.exists(path): if root and root.get_opt('warn'): warn("Not found image: %s" % path) return 0, 0 image = Image.open(path) IMAGES[path] = image.size return IMAGES[path] # pylama:ignore=F0401,D
klen/python-scss
scss/parser.py
load
python
def load(path, cache=None, precache=False): parser = Stylesheet(cache) return parser.load(path, precache=precache)
Parse from file.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L392-L396
[ "def load(self, f, precache=None):\n \"\"\" Compile scss from file.\n File is string path of file object.\n \"\"\"\n precache = precache or self.get_opt('cache') or False\n nodes = None\n if isinstance(f, file_):\n path = os.path.abspath(f.name)\n\n else:\n path = os.path.abspath(f)\n f = open(f)\n\n cache_path = os.path.splitext(path)[0] + '.ccss'\n\n if precache and os.path.exists(cache_path):\n ptime = os.path.getmtime(cache_path)\n ttime = os.path.getmtime(path)\n if ptime > ttime:\n dump = open(cache_path, 'rb').read()\n nodes = pickle.loads(dump)\n\n if not nodes:\n src = f.read()\n nodes = self.scan(src.strip())\n\n if precache:\n f = open(cache_path, 'wb')\n pickle.dump(nodes, f, protocol=1)\n\n self.parse(nodes)\n return ''.join(map(str, nodes))\n" ]
from __future__ import print_function import os.path import sys from collections import defaultdict from pyparsing import ParseBaseException from . import SORTING from .base import Node, Empty, ParseNode, ContentNode, IncludeNode from .compat import pickle, bytes_, unicode_, file_ from .control import ( Variable, Expression, Function, Mixin, Include, MixinParam, Extend, Variables, Option, FunctionDefinition, FunctionReturn, If, For, SepValString) from .function import warn, _nest from .grammar import * from .value import NumberValue, StringValue, ColorValue, QuotedStringValue, PointValue class Comment(Node): """ Comment node. """ delim = '' def __str__(self): """ Clean comments if option `comments` disabled or enabled option `compress` """ if self.root.get_opt('comments') and not self.root.get_opt('compress'): return super(Comment, self).__str__() return '' class Warn(Empty): """ Warning node @warn. """ def parse(self, target): """ Write message to stderr. """ if self.root.get_opt('warn'): warn(self.data[1]) class Import(Node): """ Import node @import. """ def __str__(self): """ Write @import to outstring. """ return "%s;\n" % super(Import, self).__str__() class Ruleset(ContentNode): """ Rule node. """ def parse(self, target): """ Parse nested rulesets and save it in cache. """ if isinstance(target, ContentNode): if target.name: self.parent = target self.name.parse(self) self.name += target.name target.ruleset.append(self) self.root.cache['rset'][str(self.name).split()[0]].add(self) super(Ruleset, self).parse(target) class Declaration(ParseNode): """ Declaration node. """ def __init__(self, s, n, t): """ Add self.name and self.expr to object. """ super(Declaration, self).__init__(s, n, t) self.name = self.expr = '' def parse(self, target): """ Parse nested declaration. """ if not isinstance(target, Node): parent = ContentNode(None, None, []) parent.parse(target) target = parent super(Declaration, self).parse(target) self.name = str(self.data[0]) while isinstance(target, Declaration): self.name = '-'.join((str(target.data[0]), self.name)) target = target.parent self.expr = ' '.join(str (n) for n in self.data [2:] if not isinstance(n, Declaration)) if self.expr: target.declareset.append(self) def __str__(self): """ Warning on unknown declaration and write current in outstring. """ name = self.name.strip('*_#') if name.startswith('-moz-'): name = name[5:] elif name.startswith('-webkit-'): name = name[8:] elif name.startswith('-o-'): name = name[3:] elif name.startswith('-ms-'): name = name[4:] if name not in SORTING and self.root.get_opt('warn'): warn("Unknown declaration: %s" % self.name) return (":%s" % self.root.cache['delims'][1]).join( (self.name, self.expr)) class DeclarationName(ParseNode): """ Name of declaration node. For spliting it in one string. """ delim = '' class SelectorTree(ParseNode): """ Tree of selectors in ruleset. """ delim = ', ' def extend(self, target): """ @extend selectors tree. """ self_test = ', '.join(map(str, self.data)) target_test = ', '.join(map(str, target.data)) self.data = ( self_test + ', ' + self_test.replace(str(self.data[0].data[0]), target_test)).split(', ') def __add__(self, target): """ Add selectors from parent nodes. """ if isinstance(target, SelectorTree): self_test = ', '.join(map(str, self.data)) target_test = ', '.join(map(str, target.data)) self.data = _nest(target_test, self_test).split(', ') return self class Selector(ParseNode): """ Simple selector node. """ delim = '' def __str__(self): """ Write to output. """ return ''.join(StringValue(n).value for n in self.data) class VarDefinition(ParseNode, Empty): """ Variable definition. """ def __init__(self, s, n, t): """ Save self.name, self.default, self.expression """ super(VarDefinition, self).__init__(s, n, t) self.name = t[0][1:] self.default = len(t) > 2 self.expression = t[1] def parse(self, target): """ Update root and parent context. """ super(VarDefinition, self).parse(target) if isinstance(self.parent, ParseNode): self.parent.ctx.update({self.name: self.expression.value}) self.root.set_var(self) class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes)) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes)) def parse(src, cache=None): """ Parse from string. """ parser = Stylesheet(cache) return parser.loads(src) # pylama:ignore=D,W0401
klen/python-scss
scss/parser.py
Ruleset.parse
python
def parse(self, target): if isinstance(target, ContentNode): if target.name: self.parent = target self.name.parse(self) self.name += target.name target.ruleset.append(self) self.root.cache['rset'][str(self.name).split()[0]].add(self) super(Ruleset, self).parse(target)
Parse nested rulesets and save it in cache.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L63-L74
[ "def parse(self, target):\n super(ParseNode, self).parse(target)\n for n in self.data:\n if isinstance(n, Node):\n n.parse(self)\n" ]
class Ruleset(ContentNode): """ Rule node. """
klen/python-scss
scss/parser.py
Declaration.parse
python
def parse(self, target): if not isinstance(target, Node): parent = ContentNode(None, None, []) parent.parse(target) target = parent super(Declaration, self).parse(target) self.name = str(self.data[0]) while isinstance(target, Declaration): self.name = '-'.join((str(target.data[0]), self.name)) target = target.parent self.expr = ' '.join(str (n) for n in self.data [2:] if not isinstance(n, Declaration)) if self.expr: target.declareset.append(self)
Parse nested declaration.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L88-L107
[ "def parse(self, target):\n super(ParseNode, self).parse(target)\n for n in self.data:\n if isinstance(n, Node):\n n.parse(self)\n" ]
class Declaration(ParseNode): """ Declaration node. """ def __init__(self, s, n, t): """ Add self.name and self.expr to object. """ super(Declaration, self).__init__(s, n, t) self.name = self.expr = '' def __str__(self): """ Warning on unknown declaration and write current in outstring. """ name = self.name.strip('*_#') if name.startswith('-moz-'): name = name[5:] elif name.startswith('-webkit-'): name = name[8:] elif name.startswith('-o-'): name = name[3:] elif name.startswith('-ms-'): name = name[4:] if name not in SORTING and self.root.get_opt('warn'): warn("Unknown declaration: %s" % self.name) return (":%s" % self.root.cache['delims'][1]).join( (self.name, self.expr))
klen/python-scss
scss/parser.py
VarDefinition.parse
python
def parse(self, target): super(VarDefinition, self).parse(target) if isinstance(self.parent, ParseNode): self.parent.ctx.update({self.name: self.expression.value}) self.root.set_var(self)
Update root and parent context.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L188-L194
[ "def parse(self, target):\n super(ParseNode, self).parse(target)\n for n in self.data:\n if isinstance(n, Node):\n n.parse(self)\n" ]
class VarDefinition(ParseNode, Empty): """ Variable definition. """ def __init__(self, s, n, t): """ Save self.name, self.default, self.expression """ super(VarDefinition, self).__init__(s, n, t) self.name = t[0][1:] self.default = len(t) > 2 self.expression = t[1]
klen/python-scss
scss/parser.py
Stylesheet.set_var
python
def set_var(self, vardef): if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value
Set variable to global stylesheet context.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L292-L296
null
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes)) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/parser.py
Stylesheet.set_opt
python
def set_opt(self, name, value): self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '')
Set option.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L298-L307
null
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes)) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/parser.py
Stylesheet.update
python
def update(self, cache): self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values())
Update self cache from other.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L314-L321
null
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes)) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/parser.py
Stylesheet.scan
python
def scan(src): assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1)
Scan scss from string and return nodes.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L324-L336
null
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes)) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/parser.py
Stylesheet.loads
python
def loads(self, src): assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes))
Compile css from scss string.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L343-L349
[ "def scan(src):\n \"\"\" Scan scss from string and return nodes.\n \"\"\"\n assert isinstance(src, (unicode_, bytes_))\n try:\n nodes = STYLESHEET.parseString(src, parseAll=True)\n return nodes\n except ParseBaseException:\n err = sys.exc_info()[1]\n print(err.line, file=sys.stderr)\n print(\" \" * (err.column - 1) + \"^\", file=sys.stderr)\n print(err, file=sys.stderr)\n sys.exit(1)\n", "def parse(self, nodes):\n for n in nodes:\n if isinstance(n, Node):\n n.parse(self)\n" ]
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def load(self, f, precache=None): """ Compile scss from file. File is string path of file object. """ precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/parser.py
Stylesheet.load
python
def load(self, f, precache=None): precache = precache or self.get_opt('cache') or False nodes = None if isinstance(f, file_): path = os.path.abspath(f.name) else: path = os.path.abspath(f) f = open(f) cache_path = os.path.splitext(path)[0] + '.ccss' if precache and os.path.exists(cache_path): ptime = os.path.getmtime(cache_path) ttime = os.path.getmtime(path) if ptime > ttime: dump = open(cache_path, 'rb').read() nodes = pickle.loads(dump) if not nodes: src = f.read() nodes = self.scan(src.strip()) if precache: f = open(cache_path, 'wb') pickle.dump(nodes, f, protocol=1) self.parse(nodes) return ''.join(map(str, nodes))
Compile scss from file. File is string path of file object.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/parser.py#L351-L382
[ "def get_opt(self, name):\n \"\"\" Get option.\n \"\"\"\n return self.cache['opts'].get(name)\n" ]
class Stylesheet(object): """ Root stylesheet node. """ def_delims = '\n', ' ', '\t' def __init__(self, cache=None, options=None): self.cache = cache or dict( # Variables context ctx=dict(), # Mixin context mix=dict(), # Rules context rset=defaultdict(set), # Options context opts=dict( comments=True, warn=True, sort=True, path=os.getcwd(), ), # CSS delimeters delims=self.def_delims, ) if options: for option in options.items(): self.set_opt(*option) self.setup() Node.root = self @staticmethod def setup(): # Values NUMBER_VALUE.setParseAction(NumberValue) IDENT.setParseAction(StringValue) PATH.setParseAction(StringValue) POINT.setParseAction(PointValue) COLOR_VALUE.setParseAction(ColorValue) quotedString.setParseAction(QuotedStringValue) EXPRESSION.setParseAction(Expression) SEP_VAL_STRING.setParseAction(SepValString) # Vars VARIABLE.setParseAction(Variable) VAR_DEFINITION.setParseAction(VarDefinition) VARIABLES.setParseAction(Variables) FUNCTION.setParseAction(Function) FUNCTION_DEFINITION.setParseAction(FunctionDefinition) FUNCTION_RETURN.setParseAction(FunctionReturn) # Coments SCSS_COMMENT.setParseAction(lambda x: '') CSS_COMMENT.setParseAction(Comment) # At rules IMPORT.setParseAction(Import) CHARSET.setParseAction(Import) MEDIA.setParseAction(Node) # Rules RULESET.setParseAction(Ruleset) DECLARATION.setParseAction(Declaration) DECLARATION_NAME.setParseAction(DeclarationName) SELECTOR.setParseAction(Selector) SELECTOR_GROUP.setParseAction(ParseNode) SELECTOR_TREE.setParseAction(SelectorTree) FONT_FACE.setParseAction(ContentNode) # SCSS Directives MIXIN.setParseAction(Mixin) MIXIN_PARAM.setParseAction(MixinParam) INCLUDE.setParseAction(Include) EXTEND.setParseAction(Extend) OPTION.setParseAction(Option) IF.setParseAction(If) IF_BODY.setParseAction(IncludeNode) ELSE.setParseAction(IncludeNode) FOR.setParseAction(For) FOR_BODY.setParseAction(IncludeNode) WARN.setParseAction(Warn) @property def ctx(self): return self.cache['ctx'] def set_var(self, vardef): """ Set variable to global stylesheet context. """ if not(vardef.default and self.cache['ctx'].get(vardef.name)): self.cache['ctx'][vardef.name] = vardef.expression.value def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '') def get_opt(self, name): """ Get option. """ return self.cache['opts'].get(name) def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['ctx'].values()) @staticmethod def scan(src): """ Scan scss from string and return nodes. """ assert isinstance(src, (unicode_, bytes_)) try: nodes = STYLESHEET.parseString(src, parseAll=True) return nodes except ParseBaseException: err = sys.exc_info()[1] print(err.line, file=sys.stderr) print(" " * (err.column - 1) + "^", file=sys.stderr) print(err, file=sys.stderr) sys.exit(1) def parse(self, nodes): for n in nodes: if isinstance(n, Node): n.parse(self) def loads(self, src): """ Compile css from scss string. """ assert isinstance(src, (unicode_, bytes_)) nodes = self.scan(src.strip()) self.parse(nodes) return ''.join(map(str, nodes))
klen/python-scss
scss/tool.py
complete
python
def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1
Auto complete scss constructions in interactive mode.
train
https://github.com/klen/python-scss/blob/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tool.py#L16-L23
null
""" Command-line tool to parse scss file. """ from __future__ import print_function import optparse import sys import os import time from . import parser, __version__ COMMANDS = ['import', 'option', 'mixin', 'include', 'for', 'if', 'else'] def main(argv=None): # noqa try: # Upgrade shell in interactive mode import atexit import readline history = os.path.join(os.environ['HOME'], ".scss-history") atexit.register(readline.write_history_file, history) readline.parse_and_bind("tab: complete") readline.set_completer(complete) readline.read_history_file(history) except (ImportError, IOError): pass # Create options p = optparse.OptionParser( usage="%prog [OPTION]... [INFILE] [OUTFILE]", version="%prog " + __version__, epilog="SCSS compiler.", description="Compile INFILE or standard input, to OUTFILE or standard output.") p.add_option( '-c', '--cache', action='store_true', dest='cache', help="Create and use cache file. Only for files.") p.add_option( '-i', '--interactive', action='store_true', dest='shell', help="Run in interactive shell mode.") p.add_option( '-m', '--compress', action='store_true', dest='compress', help="Compress css output.") p.add_option( '-w', '--watch', dest='watch', help="""Watch files or directories for changes. The location of the generated CSS can be set using a colon: scss -w input.scss:output.css """) p.add_option( '-S', '--no-sorted', action='store_false', dest='sort', help="Do not sort declaration.") p.add_option( '-C', '--no-comments', action='store_false', dest='comments', help="Clear css comments.") p.add_option( '-W', '--no-warnings', action='store_false', dest='warn', help="Disable warnings.") opts, args = p.parse_args(argv or sys.argv[1:]) precache = opts.cache # Interactive mode if opts.shell: p = parser.Stylesheet() print('SCSS v. %s interactive mode' % __version__) print('================================') print('Ctrl+D or quit for exit') while True: try: s = input('>>> ').strip() if s == 'quit': raise EOFError print(p.loads(s)) except (EOFError, KeyboardInterrupt): print('\nBye bye.') break sys.exit() # Watch mode elif opts.watch: self, _, target = opts.watch.partition(':') files = [] if not os.path.exists(self): print(sys.stderr, "Path don't exist: %s" % self, file=sys.stderr) sys.exit(1) if os.path.isdir(self): for f in os.listdir(self): path = os.path.join(self, f) if os.path.isfile(path) and f.endswith('.scss'): tpath = os.path.join(target or self, f[:-5] + '.css') files.append([path, tpath, 0]) else: files.append([self, target or self[:-5] + '.css', 0]) s = parser.Stylesheet( options=dict( comments=opts.comments, compress=opts.compress, warn=opts.warn, sort=opts.sort, cache=precache, )) def parse(f): infile, outfile, mtime = f ttime = os.path.getmtime(infile) if mtime < ttime: print(" Parse '%s' to '%s' .. done" % (infile, outfile)) out = s.load(open(infile, 'r')) open(outfile, 'w').write(out) f[2] = os.path.getmtime(outfile) print('SCSS v. %s watch mode' % __version__) print('================================') print('Ctrl+C for exit\n') while True: try: for f in files: parse(f) time.sleep(0.3) except OSError: pass except KeyboardInterrupt: print("\nSCSS stoped.") break sys.exit() # Default compile files elif not args: infile = sys.stdin outfile = sys.stdout precache = False elif len(args) == 1: try: infile = open(args[0], 'r') outfile = sys.stdout except IOError as e: sys.stderr.write(str(e)) sys.exit() elif len(args) == 2: try: infile = open(args[0], 'r') outfile = open(args[1], 'w') except IOError as e: sys.stderr.write(str(e)) sys.exit() else: p.print_help(sys.stdout) sys.exit() try: s = parser.Stylesheet( options=dict( comments=opts.comments, compress=opts.compress, warn=opts.warn, sort=opts.sort, cache=precache, )) outfile.write(s.load(infile)) except ValueError as e: raise SystemExit(e) if __name__ == '__main__': main()
Clivern/PyLogging
pylogging/mailer.py
Mailer.login
python
def login(self, usr, pwd): self._usr = usr self._pwd = pwd
Use login() to Log in with a username and password.
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/mailer.py#L20-L23
null
class Mailer(): """ Send Log Messages To Email """ def __init__(self, host='smtp.gmail.com', port=587): """ Define Host """ self.host = host self.port = port self._usr = None self._pwd = None def send(self, me, to, subject, msg): """ Send Message """ msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = to server = smtplib.SMTP(self.host, self.port) server.starttls() # Check if user and password defined if self._usr and self._pwd: server.login(self._usr, self._pwd) try: # Send email server.sendmail(me, [x.strip() for x in to.split(",")], msg.as_string()) except: # Error sending email raise Exception("Error Sending Message.") # Quit! server.quit()
Clivern/PyLogging
pylogging/mailer.py
Mailer.send
python
def send(self, me, to, subject, msg): msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = to server = smtplib.SMTP(self.host, self.port) server.starttls() # Check if user and password defined if self._usr and self._pwd: server.login(self._usr, self._pwd) try: # Send email server.sendmail(me, [x.strip() for x in to.split(",")], msg.as_string()) except: # Error sending email raise Exception("Error Sending Message.") # Quit! server.quit()
Send Message
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/mailer.py#L25-L43
null
class Mailer(): """ Send Log Messages To Email """ def __init__(self, host='smtp.gmail.com', port=587): """ Define Host """ self.host = host self.port = port self._usr = None self._pwd = None def login(self, usr, pwd): """ Use login() to Log in with a username and password. """ self._usr = usr self._pwd = pwd
Clivern/PyLogging
pylogging/storage.py
TextStorage.write
python
def write(self, log_file, msg): try: with open(log_file, 'a') as LogFile: LogFile.write(msg + os.linesep) except: raise Exception('Error Configuring PyLogger.TextStorage Class.') return os.path.isfile(log_file)
Append message to .log file
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/storage.py#L12-L20
null
class TextStorage(): """ Text Storage Class """ def read(self, log_file): """ Read messages from .log file """ if os.path.isdir(os.path.dirname(log_file)) and os.path.isfile(log_file): with open(log_file, 'r') as LogFile: data = LogFile.readlines() data = "".join(line for line in data) else: data = '' return data
Clivern/PyLogging
pylogging/storage.py
TextStorage.read
python
def read(self, log_file): if os.path.isdir(os.path.dirname(log_file)) and os.path.isfile(log_file): with open(log_file, 'r') as LogFile: data = LogFile.readlines() data = "".join(line for line in data) else: data = '' return data
Read messages from .log file
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/storage.py#L22-L30
null
class TextStorage(): """ Text Storage Class """ def write(self, log_file, msg): """ Append message to .log file """ try: with open(log_file, 'a') as LogFile: LogFile.write(msg + os.linesep) except: raise Exception('Error Configuring PyLogger.TextStorage Class.') return os.path.isfile(log_file)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._config
python
def _config(self, **kargs): for key, value in kargs.items(): setattr(self, key, value)
ReConfigure Package
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L86-L89
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.getConfig
python
def getConfig(self, key): if hasattr(self, key): return getattr(self, key) else: return False
Get a Config Value
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L91-L96
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.addFilter
python
def addFilter(self, filter): self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1)
Register Custom Filter
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L103-L106
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.addAction
python
def addAction(self, action): self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1)
Register Custom Action
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L108-L111
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.removeFilter
python
def removeFilter(self, filter): filter = filter.split('#') del self.FILTERS[int(filter[1])] return True
Remove Registered Filter
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L113-L117
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.removeAction
python
def removeAction(self, action): action = action.split('#') del self.ACTIONS[int(action[1])] return True
Remove Registered Action
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L119-L123
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.info
python
def info(self, msg): self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg)
Log Info Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L125-L130
[ "def _processMsg(self, type, msg):\n \"\"\" Process Debug Messages \"\"\"\n now = datetime.datetime.now()\n\n # Check If Path not provided\n if self.LOG_FILE_PATH == '':\n self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'\n\n # Build absolute Path\n log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'\n\n # Add General Vars\n msg = self.LOG_MESSAGE_FORMAT.format(\n TYPE=type.upper(),\n DATE=now.strftime(self.DATES_FORMAT),\n DATETIME=now.strftime(self.DATETIME_FORMAT),\n MESSAGE=msg,\n )\n\n # Check if to add platform data\n if self.PLATFORM_DATA:\n # Add Platform Specific Vars\n msg = msg.format(\n PL_TYPE=platform.machine(),\n PL_NAME=platform.node(),\n PL_PROCESSOR=platform.processor(),\n PL_PY_BUILD_DATE=platform.python_build()[1],\n PL_PY_COMPILER=platform.python_compiler(),\n PL_PY_RELEASE=platform.release(),\n PL_OS=platform.system(),\n PL_TIMEZONE=strftime(\"%z\", gmtime())\n )\n\n # Create Storage Instance\n self._STORAGE = Storage(log_file)\n # Write Storage\n return self._STORAGE.write(msg)\n", "def _sendMsg(self, type, msg):\n \"\"\" Send Alert Message To Emails \"\"\"\n if self.ALERT_STATUS and type in self.ALERT_TYPES:\n self._configMailer()\n self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)\n", "def _execFilters(self, type, msg):\n \"\"\" Execute Registered Filters \"\"\"\n for filter in self.FILTERS:\n msg = filter(type, msg)\n return msg\n", "def _execActions(self, type, msg):\n \"\"\" Execute Registered Actions \"\"\"\n for action in self.ACTIONS:\n action(type, msg)" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.warning
python
def warning(self, msg): self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg)
Log Warning Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L132-L137
[ "def _processMsg(self, type, msg):\n \"\"\" Process Debug Messages \"\"\"\n now = datetime.datetime.now()\n\n # Check If Path not provided\n if self.LOG_FILE_PATH == '':\n self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'\n\n # Build absolute Path\n log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'\n\n # Add General Vars\n msg = self.LOG_MESSAGE_FORMAT.format(\n TYPE=type.upper(),\n DATE=now.strftime(self.DATES_FORMAT),\n DATETIME=now.strftime(self.DATETIME_FORMAT),\n MESSAGE=msg,\n )\n\n # Check if to add platform data\n if self.PLATFORM_DATA:\n # Add Platform Specific Vars\n msg = msg.format(\n PL_TYPE=platform.machine(),\n PL_NAME=platform.node(),\n PL_PROCESSOR=platform.processor(),\n PL_PY_BUILD_DATE=platform.python_build()[1],\n PL_PY_COMPILER=platform.python_compiler(),\n PL_PY_RELEASE=platform.release(),\n PL_OS=platform.system(),\n PL_TIMEZONE=strftime(\"%z\", gmtime())\n )\n\n # Create Storage Instance\n self._STORAGE = Storage(log_file)\n # Write Storage\n return self._STORAGE.write(msg)\n", "def _sendMsg(self, type, msg):\n \"\"\" Send Alert Message To Emails \"\"\"\n if self.ALERT_STATUS and type in self.ALERT_TYPES:\n self._configMailer()\n self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)\n", "def _execFilters(self, type, msg):\n \"\"\" Execute Registered Filters \"\"\"\n for filter in self.FILTERS:\n msg = filter(type, msg)\n return msg\n", "def _execActions(self, type, msg):\n \"\"\" Execute Registered Actions \"\"\"\n for action in self.ACTIONS:\n action(type, msg)" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.error
python
def error(self, msg): self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg)
Log Error Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L139-L144
[ "def _processMsg(self, type, msg):\n \"\"\" Process Debug Messages \"\"\"\n now = datetime.datetime.now()\n\n # Check If Path not provided\n if self.LOG_FILE_PATH == '':\n self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'\n\n # Build absolute Path\n log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'\n\n # Add General Vars\n msg = self.LOG_MESSAGE_FORMAT.format(\n TYPE=type.upper(),\n DATE=now.strftime(self.DATES_FORMAT),\n DATETIME=now.strftime(self.DATETIME_FORMAT),\n MESSAGE=msg,\n )\n\n # Check if to add platform data\n if self.PLATFORM_DATA:\n # Add Platform Specific Vars\n msg = msg.format(\n PL_TYPE=platform.machine(),\n PL_NAME=platform.node(),\n PL_PROCESSOR=platform.processor(),\n PL_PY_BUILD_DATE=platform.python_build()[1],\n PL_PY_COMPILER=platform.python_compiler(),\n PL_PY_RELEASE=platform.release(),\n PL_OS=platform.system(),\n PL_TIMEZONE=strftime(\"%z\", gmtime())\n )\n\n # Create Storage Instance\n self._STORAGE = Storage(log_file)\n # Write Storage\n return self._STORAGE.write(msg)\n", "def _sendMsg(self, type, msg):\n \"\"\" Send Alert Message To Emails \"\"\"\n if self.ALERT_STATUS and type in self.ALERT_TYPES:\n self._configMailer()\n self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)\n", "def _execFilters(self, type, msg):\n \"\"\" Execute Registered Filters \"\"\"\n for filter in self.FILTERS:\n msg = filter(type, msg)\n return msg\n", "def _execActions(self, type, msg):\n \"\"\" Execute Registered Actions \"\"\"\n for action in self.ACTIONS:\n action(type, msg)" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.critical
python
def critical(self, msg): self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg)
Log Critical Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L146-L151
[ "def _processMsg(self, type, msg):\n \"\"\" Process Debug Messages \"\"\"\n now = datetime.datetime.now()\n\n # Check If Path not provided\n if self.LOG_FILE_PATH == '':\n self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'\n\n # Build absolute Path\n log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'\n\n # Add General Vars\n msg = self.LOG_MESSAGE_FORMAT.format(\n TYPE=type.upper(),\n DATE=now.strftime(self.DATES_FORMAT),\n DATETIME=now.strftime(self.DATETIME_FORMAT),\n MESSAGE=msg,\n )\n\n # Check if to add platform data\n if self.PLATFORM_DATA:\n # Add Platform Specific Vars\n msg = msg.format(\n PL_TYPE=platform.machine(),\n PL_NAME=platform.node(),\n PL_PROCESSOR=platform.processor(),\n PL_PY_BUILD_DATE=platform.python_build()[1],\n PL_PY_COMPILER=platform.python_compiler(),\n PL_PY_RELEASE=platform.release(),\n PL_OS=platform.system(),\n PL_TIMEZONE=strftime(\"%z\", gmtime())\n )\n\n # Create Storage Instance\n self._STORAGE = Storage(log_file)\n # Write Storage\n return self._STORAGE.write(msg)\n", "def _sendMsg(self, type, msg):\n \"\"\" Send Alert Message To Emails \"\"\"\n if self.ALERT_STATUS and type in self.ALERT_TYPES:\n self._configMailer()\n self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)\n", "def _execFilters(self, type, msg):\n \"\"\" Execute Registered Filters \"\"\"\n for filter in self.FILTERS:\n msg = filter(type, msg)\n return msg\n", "def _execActions(self, type, msg):\n \"\"\" Execute Registered Actions \"\"\"\n for action in self.ACTIONS:\n action(type, msg)" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging.log
python
def log(self, msg): self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg)
Log Normal Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L153-L158
[ "def _processMsg(self, type, msg):\n \"\"\" Process Debug Messages \"\"\"\n now = datetime.datetime.now()\n\n # Check If Path not provided\n if self.LOG_FILE_PATH == '':\n self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'\n\n # Build absolute Path\n log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log'\n\n # Add General Vars\n msg = self.LOG_MESSAGE_FORMAT.format(\n TYPE=type.upper(),\n DATE=now.strftime(self.DATES_FORMAT),\n DATETIME=now.strftime(self.DATETIME_FORMAT),\n MESSAGE=msg,\n )\n\n # Check if to add platform data\n if self.PLATFORM_DATA:\n # Add Platform Specific Vars\n msg = msg.format(\n PL_TYPE=platform.machine(),\n PL_NAME=platform.node(),\n PL_PROCESSOR=platform.processor(),\n PL_PY_BUILD_DATE=platform.python_build()[1],\n PL_PY_COMPILER=platform.python_compiler(),\n PL_PY_RELEASE=platform.release(),\n PL_OS=platform.system(),\n PL_TIMEZONE=strftime(\"%z\", gmtime())\n )\n\n # Create Storage Instance\n self._STORAGE = Storage(log_file)\n # Write Storage\n return self._STORAGE.write(msg)\n", "def _sendMsg(self, type, msg):\n \"\"\" Send Alert Message To Emails \"\"\"\n if self.ALERT_STATUS and type in self.ALERT_TYPES:\n self._configMailer()\n self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)\n", "def _execFilters(self, type, msg):\n \"\"\" Execute Registered Filters \"\"\"\n for filter in self.FILTERS:\n msg = filter(type, msg)\n return msg\n", "def _execActions(self, type, msg):\n \"\"\" Execute Registered Actions \"\"\"\n for action in self.ACTIONS:\n action(type, msg)" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._processMsg
python
def _processMsg(self, type, msg): now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg)
Process Debug Messages
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L160-L196
[ "def write(self, msg):\n \"\"\" Append message to Requested Storage Type \"\"\"\n return self.storage.write(self.LOG_FILE, msg)\n" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._configMailer
python
def _configMailer(self): self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD)
Config Mailer Class
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L198-L201
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._sendMsg
python
def _sendMsg(self, type, msg): if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)
Send Alert Message To Emails
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L203-L207
[ "def _configMailer(self):\n \"\"\" Config Mailer Class \"\"\"\n self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT)\n self._MAILER.login(self.MAILER_USER, self.MAILER_PWD)\n" ]
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._execFilters
python
def _execFilters(self, type, msg): for filter in self.FILTERS: msg = filter(type, msg) return msg
Execute Registered Filters
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L209-L213
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execActions(self, type, msg): """ Execute Registered Actions """ for action in self.ACTIONS: action(type, msg)
Clivern/PyLogging
pylogging/pylogging.py
PyLogging._execActions
python
def _execActions(self, type, msg): for action in self.ACTIONS: action(type, msg)
Execute Registered Actions
train
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/pylogging.py#L215-L218
null
class PyLogging(dict): """ A Custom Logger Class """ # Log File Name Format LOG_FILE_FORMAT = '%Y-%m-%d' # Log File Path LOG_FILE_PATH = '' # Message Format. A list of available vars: # TYPE: Message type # DATE: Log time Date # DATETIME: Log time datetime # MESSAGE: Message content LOG_MESSAGE_FORMAT = '{TYPE}: <{DATETIME}> {MESSAGE}' # Dates Format DATES_FORMAT = '%Y-%m-%d' # Datetime Format DATETIME_FORMAT = '%Y-%m-%d %H:%M' # Platform Data Vars # If set to true, It will Add the following: # PL_TYPE: The machine type, e.g. i386 # PL_NAME: The computer network name. # PL_PROCESSOR: The (real) processor name, e.g. amdk6. # PL_PY_BUILD_DATE: The Python build number. # PL_PY_COMPILER: A string identifying the compiler used for compiling Python. # PL_PY_RELEASE: The system release, e.g. 2.2.0. # PL_OS: The system/OS name, e.g. Linux, Windows # PL_TIMEZONE: The system timezone. PLATFORM_DATA = False # Whether to Send Alert Email ALERT_STATUS = False # Alert Email Default Subject ALERT_SUBJECT = "My APP Alert" # Alert Email ALERT_EMAIL = 'you@gmail.com' # Message Types to Send to Email ALERT_TYPES = ['critical', 'error'] # Mailer Class Host MAILER_HOST = 'smtp.gmail.com' # Mailer Class Port MAILER_PORT = 587 # Mailer Class User MAILER_USER = None # Mailer Class PWD MAILER_PWD = None # From Email Value MAILER_FROM = 'you@gmail.com' # Custom Message Filters FILTERS = [] # Custom Message Actions ACTIONS = [] def __init__(self, **kargs): """ Init PyLogger Class and Mailer Class """ self._config(**kargs) def _config(self, **kargs): """ ReConfigure Package """ for key, value in kargs.items(): setattr(self, key, value) def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False def setConfig(self, key, value): """ Set a Config Value """ setattr(self, key, value) return True def addFilter(self, filter): """ Register Custom Filter """ self.FILTERS.append(filter) return "FILTER#{}".format(len(self.FILTERS) - 1) def addAction(self, action): """ Register Custom Action """ self.ACTIONS.append(action) return "ACTION#{}".format(len(self.ACTIONS) - 1) def removeFilter(self, filter): """ Remove Registered Filter """ filter = filter.split('#') del self.FILTERS[int(filter[1])] return True def removeAction(self, action): """ Remove Registered Action """ action = action.split('#') del self.ACTIONS[int(action[1])] return True def info(self, msg): """ Log Info Messages """ self._execActions('info', msg) msg = self._execFilters('info', msg) self._processMsg('info', msg) self._sendMsg('info', msg) def warning(self, msg): """ Log Warning Messages """ self._execActions('warning', msg) msg = self._execFilters('warning', msg) self._processMsg('warning', msg) self._sendMsg('warning', msg) def error(self, msg): """ Log Error Messages """ self._execActions('error', msg) msg = self._execFilters('error', msg) self._processMsg('error', msg) self._sendMsg('error', msg) def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg) def log(self, msg): """ Log Normal Messages """ self._execActions('log', msg) msg = self._execFilters('log', msg) self._processMsg('log', msg) self._sendMsg('log', msg) def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) + '.log' # Add General Vars msg = self.LOG_MESSAGE_FORMAT.format( TYPE=type.upper(), DATE=now.strftime(self.DATES_FORMAT), DATETIME=now.strftime(self.DATETIME_FORMAT), MESSAGE=msg, ) # Check if to add platform data if self.PLATFORM_DATA: # Add Platform Specific Vars msg = msg.format( PL_TYPE=platform.machine(), PL_NAME=platform.node(), PL_PROCESSOR=platform.processor(), PL_PY_BUILD_DATE=platform.python_build()[1], PL_PY_COMPILER=platform.python_compiler(), PL_PY_RELEASE=platform.release(), PL_OS=platform.system(), PL_TIMEZONE=strftime("%z", gmtime()) ) # Create Storage Instance self._STORAGE = Storage(log_file) # Write Storage return self._STORAGE.write(msg) def _configMailer(self): """ Config Mailer Class """ self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT) self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) def _sendMsg(self, type, msg): """ Send Alert Message To Emails """ if self.ALERT_STATUS and type in self.ALERT_TYPES: self._configMailer() self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg) def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg
timmahrt/pysle
pysle/praattools.py
spellCheckTextgrid
python
def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False): ''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False else: returnVal = True return returnVal tg = praatio_scripts.spellCheckEntries(tg, targetTierName, newTierName, checkFunc, printEntries) return tg
Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/praattools.py#L24-L46
null
#encoding: utf-8 ''' Created on Oct 22, 2014 @author: tmahrt ''' class OptionalFeatureError(ImportError): def __str__(self): return "ERROR: You must have praatio installed to use pysle.praatTools" try: from praatio import tgio from praatio import praatio_scripts except ImportError: raise OptionalFeatureError() from pysle import isletool from pysle import pronunciationtools def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False): ''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False else: returnVal = True return returnVal tg = praatio_scripts.spellCheckEntries(tg, targetTierName, newTierName, checkFunc, printEntries) return tg def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): ''' Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTier = tg.tierDict[wordTierName] # Load in the word tier, if it exists: wordEntryList = [] phoneEntryList = [] if wordTier is not None: if removeOverlappingSegments: for startT, stopT, _ in utteranceTier.entryList: wordTier = wordTier.eraseRegion(startT, stopT, 'truncate', False) wordEntryList = wordTier.entryList # Do the naive alignment for startT, stopT, label in utteranceTier.entryList: wordList = label.split() # Get the list of phones in each word superPhoneList = [] numPhones = 0 i = 0 while i < len(wordList): word = wordList[i] try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: wordList.pop(i) continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] superPhoneList.append(phoneList) numPhones += len(phoneList) i += 1 # Get the naive alignment for words, if alignment doesn't # already exist for words subWordEntryList = [] subPhoneEntryList = [] if wordTier is not None: subWordEntryList = wordTier.crop(startT, stopT, "truncated", False).entryList if len(subWordEntryList) == 0: wordStartT = startT phoneDur = (stopT - startT) / float(numPhones) for i, word in enumerate(wordList): phoneListTxt = " ".join(superPhoneList[i]) wordStartT = wordStartT wordEndT = wordStartT + (phoneDur * len(superPhoneList[i])) subWordEntryList.append((wordStartT, wordEndT, word)) subPhoneEntryList.append((wordStartT, wordEndT, phoneListTxt)) wordStartT = wordEndT wordEntryList.extend(subWordEntryList) phoneEntryList.extend(subPhoneEntryList) # Replace or add the word tier newWordTier = tgio.IntervalTier(wordTierName, wordEntryList, tg.minTimestamp, tg.maxTimestamp) if wordTier is not None: tg.replaceTier(wordTierName, newWordTier) else: tg.addTier(newWordTier) # Add the phone tier # This is mainly used as an annotation tier if phoneHelperTierName is not None and len(phoneEntryList) > 0: newPhoneTier = tgio.IntervalTier(phoneHelperTierName, phoneEntryList, tg.minTimestamp, tg.minTimestamp) if phoneHelperTierName in tg.tierNameList: tg.replaceTier(phoneHelperTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False): ''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' wordTier = tg.tierDict[wordTierName] phoneTier = None if phoneTierName in tg.tierNameList: phoneTier = tg.tierDict[phoneTierName] # Load in the phone tier, if it exists: phoneEntryList = [] if phoneTier is not None: if removeOverlappingSegments: for startT, stopT, _ in wordTier.entryList: phoneTier = phoneTier.eraseRegion(startT, stopT, 'truncate', False) phoneEntryList = phoneTier.entryList # Do the naive alignment for wordStartT, wordEndT, word in wordTier.entryList: # Get the list of phones in this word try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] for char in [u'ˈ', u'ˌ']: phoneList = [phone.replace(char, '') for phone in phoneList] # Get the naive alignment for phones, if alignment doesn't # already exist for phones subPhoneEntryList = [] if phoneTier is not None: subPhoneEntryList = phoneTier.crop(wordStartT, wordEndT, "truncated", False).entryList if len(subPhoneEntryList) == 0: phoneDur = (wordEndT - wordStartT) / len(phoneList) phoneStartT = wordStartT for phone in phoneList: phoneEndT = phoneStartT + phoneDur subPhoneEntryList.append((phoneStartT, phoneEndT, phone)) phoneStartT = phoneEndT phoneEntryList.extend(subPhoneEntryList) # Replace or add the phone tier newPhoneTier = tgio.IntervalTier(phoneTierName, phoneEntryList, tg.minTimestamp, tg.maxTimestamp) if phoneTier is not None: tg.replaceTier(phoneTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): ''' Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress). ''' minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: skipLabelList = [] syllableEntryList = [] tonicSEntryList = [] tonicPEntryList = [] if startT is not None or stopT is not None: if startT is None: startT = minT if stopT is None: stopT = maxT wordTier = wordTier.crop(startT, stopT, "truncated", False) for start, stop, word in wordTier.entryList: if word in skipLabelList: continue subPhoneTier = phoneTier.crop(start, stop, "strict", False) # entry = (start, stop, phone) phoneList = [entry[2] for entry in subPhoneTier.entryList if entry[2] != ''] phoneList = [phoneList, ] try: sylTmp = pronunciationtools.findBestSyllabification(isleDict, word, phoneList) except isletool.WordNotInISLE: print("Word ('%s') not is isle -- skipping syllabification" % word) continue except (pronunciationtools.NullPronunciationError): print("Word ('%s') has no provided pronunciation" % word) continue except AssertionError: print("Unable to syllabify '%s'" % word) continue for syllabificationResultList in sylTmp: stressI = syllabificationResultList[0] stressJ = syllabificationResultList[1] syllableList = syllabificationResultList[2] stressedPhone = None if stressI is not None and stressJ is not None: stressedPhone = syllableList[stressI][stressJ] syllableList[stressI][stressJ] += u"ˈ" i = 0 # print(syllableList) for k, syllable in enumerate(syllableList): # Create the syllable tier entry j = len(syllable) stubEntryList = subPhoneTier.entryList[i:i + j] i += j # The whole syllable was deleted if len(stubEntryList) == 0: continue syllableStart = stubEntryList[0][0] syllableEnd = stubEntryList[-1][1] label = "-".join([entry[2] for entry in stubEntryList]) syllableEntryList.append((syllableStart, syllableEnd, label)) # Create the tonic syllable tier entry if k == stressI: tonicSEntryList.append((syllableStart, syllableEnd, 'T')) # Create the tonic phone tier entry if k == stressI: syllablePhoneTier = phoneTier.crop(syllableStart, syllableEnd, "strict", False) phoneList = [entry for entry in syllablePhoneTier.entryList if entry[2] != ''] justPhones = [phone for _, _, phone in phoneList] cvList = pronunciationtools._prepPronunciation(justPhones) try: tmpStressJ = cvList.index('V') except ValueError: for char in [u'r', u'n', u'l']: if char in cvList: tmpStressJ = cvList.index(char) break phoneStart, phoneEnd = phoneList[tmpStressJ][:2] tonicPEntryList.append((phoneStart, phoneEnd, 'T')) # Create a textgrid with the two syllable-level tiers syllableTier = tgio.IntervalTier('syllable', syllableEntryList, minT, maxT) tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList, minT, maxT) tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList, minT, maxT) syllableTG = tgio.Textgrid() syllableTG.addTier(syllableTier) syllableTG.addTier(tonicSTier) syllableTG.addTier(tonicPTier) return syllableTG
timmahrt/pysle
pysle/praattools.py
naiveWordAlignment
python
def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): ''' Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTier = tg.tierDict[wordTierName] # Load in the word tier, if it exists: wordEntryList = [] phoneEntryList = [] if wordTier is not None: if removeOverlappingSegments: for startT, stopT, _ in utteranceTier.entryList: wordTier = wordTier.eraseRegion(startT, stopT, 'truncate', False) wordEntryList = wordTier.entryList # Do the naive alignment for startT, stopT, label in utteranceTier.entryList: wordList = label.split() # Get the list of phones in each word superPhoneList = [] numPhones = 0 i = 0 while i < len(wordList): word = wordList[i] try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: wordList.pop(i) continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] superPhoneList.append(phoneList) numPhones += len(phoneList) i += 1 # Get the naive alignment for words, if alignment doesn't # already exist for words subWordEntryList = [] subPhoneEntryList = [] if wordTier is not None: subWordEntryList = wordTier.crop(startT, stopT, "truncated", False).entryList if len(subWordEntryList) == 0: wordStartT = startT phoneDur = (stopT - startT) / float(numPhones) for i, word in enumerate(wordList): phoneListTxt = " ".join(superPhoneList[i]) wordStartT = wordStartT wordEndT = wordStartT + (phoneDur * len(superPhoneList[i])) subWordEntryList.append((wordStartT, wordEndT, word)) subPhoneEntryList.append((wordStartT, wordEndT, phoneListTxt)) wordStartT = wordEndT wordEntryList.extend(subWordEntryList) phoneEntryList.extend(subPhoneEntryList) # Replace or add the word tier newWordTier = tgio.IntervalTier(wordTierName, wordEntryList, tg.minTimestamp, tg.maxTimestamp) if wordTier is not None: tg.replaceTier(wordTierName, newWordTier) else: tg.addTier(newWordTier) # Add the phone tier # This is mainly used as an annotation tier if phoneHelperTierName is not None and len(phoneEntryList) > 0: newPhoneTier = tgio.IntervalTier(phoneHelperTierName, phoneEntryList, tg.minTimestamp, tg.minTimestamp) if phoneHelperTierName in tg.tierNameList: tg.replaceTier(phoneHelperTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg
Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/praattools.py#L49-L150
[ "def lookup(self, word):\n '''\n Lookup a word and receive a list of syllables and stressInfo\n\n Output example for the word 'another' which has two pronunciations\n [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),\n ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]\n '''\n\n # All words must be lowercase with no extraneous whitespace\n word = word.lower()\n word = word.strip()\n\n pronList = self.data.get(word, None)\n\n if pronList is None:\n raise WordNotInISLE(word)\n else:\n pronList = [_parsePronunciation(pronunciationStr)\n for pronunciationStr, _ in pronList]\n pronList = list(zip(*pronList))\n\n return pronList\n" ]
#encoding: utf-8 ''' Created on Oct 22, 2014 @author: tmahrt ''' class OptionalFeatureError(ImportError): def __str__(self): return "ERROR: You must have praatio installed to use pysle.praatTools" try: from praatio import tgio from praatio import praatio_scripts except ImportError: raise OptionalFeatureError() from pysle import isletool from pysle import pronunciationtools def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False): ''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False else: returnVal = True return returnVal tg = praatio_scripts.spellCheckEntries(tg, targetTierName, newTierName, checkFunc, printEntries) return tg def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): ''' Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTier = tg.tierDict[wordTierName] # Load in the word tier, if it exists: wordEntryList = [] phoneEntryList = [] if wordTier is not None: if removeOverlappingSegments: for startT, stopT, _ in utteranceTier.entryList: wordTier = wordTier.eraseRegion(startT, stopT, 'truncate', False) wordEntryList = wordTier.entryList # Do the naive alignment for startT, stopT, label in utteranceTier.entryList: wordList = label.split() # Get the list of phones in each word superPhoneList = [] numPhones = 0 i = 0 while i < len(wordList): word = wordList[i] try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: wordList.pop(i) continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] superPhoneList.append(phoneList) numPhones += len(phoneList) i += 1 # Get the naive alignment for words, if alignment doesn't # already exist for words subWordEntryList = [] subPhoneEntryList = [] if wordTier is not None: subWordEntryList = wordTier.crop(startT, stopT, "truncated", False).entryList if len(subWordEntryList) == 0: wordStartT = startT phoneDur = (stopT - startT) / float(numPhones) for i, word in enumerate(wordList): phoneListTxt = " ".join(superPhoneList[i]) wordStartT = wordStartT wordEndT = wordStartT + (phoneDur * len(superPhoneList[i])) subWordEntryList.append((wordStartT, wordEndT, word)) subPhoneEntryList.append((wordStartT, wordEndT, phoneListTxt)) wordStartT = wordEndT wordEntryList.extend(subWordEntryList) phoneEntryList.extend(subPhoneEntryList) # Replace or add the word tier newWordTier = tgio.IntervalTier(wordTierName, wordEntryList, tg.minTimestamp, tg.maxTimestamp) if wordTier is not None: tg.replaceTier(wordTierName, newWordTier) else: tg.addTier(newWordTier) # Add the phone tier # This is mainly used as an annotation tier if phoneHelperTierName is not None and len(phoneEntryList) > 0: newPhoneTier = tgio.IntervalTier(phoneHelperTierName, phoneEntryList, tg.minTimestamp, tg.minTimestamp) if phoneHelperTierName in tg.tierNameList: tg.replaceTier(phoneHelperTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False): ''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' wordTier = tg.tierDict[wordTierName] phoneTier = None if phoneTierName in tg.tierNameList: phoneTier = tg.tierDict[phoneTierName] # Load in the phone tier, if it exists: phoneEntryList = [] if phoneTier is not None: if removeOverlappingSegments: for startT, stopT, _ in wordTier.entryList: phoneTier = phoneTier.eraseRegion(startT, stopT, 'truncate', False) phoneEntryList = phoneTier.entryList # Do the naive alignment for wordStartT, wordEndT, word in wordTier.entryList: # Get the list of phones in this word try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] for char in [u'ˈ', u'ˌ']: phoneList = [phone.replace(char, '') for phone in phoneList] # Get the naive alignment for phones, if alignment doesn't # already exist for phones subPhoneEntryList = [] if phoneTier is not None: subPhoneEntryList = phoneTier.crop(wordStartT, wordEndT, "truncated", False).entryList if len(subPhoneEntryList) == 0: phoneDur = (wordEndT - wordStartT) / len(phoneList) phoneStartT = wordStartT for phone in phoneList: phoneEndT = phoneStartT + phoneDur subPhoneEntryList.append((phoneStartT, phoneEndT, phone)) phoneStartT = phoneEndT phoneEntryList.extend(subPhoneEntryList) # Replace or add the phone tier newPhoneTier = tgio.IntervalTier(phoneTierName, phoneEntryList, tg.minTimestamp, tg.maxTimestamp) if phoneTier is not None: tg.replaceTier(phoneTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): ''' Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress). ''' minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: skipLabelList = [] syllableEntryList = [] tonicSEntryList = [] tonicPEntryList = [] if startT is not None or stopT is not None: if startT is None: startT = minT if stopT is None: stopT = maxT wordTier = wordTier.crop(startT, stopT, "truncated", False) for start, stop, word in wordTier.entryList: if word in skipLabelList: continue subPhoneTier = phoneTier.crop(start, stop, "strict", False) # entry = (start, stop, phone) phoneList = [entry[2] for entry in subPhoneTier.entryList if entry[2] != ''] phoneList = [phoneList, ] try: sylTmp = pronunciationtools.findBestSyllabification(isleDict, word, phoneList) except isletool.WordNotInISLE: print("Word ('%s') not is isle -- skipping syllabification" % word) continue except (pronunciationtools.NullPronunciationError): print("Word ('%s') has no provided pronunciation" % word) continue except AssertionError: print("Unable to syllabify '%s'" % word) continue for syllabificationResultList in sylTmp: stressI = syllabificationResultList[0] stressJ = syllabificationResultList[1] syllableList = syllabificationResultList[2] stressedPhone = None if stressI is not None and stressJ is not None: stressedPhone = syllableList[stressI][stressJ] syllableList[stressI][stressJ] += u"ˈ" i = 0 # print(syllableList) for k, syllable in enumerate(syllableList): # Create the syllable tier entry j = len(syllable) stubEntryList = subPhoneTier.entryList[i:i + j] i += j # The whole syllable was deleted if len(stubEntryList) == 0: continue syllableStart = stubEntryList[0][0] syllableEnd = stubEntryList[-1][1] label = "-".join([entry[2] for entry in stubEntryList]) syllableEntryList.append((syllableStart, syllableEnd, label)) # Create the tonic syllable tier entry if k == stressI: tonicSEntryList.append((syllableStart, syllableEnd, 'T')) # Create the tonic phone tier entry if k == stressI: syllablePhoneTier = phoneTier.crop(syllableStart, syllableEnd, "strict", False) phoneList = [entry for entry in syllablePhoneTier.entryList if entry[2] != ''] justPhones = [phone for _, _, phone in phoneList] cvList = pronunciationtools._prepPronunciation(justPhones) try: tmpStressJ = cvList.index('V') except ValueError: for char in [u'r', u'n', u'l']: if char in cvList: tmpStressJ = cvList.index(char) break phoneStart, phoneEnd = phoneList[tmpStressJ][:2] tonicPEntryList.append((phoneStart, phoneEnd, 'T')) # Create a textgrid with the two syllable-level tiers syllableTier = tgio.IntervalTier('syllable', syllableEntryList, minT, maxT) tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList, minT, maxT) tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList, minT, maxT) syllableTG = tgio.Textgrid() syllableTG.addTier(syllableTier) syllableTG.addTier(tonicSTier) syllableTG.addTier(tonicPTier) return syllableTG
timmahrt/pysle
pysle/praattools.py
naivePhoneAlignment
python
def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False): ''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' wordTier = tg.tierDict[wordTierName] phoneTier = None if phoneTierName in tg.tierNameList: phoneTier = tg.tierDict[phoneTierName] # Load in the phone tier, if it exists: phoneEntryList = [] if phoneTier is not None: if removeOverlappingSegments: for startT, stopT, _ in wordTier.entryList: phoneTier = phoneTier.eraseRegion(startT, stopT, 'truncate', False) phoneEntryList = phoneTier.entryList # Do the naive alignment for wordStartT, wordEndT, word in wordTier.entryList: # Get the list of phones in this word try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] for char in [u'ˈ', u'ˌ']: phoneList = [phone.replace(char, '') for phone in phoneList] # Get the naive alignment for phones, if alignment doesn't # already exist for phones subPhoneEntryList = [] if phoneTier is not None: subPhoneEntryList = phoneTier.crop(wordStartT, wordEndT, "truncated", False).entryList if len(subPhoneEntryList) == 0: phoneDur = (wordEndT - wordStartT) / len(phoneList) phoneStartT = wordStartT for phone in phoneList: phoneEndT = phoneStartT + phoneDur subPhoneEntryList.append((phoneStartT, phoneEndT, phone)) phoneStartT = phoneEndT phoneEntryList.extend(subPhoneEntryList) # Replace or add the phone tier newPhoneTier = tgio.IntervalTier(phoneTierName, phoneEntryList, tg.minTimestamp, tg.maxTimestamp) if phoneTier is not None: tg.replaceTier(phoneTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg
Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/praattools.py#L153-L223
[ "def lookup(self, word):\n '''\n Lookup a word and receive a list of syllables and stressInfo\n\n Output example for the word 'another' which has two pronunciations\n [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),\n ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]\n '''\n\n # All words must be lowercase with no extraneous whitespace\n word = word.lower()\n word = word.strip()\n\n pronList = self.data.get(word, None)\n\n if pronList is None:\n raise WordNotInISLE(word)\n else:\n pronList = [_parsePronunciation(pronunciationStr)\n for pronunciationStr, _ in pronList]\n pronList = list(zip(*pronList))\n\n return pronList\n" ]
#encoding: utf-8 ''' Created on Oct 22, 2014 @author: tmahrt ''' class OptionalFeatureError(ImportError): def __str__(self): return "ERROR: You must have praatio installed to use pysle.praatTools" try: from praatio import tgio from praatio import praatio_scripts except ImportError: raise OptionalFeatureError() from pysle import isletool from pysle import pronunciationtools def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False): ''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False else: returnVal = True return returnVal tg = praatio_scripts.spellCheckEntries(tg, targetTierName, newTierName, checkFunc, printEntries) return tg def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): ''' Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTier = tg.tierDict[wordTierName] # Load in the word tier, if it exists: wordEntryList = [] phoneEntryList = [] if wordTier is not None: if removeOverlappingSegments: for startT, stopT, _ in utteranceTier.entryList: wordTier = wordTier.eraseRegion(startT, stopT, 'truncate', False) wordEntryList = wordTier.entryList # Do the naive alignment for startT, stopT, label in utteranceTier.entryList: wordList = label.split() # Get the list of phones in each word superPhoneList = [] numPhones = 0 i = 0 while i < len(wordList): word = wordList[i] try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: wordList.pop(i) continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] superPhoneList.append(phoneList) numPhones += len(phoneList) i += 1 # Get the naive alignment for words, if alignment doesn't # already exist for words subWordEntryList = [] subPhoneEntryList = [] if wordTier is not None: subWordEntryList = wordTier.crop(startT, stopT, "truncated", False).entryList if len(subWordEntryList) == 0: wordStartT = startT phoneDur = (stopT - startT) / float(numPhones) for i, word in enumerate(wordList): phoneListTxt = " ".join(superPhoneList[i]) wordStartT = wordStartT wordEndT = wordStartT + (phoneDur * len(superPhoneList[i])) subWordEntryList.append((wordStartT, wordEndT, word)) subPhoneEntryList.append((wordStartT, wordEndT, phoneListTxt)) wordStartT = wordEndT wordEntryList.extend(subWordEntryList) phoneEntryList.extend(subPhoneEntryList) # Replace or add the word tier newWordTier = tgio.IntervalTier(wordTierName, wordEntryList, tg.minTimestamp, tg.maxTimestamp) if wordTier is not None: tg.replaceTier(wordTierName, newWordTier) else: tg.addTier(newWordTier) # Add the phone tier # This is mainly used as an annotation tier if phoneHelperTierName is not None and len(phoneEntryList) > 0: newPhoneTier = tgio.IntervalTier(phoneHelperTierName, phoneEntryList, tg.minTimestamp, tg.minTimestamp) if phoneHelperTierName in tg.tierNameList: tg.replaceTier(phoneHelperTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False): ''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' wordTier = tg.tierDict[wordTierName] phoneTier = None if phoneTierName in tg.tierNameList: phoneTier = tg.tierDict[phoneTierName] # Load in the phone tier, if it exists: phoneEntryList = [] if phoneTier is not None: if removeOverlappingSegments: for startT, stopT, _ in wordTier.entryList: phoneTier = phoneTier.eraseRegion(startT, stopT, 'truncate', False) phoneEntryList = phoneTier.entryList # Do the naive alignment for wordStartT, wordEndT, word in wordTier.entryList: # Get the list of phones in this word try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] for char in [u'ˈ', u'ˌ']: phoneList = [phone.replace(char, '') for phone in phoneList] # Get the naive alignment for phones, if alignment doesn't # already exist for phones subPhoneEntryList = [] if phoneTier is not None: subPhoneEntryList = phoneTier.crop(wordStartT, wordEndT, "truncated", False).entryList if len(subPhoneEntryList) == 0: phoneDur = (wordEndT - wordStartT) / len(phoneList) phoneStartT = wordStartT for phone in phoneList: phoneEndT = phoneStartT + phoneDur subPhoneEntryList.append((phoneStartT, phoneEndT, phone)) phoneStartT = phoneEndT phoneEntryList.extend(subPhoneEntryList) # Replace or add the phone tier newPhoneTier = tgio.IntervalTier(phoneTierName, phoneEntryList, tg.minTimestamp, tg.maxTimestamp) if phoneTier is not None: tg.replaceTier(phoneTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): ''' Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress). ''' minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: skipLabelList = [] syllableEntryList = [] tonicSEntryList = [] tonicPEntryList = [] if startT is not None or stopT is not None: if startT is None: startT = minT if stopT is None: stopT = maxT wordTier = wordTier.crop(startT, stopT, "truncated", False) for start, stop, word in wordTier.entryList: if word in skipLabelList: continue subPhoneTier = phoneTier.crop(start, stop, "strict", False) # entry = (start, stop, phone) phoneList = [entry[2] for entry in subPhoneTier.entryList if entry[2] != ''] phoneList = [phoneList, ] try: sylTmp = pronunciationtools.findBestSyllabification(isleDict, word, phoneList) except isletool.WordNotInISLE: print("Word ('%s') not is isle -- skipping syllabification" % word) continue except (pronunciationtools.NullPronunciationError): print("Word ('%s') has no provided pronunciation" % word) continue except AssertionError: print("Unable to syllabify '%s'" % word) continue for syllabificationResultList in sylTmp: stressI = syllabificationResultList[0] stressJ = syllabificationResultList[1] syllableList = syllabificationResultList[2] stressedPhone = None if stressI is not None and stressJ is not None: stressedPhone = syllableList[stressI][stressJ] syllableList[stressI][stressJ] += u"ˈ" i = 0 # print(syllableList) for k, syllable in enumerate(syllableList): # Create the syllable tier entry j = len(syllable) stubEntryList = subPhoneTier.entryList[i:i + j] i += j # The whole syllable was deleted if len(stubEntryList) == 0: continue syllableStart = stubEntryList[0][0] syllableEnd = stubEntryList[-1][1] label = "-".join([entry[2] for entry in stubEntryList]) syllableEntryList.append((syllableStart, syllableEnd, label)) # Create the tonic syllable tier entry if k == stressI: tonicSEntryList.append((syllableStart, syllableEnd, 'T')) # Create the tonic phone tier entry if k == stressI: syllablePhoneTier = phoneTier.crop(syllableStart, syllableEnd, "strict", False) phoneList = [entry for entry in syllablePhoneTier.entryList if entry[2] != ''] justPhones = [phone for _, _, phone in phoneList] cvList = pronunciationtools._prepPronunciation(justPhones) try: tmpStressJ = cvList.index('V') except ValueError: for char in [u'r', u'n', u'l']: if char in cvList: tmpStressJ = cvList.index(char) break phoneStart, phoneEnd = phoneList[tmpStressJ][:2] tonicPEntryList.append((phoneStart, phoneEnd, 'T')) # Create a textgrid with the two syllable-level tiers syllableTier = tgio.IntervalTier('syllable', syllableEntryList, minT, maxT) tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList, minT, maxT) tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList, minT, maxT) syllableTG = tgio.Textgrid() syllableTG.addTier(syllableTier) syllableTG.addTier(tonicSTier) syllableTG.addTier(tonicPTier) return syllableTG
timmahrt/pysle
pysle/praattools.py
syllabifyTextgrid
python
def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): ''' Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress). ''' minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: skipLabelList = [] syllableEntryList = [] tonicSEntryList = [] tonicPEntryList = [] if startT is not None or stopT is not None: if startT is None: startT = minT if stopT is None: stopT = maxT wordTier = wordTier.crop(startT, stopT, "truncated", False) for start, stop, word in wordTier.entryList: if word in skipLabelList: continue subPhoneTier = phoneTier.crop(start, stop, "strict", False) # entry = (start, stop, phone) phoneList = [entry[2] for entry in subPhoneTier.entryList if entry[2] != ''] phoneList = [phoneList, ] try: sylTmp = pronunciationtools.findBestSyllabification(isleDict, word, phoneList) except isletool.WordNotInISLE: print("Word ('%s') not is isle -- skipping syllabification" % word) continue except (pronunciationtools.NullPronunciationError): print("Word ('%s') has no provided pronunciation" % word) continue except AssertionError: print("Unable to syllabify '%s'" % word) continue for syllabificationResultList in sylTmp: stressI = syllabificationResultList[0] stressJ = syllabificationResultList[1] syllableList = syllabificationResultList[2] stressedPhone = None if stressI is not None and stressJ is not None: stressedPhone = syllableList[stressI][stressJ] syllableList[stressI][stressJ] += u"ˈ" i = 0 # print(syllableList) for k, syllable in enumerate(syllableList): # Create the syllable tier entry j = len(syllable) stubEntryList = subPhoneTier.entryList[i:i + j] i += j # The whole syllable was deleted if len(stubEntryList) == 0: continue syllableStart = stubEntryList[0][0] syllableEnd = stubEntryList[-1][1] label = "-".join([entry[2] for entry in stubEntryList]) syllableEntryList.append((syllableStart, syllableEnd, label)) # Create the tonic syllable tier entry if k == stressI: tonicSEntryList.append((syllableStart, syllableEnd, 'T')) # Create the tonic phone tier entry if k == stressI: syllablePhoneTier = phoneTier.crop(syllableStart, syllableEnd, "strict", False) phoneList = [entry for entry in syllablePhoneTier.entryList if entry[2] != ''] justPhones = [phone for _, _, phone in phoneList] cvList = pronunciationtools._prepPronunciation(justPhones) try: tmpStressJ = cvList.index('V') except ValueError: for char in [u'r', u'n', u'l']: if char in cvList: tmpStressJ = cvList.index(char) break phoneStart, phoneEnd = phoneList[tmpStressJ][:2] tonicPEntryList.append((phoneStart, phoneEnd, 'T')) # Create a textgrid with the two syllable-level tiers syllableTier = tgio.IntervalTier('syllable', syllableEntryList, minT, maxT) tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList, minT, maxT) tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList, minT, maxT) syllableTG = tgio.Textgrid() syllableTG.addTier(syllableTier) syllableTG.addTier(tonicSTier) syllableTG.addTier(tonicPTier) return syllableTG
Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress).
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/praattools.py#L226-L354
[ "def findBestSyllabification(isleDict, wordText,\n actualPronListOfLists):\n\n for aPron in actualPronListOfLists:\n if not isinstance(aPron, list):\n raise WrongTypeError(\"The pronunciation list must be a list\"\n \"of lists, even if it only has one sublist.\"\n \"\\ne.g. labyrinth\\n\"\n \"[[l ˈæ . b ɚ . ˌɪ n ɵ], ]\")\n if len(aPron) == 0:\n raise NullPronunciationError(wordText)\n\n try:\n actualPronListOfLists = [[unicode(char, \"utf-8\") for char in row]\n for row in actualPronListOfLists]\n except (NameError, TypeError):\n pass\n\n numWords = len(actualPronListOfLists)\n\n isleWordList = isleDict.lookup(wordText)\n\n\n if len(isleWordList) == numWords:\n retList = []\n for isleWordList, aPron in zip(isleWordList, actualPronListOfLists):\n retList.append(_findBestSyllabification(isleWordList, aPron))\n else:\n raise NumWordsMismatchError(wordText, len(isleWordList))\n\n return retList\n", "def _prepPronunciation(phoneList):\n retList = []\n for phone in phoneList:\n\n # Remove diacritics\n for diacritic in isletool.diacriticList:\n phone = phone.replace(diacritic, u'')\n\n # Unify rhotics\n if 'r' in phone:\n phone = 'r'\n\n phone = phone.lower()\n\n # Unify vowels\n if isletool.isVowel(phone):\n phone = u'V'\n\n # Only represent the string by its first letter\n try:\n phone = phone[0]\n except IndexError:\n raise NullPhoneError()\n\n # Unify vowels (reducing the vowel to one char)\n if isletool.isVowel(phone):\n phone = u'V'\n\n retList.append(phone)\n\n return retList\n" ]
#encoding: utf-8 ''' Created on Oct 22, 2014 @author: tmahrt ''' class OptionalFeatureError(ImportError): def __str__(self): return "ERROR: You must have praatio installed to use pysle.praatTools" try: from praatio import tgio from praatio import praatio_scripts except ImportError: raise OptionalFeatureError() from pysle import isletool from pysle import pronunciationtools def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False): ''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False else: returnVal = True return returnVal tg = praatio_scripts.spellCheckEntries(tg, targetTierName, newTierName, checkFunc, printEntries) return tg def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): ''' Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, 1.5, "he said he likes ketchup"). phoneHelperTierName - creates a tier that is parallel to the word tier. However, the labels are the phones for the word, rather than the word removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTier = tg.tierDict[wordTierName] # Load in the word tier, if it exists: wordEntryList = [] phoneEntryList = [] if wordTier is not None: if removeOverlappingSegments: for startT, stopT, _ in utteranceTier.entryList: wordTier = wordTier.eraseRegion(startT, stopT, 'truncate', False) wordEntryList = wordTier.entryList # Do the naive alignment for startT, stopT, label in utteranceTier.entryList: wordList = label.split() # Get the list of phones in each word superPhoneList = [] numPhones = 0 i = 0 while i < len(wordList): word = wordList[i] try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: wordList.pop(i) continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] superPhoneList.append(phoneList) numPhones += len(phoneList) i += 1 # Get the naive alignment for words, if alignment doesn't # already exist for words subWordEntryList = [] subPhoneEntryList = [] if wordTier is not None: subWordEntryList = wordTier.crop(startT, stopT, "truncated", False).entryList if len(subWordEntryList) == 0: wordStartT = startT phoneDur = (stopT - startT) / float(numPhones) for i, word in enumerate(wordList): phoneListTxt = " ".join(superPhoneList[i]) wordStartT = wordStartT wordEndT = wordStartT + (phoneDur * len(superPhoneList[i])) subWordEntryList.append((wordStartT, wordEndT, word)) subPhoneEntryList.append((wordStartT, wordEndT, phoneListTxt)) wordStartT = wordEndT wordEntryList.extend(subWordEntryList) phoneEntryList.extend(subPhoneEntryList) # Replace or add the word tier newWordTier = tgio.IntervalTier(wordTierName, wordEntryList, tg.minTimestamp, tg.maxTimestamp) if wordTier is not None: tg.replaceTier(wordTierName, newWordTier) else: tg.addTier(newWordTier) # Add the phone tier # This is mainly used as an annotation tier if phoneHelperTierName is not None and len(phoneEntryList) > 0: newPhoneTier = tgio.IntervalTier(phoneHelperTierName, phoneEntryList, tg.minTimestamp, tg.minTimestamp) if phoneHelperTierName in tg.tierNameList: tg.replaceTier(phoneHelperTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False): ''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under labeled utterances ''' wordTier = tg.tierDict[wordTierName] phoneTier = None if phoneTierName in tg.tierNameList: phoneTier = tg.tierDict[phoneTierName] # Load in the phone tier, if it exists: phoneEntryList = [] if phoneTier is not None: if removeOverlappingSegments: for startT, stopT, _ in wordTier.entryList: phoneTier = phoneTier.eraseRegion(startT, stopT, 'truncate', False) phoneEntryList = phoneTier.entryList # Do the naive alignment for wordStartT, wordEndT, word in wordTier.entryList: # Get the list of phones in this word try: firstSyllableList = isleDict.lookup(word)[0][0][0] except isletool.WordNotInISLE: continue phoneList = [phone for syllable in firstSyllableList for phone in syllable] for char in [u'ˈ', u'ˌ']: phoneList = [phone.replace(char, '') for phone in phoneList] # Get the naive alignment for phones, if alignment doesn't # already exist for phones subPhoneEntryList = [] if phoneTier is not None: subPhoneEntryList = phoneTier.crop(wordStartT, wordEndT, "truncated", False).entryList if len(subPhoneEntryList) == 0: phoneDur = (wordEndT - wordStartT) / len(phoneList) phoneStartT = wordStartT for phone in phoneList: phoneEndT = phoneStartT + phoneDur subPhoneEntryList.append((phoneStartT, phoneEndT, phone)) phoneStartT = phoneEndT phoneEntryList.extend(subPhoneEntryList) # Replace or add the phone tier newPhoneTier = tgio.IntervalTier(phoneTierName, phoneEntryList, tg.minTimestamp, tg.maxTimestamp) if phoneTier is not None: tg.replaceTier(phoneTierName, newPhoneTier) else: tg.addTier(newPhoneTier) return tg def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): ''' Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabification of the phone tier and a tier marking word-stress). ''' minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: skipLabelList = [] syllableEntryList = [] tonicSEntryList = [] tonicPEntryList = [] if startT is not None or stopT is not None: if startT is None: startT = minT if stopT is None: stopT = maxT wordTier = wordTier.crop(startT, stopT, "truncated", False) for start, stop, word in wordTier.entryList: if word in skipLabelList: continue subPhoneTier = phoneTier.crop(start, stop, "strict", False) # entry = (start, stop, phone) phoneList = [entry[2] for entry in subPhoneTier.entryList if entry[2] != ''] phoneList = [phoneList, ] try: sylTmp = pronunciationtools.findBestSyllabification(isleDict, word, phoneList) except isletool.WordNotInISLE: print("Word ('%s') not is isle -- skipping syllabification" % word) continue except (pronunciationtools.NullPronunciationError): print("Word ('%s') has no provided pronunciation" % word) continue except AssertionError: print("Unable to syllabify '%s'" % word) continue for syllabificationResultList in sylTmp: stressI = syllabificationResultList[0] stressJ = syllabificationResultList[1] syllableList = syllabificationResultList[2] stressedPhone = None if stressI is not None and stressJ is not None: stressedPhone = syllableList[stressI][stressJ] syllableList[stressI][stressJ] += u"ˈ" i = 0 # print(syllableList) for k, syllable in enumerate(syllableList): # Create the syllable tier entry j = len(syllable) stubEntryList = subPhoneTier.entryList[i:i + j] i += j # The whole syllable was deleted if len(stubEntryList) == 0: continue syllableStart = stubEntryList[0][0] syllableEnd = stubEntryList[-1][1] label = "-".join([entry[2] for entry in stubEntryList]) syllableEntryList.append((syllableStart, syllableEnd, label)) # Create the tonic syllable tier entry if k == stressI: tonicSEntryList.append((syllableStart, syllableEnd, 'T')) # Create the tonic phone tier entry if k == stressI: syllablePhoneTier = phoneTier.crop(syllableStart, syllableEnd, "strict", False) phoneList = [entry for entry in syllablePhoneTier.entryList if entry[2] != ''] justPhones = [phone for _, _, phone in phoneList] cvList = pronunciationtools._prepPronunciation(justPhones) try: tmpStressJ = cvList.index('V') except ValueError: for char in [u'r', u'n', u'l']: if char in cvList: tmpStressJ = cvList.index(char) break phoneStart, phoneEnd = phoneList[tmpStressJ][:2] tonicPEntryList.append((phoneStart, phoneEnd, 'T')) # Create a textgrid with the two syllable-level tiers syllableTier = tgio.IntervalTier('syllable', syllableEntryList, minT, maxT) tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList, minT, maxT) tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList, minT, maxT) syllableTG = tgio.Textgrid() syllableTG.addTier(syllableTier) syllableTG.addTier(tonicSTier) syllableTG.addTier(tonicPTier) return syllableTG
timmahrt/pysle
pysle/isletool.py
_prepRESearchStr
python
def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr
Prepares a user's RE string for a search
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L125-L246
null
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
search
python
def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList
Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L249-L329
[ "def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok',\n spanSyllable='ok', stressedSyllable='ok'):\n '''\n Prepares a user's RE string for a search\n '''\n\n # Protect sounds that are two characters\n # After this we can assume that each character represents a sound\n # (We'll revert back when we're done processing the RE)\n replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'),\n (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'),\n (u'ɔi', u'$')]\n\n # Add to the replList\n currentReplNum = 0\n startI = 0\n for left, right in (('(', ')'), ('[', ']')):\n while True:\n try:\n i = matchStr.index(left, startI)\n except ValueError:\n break\n j = matchStr.index(right, i) + 1\n replList.append((matchStr[i:j], str(currentReplNum)))\n currentReplNum += 1\n startI = j\n\n for charA, charB in replList:\n matchStr = matchStr.replace(charA, charB)\n\n # Characters to check between all other characters\n # Don't check between all other characters if the character is already\n # in the search string or\n interleaveStr = None\n stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only')\n spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only')\n if stressOpt and spanOpt:\n interleaveStr = u\"\\.?ˈ?\"\n elif stressOpt:\n interleaveStr = u\"ˈ?\"\n elif spanOpt:\n interleaveStr = u\"\\.?\"\n\n if interleaveStr is not None:\n matchStr = interleaveStr.join(matchStr)\n\n # Setting search boundaries\n # We search on '[^\\.#]' and not '.' so that the search doesn't span\n # multiple syllables or words\n if wordInitial == 'only':\n matchStr = u'#' + matchStr\n elif wordInitial == 'no':\n # Match the closest preceeding syllable. If there is none, look\n # for word boundary plus at least one other character\n matchStr = u'(?:\\.[^\\.#]*?|#[^\\.#]+?)' + matchStr\n else:\n matchStr = u'[#\\.][^\\.#]*?' + matchStr\n\n if wordFinal == 'only':\n matchStr = matchStr + u'#'\n elif wordFinal == 'no':\n matchStr = matchStr + u\"(?:[^\\.#]*?\\.|[^\\.#]+?#)\"\n else:\n matchStr = matchStr + u'[^\\.#]*?[#\\.]'\n\n # For sounds that are designated two characters, prevent\n # detecting those sounds if the user wanted a sound\n # designated by one of the contained characters\n\n # Forward search ('a' and not 'ab')\n insertList = []\n for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'),\n (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]:\n startI = 0\n while True:\n try:\n i = matchStr.index(charA, startI)\n except ValueError:\n break\n if matchStr[i + 1] != charB:\n forwardStr = u'(?!%s)' % charB\n# matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:]\n startI = i + 1 + len(forwardStr)\n insertList.append((i + 1, forwardStr))\n\n # Backward search ('b' and not 'ab')\n for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'),\n (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]:\n startI = 0\n while True:\n try:\n i = matchStr.index(charB, startI)\n except ValueError:\n break\n if matchStr[i - 1] != charA:\n backStr = u'(?<!%s)' % charA\n# matchStr = matchStr[:i] + backStr + matchStr[i:]\n startI = i + 1 + len(backStr)\n insertList.append((i, backStr))\n\n insertList.sort()\n for i, insertStr in insertList[::-1]:\n matchStr = matchStr[:i] + insertStr + matchStr[i:]\n\n # Revert the special sounds back from 1 character to 2 characters\n for charA, charB in replList:\n matchStr = matchStr.replace(charB, charA)\n\n # Replace special characters\n replDict = {\"D\": u\"(?:t(?!ʃ)|d(?!ʒ)|[sz])\", # dentals\n \"F\": u\"[ʃʒfvszɵðh]\", # fricatives\n \"S\": u\"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])\", # stops\n \"N\": u\"[nmŋ]\", # nasals\n \"R\": u\"[rɝɚ]\", # rhotics\n \"V\": u\"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?\", # vowels\n \"B\": u\"\\.\", # syllable boundary\n }\n\n for char, replStr in replDict.items():\n matchStr = matchStr.replace(char, replStr)\n\n return matchStr\n" ]
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
_parsePronunciation
python
def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList
Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L332-L360
null
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
getNumPhones
python
def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount
Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L363-L398
[ "def lookup(self, word):\n '''\n Lookup a word and receive a list of syllables and stressInfo\n\n Output example for the word 'another' which has two pronunciations\n [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),\n ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]\n '''\n\n # All words must be lowercase with no extraneous whitespace\n word = word.lower()\n word = word.strip()\n\n pronList = self.data.get(word, None)\n\n if pronList is None:\n raise WordNotInISLE(word)\n else:\n pronList = [_parsePronunciation(pronunciationStr)\n for pronunciationStr, _ in pronList]\n pronList = list(zip(*pronList))\n\n return pronList\n" ]
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
findOODWords
python
def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList
Returns all of the out-of-dictionary words found in a list of utterances
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L401-L415
[ "def lookup(self, word):\n '''\n Lookup a word and receive a list of syllables and stressInfo\n\n Output example for the word 'another' which has two pronunciations\n [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),\n ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]\n '''\n\n # All words must be lowercase with no extraneous whitespace\n word = word.lower()\n word = word.strip()\n\n pronList = self.data.get(word, None)\n\n if pronList is None:\n raise WordNotInISLE(word)\n else:\n pronList = [_parsePronunciation(pronunciationStr)\n for pronunciationStr, _ in pronList]\n pronList = list(zip(*pronList))\n\n return pronList\n" ]
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
autopair
python
def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L418-L443
null
#encoding: utf-8 ''' Created on Oct 11, 2012 @author: timmahrt ''' import io import re charList = [u'#', u'.', u'aʊ', u'b', u'd', u'dʒ', u'ei', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'oʊ', u'p', u'r', u's', u't', u'tʃ', u'u', u'v', u'w', u'z', u'æ', u'ð', u'ŋ', u'ɑ', u'ɑɪ', u'ɔ', u'ɔi', u'ə', u'ɚ', u'ɛ', u'ɝ', u'ɪ', u'ɵ', u'ɹ', u'ʃ', u'ʊ', u'ʒ', u'æ', u'ʌ', ] diacriticList = [u'˺', u'ˌ', u'̩', u'̃', u'ˈ', ] monophthongList = [u'u', u'æ', u'ɑ', u'ɔ', u'ə', u'i', u'ɛ', u'ɪ', u'ʊ', u'ʌ', u'a', u'e', u'o', ] diphthongList = [u'ɑɪ', u'aʊ', u'ei', u'ɔi', u'oʊ', u'ae'] syllabicConsonantList = [u'l̩', u'n̩', u'ɚ', u'ɝ'] # ISLE words are part of speech tagged using the Penn Part of Speech Tagset posList = ['cc', 'cd', 'dt', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nnd', 'nnp', 'nnps', 'nns', 'pdt', 'prp', 'punc', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'vpb', 'wdt', 'wp', 'wrb'] vowelList = monophthongList + diphthongList + syllabicConsonantList def isVowel(char): return any([vowel in char for vowel in vowelList]) def sequenceMatch(matchChar, searchStr): return matchChar in searchStr class WordNotInISLE(Exception): def __init__(self, word): super(WordNotInISLE, self).__init__() self.word = word def __str__(self): return ("Word '%s' not in ISLE dictionary. " "Please add it to continue." % self.word) class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos) def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'll revert back when we're done processing the RE) replList = [(u'ei', u'9'), (u'tʃ', u'='), (u'oʊ', u'~'), (u'dʒ', u'@'), (u'aʊ', u'%'), (u'ɑɪ', u'&'), (u'ɔi', u'$')] # Add to the replList currentReplNum = 0 startI = 0 for left, right in (('(', ')'), ('[', ']')): while True: try: i = matchStr.index(left, startI) except ValueError: break j = matchStr.index(right, i) + 1 replList.append((matchStr[i:j], str(currentReplNum))) currentReplNum += 1 startI = j for charA, charB in replList: matchStr = matchStr.replace(charA, charB) # Characters to check between all other characters # Don't check between all other characters if the character is already # in the search string or interleaveStr = None stressOpt = (stressedSyllable == 'ok' or stressedSyllable == 'only') spanOpt = (spanSyllable == 'ok' or spanSyllable == 'only') if stressOpt and spanOpt: interleaveStr = u"\.?ˈ?" elif stressOpt: interleaveStr = u"ˈ?" elif spanOpt: interleaveStr = u"\.?" if interleaveStr is not None: matchStr = interleaveStr.join(matchStr) # Setting search boundaries # We search on '[^\.#]' and not '.' so that the search doesn't span # multiple syllables or words if wordInitial == 'only': matchStr = u'#' + matchStr elif wordInitial == 'no': # Match the closest preceeding syllable. If there is none, look # for word boundary plus at least one other character matchStr = u'(?:\.[^\.#]*?|#[^\.#]+?)' + matchStr else: matchStr = u'[#\.][^\.#]*?' + matchStr if wordFinal == 'only': matchStr = matchStr + u'#' elif wordFinal == 'no': matchStr = matchStr + u"(?:[^\.#]*?\.|[^\.#]+?#)" else: matchStr = matchStr + u'[^\.#]*?[#\.]' # For sounds that are designated two characters, prevent # detecting those sounds if the user wanted a sound # designated by one of the contained characters # Forward search ('a' and not 'ab') insertList = [] for charA, charB in [(u'e', u'i'), (u't', u'ʃ'), (u'd', u'ʒ'), (u'o', u'ʊ'), (u'a', u'ʊ|ɪ'), (u'ɔ', u'i'), ]: startI = 0 while True: try: i = matchStr.index(charA, startI) except ValueError: break if matchStr[i + 1] != charB: forwardStr = u'(?!%s)' % charB # matchStr = matchStr[:i + 1] + forwardStr + matchStr[i + 1:] startI = i + 1 + len(forwardStr) insertList.append((i + 1, forwardStr)) # Backward search ('b' and not 'ab') for charA, charB in [(u't', u'ʃ'), (u'd', u'ʒ'), (u'a|o', u'ʊ'), (u'e|ɔ', u'i'), (u'ɑ' u'ɪ'), ]: startI = 0 while True: try: i = matchStr.index(charB, startI) except ValueError: break if matchStr[i - 1] != charA: backStr = u'(?<!%s)' % charA # matchStr = matchStr[:i] + backStr + matchStr[i:] startI = i + 1 + len(backStr) insertList.append((i, backStr)) insertList.sort() for i, insertStr in insertList[::-1]: matchStr = matchStr[:i] + insertStr + matchStr[i:] # Revert the special sounds back from 1 character to 2 characters for charA, charB in replList: matchStr = matchStr.replace(charB, charA) # Replace special characters replDict = {"D": u"(?:t(?!ʃ)|d(?!ʒ)|[sz])", # dentals "F": u"[ʃʒfvszɵðh]", # fricatives "S": u"(?:t(?!ʃ)|d(?!ʒ)|[pbkg])", # stops "N": u"[nmŋ]", # nasals "R": u"[rɝɚ]", # rhotics "V": u"(?:aʊ|ei|oʊ|ɑɪ|ɔi|[iuæɑɔəɛɪʊʌ]):?", # vowels "B": u"\.", # syllable boundary } for char, replStr in replDict.items(): matchStr = matchStr.replace(char, replStr) return matchStr def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible tags Special search characters: 'D' - any dental; 'F' - any fricative; 'S' - any stop 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic '#' - word boundary 'B' - syllable boundary '.' - anything For advanced queries: Regular expression syntax applies, so if you wanted to search for any word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc. ''' # Run search for words matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) compiledRE = re.compile(matchStr) retList = [] for word, pronList in searchList: newPronList = [] for pron, posList in pronList: searchPron = pron.replace(",", "").replace(" ", "") # Search for pos if pos is not None: if pos not in posList: continue # Ignore diacritics for now: for diacritic in diacriticList: if diacritic not in matchStr: searchPron = searchPron.replace(diacritic, "") if numSyllables is not None: if numSyllables != searchPron.count('.') + 1: continue # Is this a compound word? if multiword == 'only': if searchPron.count('#') == 2: continue elif multiword == 'no': if searchPron.count('#') > 2: continue matchList = compiledRE.findall(searchPron) if len(matchList) > 0: if stressedSyllable == 'only': if all([u"ˈ" not in match for match in matchList]): continue if stressedSyllable == 'no': if all([u"ˈ" in match for match in matchList]): continue # For syllable spanning, we check if there is a syllable # marker inside (not at the border) of the match. if spanSyllable == 'only': if all(["." not in txt[1:-1] for txt in matchList]): continue if spanSyllable == 'no': if all(["." in txt[1:-1] for txt in matchList]): continue newPronList.append((pron, posList)) if len(newPronList) > 0: retList.append((word, newPronList)) retList.sort() return retList def _parsePronunciation(pronunciationStr): ''' Parses the pronunciation string Returns the list of syllables and a list of primary and secondary stress locations ''' retList = [] for syllableTxt in pronunciationStr.split("#"): if syllableTxt == "": continue syllableList = [x.split() for x in syllableTxt.split(' . ')] # Find stress stressedSyllableList = [] stressedPhoneList = [] for i, syllable in enumerate(syllableList): for j, phone in enumerate(syllable): if u"ˈ" in phone: stressedSyllableList.insert(0, i) stressedPhoneList.insert(0, j) break elif u'ˌ' in phone: stressedSyllableList.append(i) stressedPhoneList.append(j) retList.append((syllableList, stressedSyllableList, stressedPhoneList)) return retList def getNumPhones(isleDict, word, maxFlag): ''' Get the number of syllables and phones in this word If maxFlag=True, use the longest pronunciation. Otherwise, take the average length. ''' phoneCount = 0 syllableCount = 0 syllableCountList = [] phoneCountList = [] wordList = isleDict.lookup(word) entryList = zip(*wordList) for lookupResultList in entryList: syllableList = [] for wordSyllableList in lookupResultList: syllableList.extend(wordSyllableList) syllableCountList.append(len(syllableList)) phoneCountList.append(len([phon for phoneList in syllableList for phon in phoneList])) # The average number of phones for all possible pronunciations # of this word if maxFlag is True: syllableCount += max(syllableCountList) phoneCount += max(phoneCountList) else: syllableCount += (sum(syllableCountList) / float(len(syllableCountList))) phoneCount += sum(phoneCountList) / float(len(phoneCountList)) return syllableCount, phoneCount def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(set(oodList)) oodList.sort() return oodList def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the dictionary ''' newWordList = [("%s_%s" % (wordList[i], wordList[i + 1]), i) for i in range(0, len(wordList) - 1)] sentenceList = [] indexList = [] for word, i in newWordList: if word in isleDict.data: sentenceList.append(wordList[:i] + [word, ] + wordList[i + 1:]) indexList.append(i) return sentenceList, indexList
timmahrt/pysle
pysle/isletool.py
LexicalTool._buildDict
python
def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict
Builds the isle textfile into a dictionary for fast searching
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L66-L86
null
class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos)
timmahrt/pysle
pysle/isletool.py
LexicalTool.lookup
python
def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList
Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L88-L110
null
class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos)
timmahrt/pysle
pysle/isletool.py
LexicalTool.search
python
def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(), matchStr, numSyllables=numSyllables, wordInitial=wordInitial, wordFinal=wordFinal, spanSyllable=spanSyllable, stressedSyllable=stressedSyllable, multiword=multiword, pos=pos)
for help on isletool.LexicalTool.search(), see see isletool.search()
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/isletool.py#L112-L122
[ "def search(searchList, matchStr, numSyllables=None, wordInitial='ok',\n wordFinal='ok', spanSyllable='ok', stressedSyllable='ok',\n multiword='ok', pos=None):\n '''\n Searches for matching words in the dictionary with regular expressions\n\n wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword\n can take three different values: 'ok', 'only', or 'no'.\n\n pos: a tag in the Penn Part of Speech tagset\n see isletool.posList for the full list of possible tags\n\n Special search characters:\n 'D' - any dental; 'F' - any fricative; 'S' - any stop\n 'V' - any vowel; 'N' - any nasal; 'R' - any rhotic\n '#' - word boundary\n 'B' - syllable boundary\n '.' - anything\n\n For advanced queries:\n Regular expression syntax applies, so if you wanted to search for any\n word ending with a vowel or rhotic, matchStr = '(?:VR)#', '[VR]#', etc.\n '''\n # Run search for words\n\n matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal,\n spanSyllable, stressedSyllable)\n\n compiledRE = re.compile(matchStr)\n retList = []\n for word, pronList in searchList:\n newPronList = []\n for pron, posList in pronList:\n searchPron = pron.replace(\",\", \"\").replace(\" \", \"\")\n\n # Search for pos\n if pos is not None:\n if pos not in posList:\n continue\n\n # Ignore diacritics for now:\n for diacritic in diacriticList:\n if diacritic not in matchStr:\n searchPron = searchPron.replace(diacritic, \"\")\n\n if numSyllables is not None:\n if numSyllables != searchPron.count('.') + 1:\n continue\n\n # Is this a compound word?\n if multiword == 'only':\n if searchPron.count('#') == 2:\n continue\n elif multiword == 'no':\n if searchPron.count('#') > 2:\n continue\n\n matchList = compiledRE.findall(searchPron)\n if len(matchList) > 0:\n if stressedSyllable == 'only':\n if all([u\"ˈ\" not in match for match in matchList]):\n continue\n if stressedSyllable == 'no':\n if all([u\"ˈ\" in match for match in matchList]):\n continue\n\n # For syllable spanning, we check if there is a syllable\n # marker inside (not at the border) of the match.\n if spanSyllable == 'only':\n if all([\".\" not in txt[1:-1] for txt in matchList]):\n continue\n if spanSyllable == 'no':\n if all([\".\" in txt[1:-1] for txt in matchList]):\n continue\n newPronList.append((pron, posList))\n\n if len(newPronList) > 0:\n retList.append((word, newPronList))\n\n retList.sort()\n return retList\n" ]
class LexicalTool(): def __init__(self, islePath): ''' self.data: the pronunciation data {(word, pronunciationList),} self.dataExtra: pos and other info {(word, infoList),} ''' self.islePath = islePath self.data = self._buildDict() def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pronunciation = row.split(" ", 1) word, extraInfo = word.split("(", 1) extraInfo = extraInfo.replace(")", "") extraInfoList = [segment for segment in extraInfo.split(",") if ("_" not in segment and "+" not in segment and ':' not in segment and segment != '')] lexDict.setdefault(word, []) lexDict[word].append((pronunciation, extraInfoList)) return lexDict def lookup(self, word): ''' Lookup a word and receive a list of syllables and stressInfo Output example for the word 'another' which has two pronunciations [(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]), ([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] ''' # All words must be lowercase with no extraneous whitespace word = word.lower() word = word.strip() pronList = self.data.get(word, None) if pronList is None: raise WordNotInISLE(word) else: pronList = [_parsePronunciation(pronunciationStr) for pronunciationStr, _ in pronList] pronList = list(zip(*pronList)) return pronList
timmahrt/pysle
pysle/pronunciationtools.py
_adjustSyllabification
python
def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList
Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L132-L165
null
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
_findBestPronunciation
python
def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex)
Words may have multiple candidates in ISLE; returns the 'optimal' one.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L168-L235
[ "def _prepPronunciation(phoneList):\n retList = []\n for phone in phoneList:\n\n # Remove diacritics\n for diacritic in isletool.diacriticList:\n phone = phone.replace(diacritic, u'')\n\n # Unify rhotics\n if 'r' in phone:\n phone = 'r'\n\n phone = phone.lower()\n\n # Unify vowels\n if isletool.isVowel(phone):\n phone = u'V'\n\n # Only represent the string by its first letter\n try:\n phone = phone[0]\n except IndexError:\n raise NullPhoneError()\n\n # Unify vowels (reducing the vowel to one char)\n if isletool.isVowel(phone):\n phone = u'V'\n\n retList.append(phone)\n\n return retList\n", "def _adjustSyllabification(adjustedPhoneList, syllableList):\n '''\n Inserts spaces into a syllable if needed\n\n Originally the phone list and syllable list contained the same number\n of phones. But the adjustedPhoneList may have some insertions which are\n not accounted for in the syllableList.\n '''\n i = 0\n retSyllableList = []\n for syllableNum, syllable in enumerate(syllableList):\n j = len(syllable)\n if syllableNum == len(syllableList) - 1:\n j = len(adjustedPhoneList) - i\n tmpPhoneList = adjustedPhoneList[i:i + j]\n numBlanks = -1\n phoneList = tmpPhoneList[:]\n while numBlanks != 0:\n\n numBlanks = tmpPhoneList.count(u\"''\")\n if numBlanks > 0:\n tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks]\n phoneList.extend(tmpPhoneList)\n j += numBlanks\n\n for k, phone in enumerate(phoneList):\n if phone == u\"''\":\n syllable.insert(k, u\"''\")\n\n i += j\n\n retSyllableList.append(syllable)\n\n return retSyllableList\n", "def alignPronunciations(pronI, pronA):\n '''\n Align the phones in two pronunciations\n '''\n\n # First prep the two pronunctions\n pronI = [char for char in pronI]\n pronA = [char for char in pronA]\n\n # Remove any elements not in the other list (but maintain order)\n pronITmp = pronI\n pronATmp = pronA\n\n # Find the longest sequence\n sequence = _lcs(pronITmp, pronATmp)\n\n # Find the index of the sequence\n # TODO: investigate ambiguous cases\n startA = 0\n startI = 0\n sequenceIndexListA = []\n sequenceIndexListI = []\n for phone in sequence:\n startA = pronA.index(phone, startA)\n startI = pronI.index(phone, startI)\n\n sequenceIndexListA.append(startA)\n sequenceIndexListI.append(startI)\n\n # An index on the tail of both will be used to create output strings\n # of the same length\n sequenceIndexListA.append(len(pronA))\n sequenceIndexListI.append(len(pronI))\n\n # Fill in any blanks such that the sequential items have the same\n # index and the two strings are the same length\n for x in range(len(sequenceIndexListA)):\n indexA = sequenceIndexListA[x]\n indexI = sequenceIndexListI[x]\n if indexA < indexI:\n for x in range(indexI - indexA):\n pronA.insert(indexA, \"''\")\n sequenceIndexListA = [val + indexI - indexA\n for val in sequenceIndexListA]\n elif indexA > indexI:\n for x in range(indexA - indexI):\n pronI.insert(indexI, \"''\")\n sequenceIndexListI = [val + indexA - indexI\n for val in sequenceIndexListI]\n\n return pronI, pronA\n" ]
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
_syllabifyPhones
python
def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList
Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L238-L258
null
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
alignPronunciations
python
def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA
Align the phones in two pronunciations
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L261-L311
[ "def _lcs(xs, ys):\n nx, ny = len(xs), len(ys)\n if nx == 0:\n return []\n elif nx == 1:\n return [xs[0]] if xs[0] in ys else []\n else:\n i = nx // 2\n xb, xe = xs[:i], xs[i:]\n ll_b = _lcs_lens(xb, ys)\n ll_e = _lcs_lens(xe[::-1], ys[::-1])\n _, k = max((ll_b[j] + ll_e[ny - j], j)\n for j in range(ny + 1))\n yb, ye = ys[:k], ys[k:]\n return _lcs(xb, yb) + _lcs(xe, ye)\n" ]
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
_findBestSyllabification
python
def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList)
Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation.
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L347-L387
[ "def _findBestPronunciation(isleWordList, aPron):\n '''\n Words may have multiple candidates in ISLE; returns the 'optimal' one.\n '''\n\n aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory\n\n numDiffList = []\n withStress = []\n i = 0\n alignedSyllabificationList = []\n alignedActualPronunciationList = []\n for wordTuple in isleWordList:\n aPronMap = copy.deepcopy(aPron)\n syllableList = wordTuple[0] # syllableList, stressList\n\n iP = [phone for phoneList in syllableList for phone in phoneList]\n iP = _prepPronunciation(iP)\n\n alignedIP, alignedAP = alignPronunciations(iP, aP)\n\n # Remapping to actual phones\n# alignedAP = [origPronDict.get(phon, u\"''\") for phon in alignedAP]\n alignedAP = [aPronMap.pop(0) if phon != u\"''\" else u\"''\"\n for phon in alignedAP]\n alignedActualPronunciationList.append(alignedAP)\n\n # Adjusting the syllabification for differences between the dictionary\n # pronunciation and the actual pronunciation\n alignedSyllabification = _adjustSyllabification(alignedIP,\n syllableList)\n alignedSyllabificationList.append(alignedSyllabification)\n\n # Count the number of misalignments between the two\n numDiff = alignedIP.count(u\"''\") + alignedAP.count(u\"''\")\n numDiffList.append(numDiff)\n\n # Is there stress in this word\n hasStress = False\n for syllable in syllableList:\n for phone in syllable:\n hasStress = u\"ˈ\" in phone or hasStress\n\n if hasStress:\n withStress.append(i)\n i += 1\n\n # Return the pronunciation that had the fewest differences\n # to the actual pronunciation\n minDiff = min(numDiffList)\n\n # When there are multiple candidates that have the minimum number\n # of differences, prefer one that has stress in it\n bestIndex = None\n bestIsStressed = None\n for i, numDiff in enumerate(numDiffList):\n if numDiff != minDiff:\n continue\n if bestIndex is None:\n bestIndex = i\n bestIsStressed = i in withStress\n else:\n if not bestIsStressed and i in withStress:\n bestIndex = i\n bestIsStressed = True\n\n return (isleWordList, alignedActualPronunciationList,\n alignedSyllabificationList, bestIndex)\n", "def _syllabifyPhones(phoneList, syllableList):\n '''\n Given a phone list and a syllable list, syllabify the phones\n\n Typically used by findBestSyllabification which first aligns the phoneList\n with a dictionary phoneList and then uses the dictionary syllabification\n to syllabify the input phoneList.\n '''\n\n numPhoneList = [len(syllable) for syllable in syllableList]\n\n start = 0\n syllabifiedList = []\n for end in numPhoneList:\n\n syllable = phoneList[start:start + end]\n syllabifiedList.append(syllable)\n\n start += end\n\n return syllabifiedList\n", "def _getSyllableNucleus(phoneList):\n '''\n Given the phones in a syllable, retrieves the vowel index\n '''\n cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList]\n\n vowelCount = cvList.count('V')\n if vowelCount > 1:\n raise TooManyVowelsInSyllable(phoneList, cvList)\n\n if vowelCount == 1:\n stressI = cvList.index('V')\n else:\n stressI = None\n\n return stressI\n" ]
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
_getSyllableNucleus
python
def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI
Given the phones in a syllable, retrieves the vowel index
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L390-L405
null
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
timmahrt/pysle
pysle/pronunciationtools.py
findClosestPronunciation
python
def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
Find the closest dictionary pronunciation to a provided pronunciation
train
https://github.com/timmahrt/pysle/blob/da7c3d9ebdc01647be845f442b6f072a854eba3b/pysle/pronunciationtools.py#L408-L417
[ "def _findBestPronunciation(isleWordList, aPron):\n '''\n Words may have multiple candidates in ISLE; returns the 'optimal' one.\n '''\n\n aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory\n\n numDiffList = []\n withStress = []\n i = 0\n alignedSyllabificationList = []\n alignedActualPronunciationList = []\n for wordTuple in isleWordList:\n aPronMap = copy.deepcopy(aPron)\n syllableList = wordTuple[0] # syllableList, stressList\n\n iP = [phone for phoneList in syllableList for phone in phoneList]\n iP = _prepPronunciation(iP)\n\n alignedIP, alignedAP = alignPronunciations(iP, aP)\n\n # Remapping to actual phones\n# alignedAP = [origPronDict.get(phon, u\"''\") for phon in alignedAP]\n alignedAP = [aPronMap.pop(0) if phon != u\"''\" else u\"''\"\n for phon in alignedAP]\n alignedActualPronunciationList.append(alignedAP)\n\n # Adjusting the syllabification for differences between the dictionary\n # pronunciation and the actual pronunciation\n alignedSyllabification = _adjustSyllabification(alignedIP,\n syllableList)\n alignedSyllabificationList.append(alignedSyllabification)\n\n # Count the number of misalignments between the two\n numDiff = alignedIP.count(u\"''\") + alignedAP.count(u\"''\")\n numDiffList.append(numDiff)\n\n # Is there stress in this word\n hasStress = False\n for syllable in syllableList:\n for phone in syllable:\n hasStress = u\"ˈ\" in phone or hasStress\n\n if hasStress:\n withStress.append(i)\n i += 1\n\n # Return the pronunciation that had the fewest differences\n # to the actual pronunciation\n minDiff = min(numDiffList)\n\n # When there are multiple candidates that have the minimum number\n # of differences, prefer one that has stress in it\n bestIndex = None\n bestIsStressed = None\n for i, numDiff in enumerate(numDiffList):\n if numDiff != minDiff:\n continue\n if bestIndex is None:\n bestIndex = i\n bestIsStressed = i in withStress\n else:\n if not bestIsStressed and i in withStress:\n bestIndex = i\n bestIsStressed = True\n\n return (isleWordList, alignedActualPronunciationList,\n alignedSyllabificationList, bestIndex)\n" ]
#encoding: utf-8 ''' Created on Oct 15, 2014 @author: tmahrt ''' import itertools import copy from pysle import isletool class TooManyVowelsInSyllable(Exception): def __init__(self, syllable, syllableCVMapped): super(TooManyVowelsInSyllable, self).__init__() self.syllable = syllable self.syllableCVMapped = syllableCVMapped def __str__(self): errStr = ("Error: syllable '%s' found to have more than " "one vowel.\n This was the CV mapping: '%s'") syllableStr = u"".join(self.syllable) syllableCVStr = u"".join(self.syllableCVMapped) return errStr % (syllableStr, syllableCVStr) class NumWordsMismatchError(Exception): def __init__(self, word, numMatches): super(NumWordsMismatchError, self).__init__() self.word = word self.numMatches = numMatches def __str__(self): errStr = ("Error: %d matches found in isleDict for '%s'.\n" "Only 1 match allowed--likely you need to break" "up your query text into separate words.") return errStr % (self.numMatches, self.word) class WrongTypeError(Exception): def __init__(self, errMsg): super(WrongTypeError, self).__init__() self.str = errMsg def __str__(self): return self.str class NullPronunciationError(Exception): def __init__(self, word): super(NullPronunciationError, self).__init__() self.word = word def __str__(self): return "No pronunciation given for word '%s'" % self.word class NullPhoneError(Exception): def __str(self): return "Received an empty phone in the pronunciation list" def _lcs_lens(xs, ys): curr = list(itertools.repeat(0, 1 + len(ys))) for x in xs: prev = list(curr) for i, y in enumerate(ys): if x == y: curr[i + 1] = prev[i] + 1 else: curr[i + 1] = max(curr[i], prev[i + 1]) return curr def _lcs(xs, ys): nx, ny = len(xs), len(ys) if nx == 0: return [] elif nx == 1: return [xs[0]] if xs[0] in ys else [] else: i = nx // 2 xb, xe = xs[:i], xs[i:] ll_b = _lcs_lens(xb, ys) ll_e = _lcs_lens(xe[::-1], ys[::-1]) _, k = max((ll_b[j] + ll_e[ny - j], j) for j in range(ny + 1)) yb, ye = ys[:k], ys[k:] return _lcs(xb, yb) + _lcs(xe, ye) def _prepPronunciation(phoneList): retList = [] for phone in phoneList: # Remove diacritics for diacritic in isletool.diacriticList: phone = phone.replace(diacritic, u'') # Unify rhotics if 'r' in phone: phone = 'r' phone = phone.lower() # Unify vowels if isletool.isVowel(phone): phone = u'V' # Only represent the string by its first letter try: phone = phone[0] except IndexError: raise NullPhoneError() # Unify vowels (reducing the vowel to one char) if isletool.isVowel(phone): phone = u'V' retList.append(phone) return retList def _adjustSyllabification(adjustedPhoneList, syllableList): ''' Inserts spaces into a syllable if needed Originally the phone list and syllable list contained the same number of phones. But the adjustedPhoneList may have some insertions which are not accounted for in the syllableList. ''' i = 0 retSyllableList = [] for syllableNum, syllable in enumerate(syllableList): j = len(syllable) if syllableNum == len(syllableList) - 1: j = len(adjustedPhoneList) - i tmpPhoneList = adjustedPhoneList[i:i + j] numBlanks = -1 phoneList = tmpPhoneList[:] while numBlanks != 0: numBlanks = tmpPhoneList.count(u"''") if numBlanks > 0: tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks] phoneList.extend(tmpPhoneList) j += numBlanks for k, phone in enumerate(phoneList): if phone == u"''": syllable.insert(k, u"''") i += j retSyllableList.append(syllable) return retSyllableList def _findBestPronunciation(isleWordList, aPron): ''' Words may have multiple candidates in ISLE; returns the 'optimal' one. ''' aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory numDiffList = [] withStress = [] i = 0 alignedSyllabificationList = [] alignedActualPronunciationList = [] for wordTuple in isleWordList: aPronMap = copy.deepcopy(aPron) syllableList = wordTuple[0] # syllableList, stressList iP = [phone for phoneList in syllableList for phone in phoneList] iP = _prepPronunciation(iP) alignedIP, alignedAP = alignPronunciations(iP, aP) # Remapping to actual phones # alignedAP = [origPronDict.get(phon, u"''") for phon in alignedAP] alignedAP = [aPronMap.pop(0) if phon != u"''" else u"''" for phon in alignedAP] alignedActualPronunciationList.append(alignedAP) # Adjusting the syllabification for differences between the dictionary # pronunciation and the actual pronunciation alignedSyllabification = _adjustSyllabification(alignedIP, syllableList) alignedSyllabificationList.append(alignedSyllabification) # Count the number of misalignments between the two numDiff = alignedIP.count(u"''") + alignedAP.count(u"''") numDiffList.append(numDiff) # Is there stress in this word hasStress = False for syllable in syllableList: for phone in syllable: hasStress = u"ˈ" in phone or hasStress if hasStress: withStress.append(i) i += 1 # Return the pronunciation that had the fewest differences # to the actual pronunciation minDiff = min(numDiffList) # When there are multiple candidates that have the minimum number # of differences, prefer one that has stress in it bestIndex = None bestIsStressed = None for i, numDiff in enumerate(numDiffList): if numDiff != minDiff: continue if bestIndex is None: bestIndex = i bestIsStressed = i in withStress else: if not bestIsStressed and i in withStress: bestIndex = i bestIsStressed = True return (isleWordList, alignedActualPronunciationList, alignedSyllabificationList, bestIndex) def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ''' numPhoneList = [len(syllable) for syllable in syllableList] start = 0 syllabifiedList = [] for end in numPhoneList: syllable = phoneList[start:start + end] syllabifiedList.append(syllable) start += end return syllabifiedList def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronATmp = pronA # Find the longest sequence sequence = _lcs(pronITmp, pronATmp) # Find the index of the sequence # TODO: investigate ambiguous cases startA = 0 startI = 0 sequenceIndexListA = [] sequenceIndexListI = [] for phone in sequence: startA = pronA.index(phone, startA) startI = pronI.index(phone, startI) sequenceIndexListA.append(startA) sequenceIndexListI.append(startI) # An index on the tail of both will be used to create output strings # of the same length sequenceIndexListA.append(len(pronA)) sequenceIndexListI.append(len(pronI)) # Fill in any blanks such that the sequential items have the same # index and the two strings are the same length for x in range(len(sequenceIndexListA)): indexA = sequenceIndexListA[x] indexI = sequenceIndexListI[x] if indexA < indexI: for x in range(indexI - indexA): pronA.insert(indexA, "''") sequenceIndexListA = [val + indexI - indexA for val in sequenceIndexListA] elif indexA > indexI: for x in range(indexA - indexI): pronI.insert(indexI, "''") sequenceIndexListI = [val + indexA - indexI for val in sequenceIndexListI] return pronI, pronA def findBestSyllabification(isleDict, wordText, actualPronListOfLists): for aPron in actualPronListOfLists: if not isinstance(aPron, list): raise WrongTypeError("The pronunciation list must be a list" "of lists, even if it only has one sublist." "\ne.g. labyrinth\n" "[[l ˈæ . b ɚ . ˌɪ n ɵ], ]") if len(aPron) == 0: raise NullPronunciationError(wordText) try: actualPronListOfLists = [[unicode(char, "utf-8") for char in row] for row in actualPronListOfLists] except (NameError, TypeError): pass numWords = len(actualPronListOfLists) isleWordList = isleDict.lookup(wordText) if len(isleWordList) == numWords: retList = [] for isleWordList, aPron in zip(isleWordList, actualPronListOfLists): retList.append(_findBestSyllabification(isleWordList, aPron)) else: raise NumWordsMismatchError(wordText, len(isleWordList)) return retList def _findBestSyllabification(inputIsleWordList, actualPronunciationList): ''' Find the best syllabification for a word First find the closest pronunciation to a given pronunciation. Then take the syllabification for that pronunciation and map it onto the input pronunciation. ''' retList = _findBestPronunciation(inputIsleWordList, actualPronunciationList) isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList alignedPhoneList = alignedAPronList[bestIndex] alignedSyllables = alignedSyllableList[bestIndex] syllabification = isleWordList[bestIndex][0] stressedSyllableIndexList = isleWordList[bestIndex][1] stressedPhoneIndexList = isleWordList[bestIndex][2] syllableList = _syllabifyPhones(alignedPhoneList, alignedSyllables) # Get the location of stress in the generated file try: stressedSyllableI = stressedSyllableIndexList[0] except IndexError: stressedSyllableI = None stressedVowelI = None else: stressedVowelI = _getSyllableNucleus(syllableList[stressedSyllableI]) # Count the index of the stressed phones, if the stress list has # become flattened (no syllable information) flattenedStressIndexList = [] for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList): k = j for l in range(i): k += len(syllableList[l]) flattenedStressIndexList.append(k) return (stressedSyllableI, stressedVowelI, syllableList, syllabification, stressedSyllableIndexList, stressedPhoneIndexList, flattenedStressIndexList) def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) if vowelCount == 1: stressI = cvList.index('V') else: stressI = None return stressI def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndex]
mlavin/django-all-access
example/example/views.py
home
python
def home(request): "Simple homepage view." context = {} if request.user.is_authenticated(): try: access = request.user.accountaccess_set.all()[0] except IndexError: access = None else: client = access.api_client context['info'] = client.get_profile_info(raw_token=access.access_token) return render(request, 'home.html', context)
Simple homepage view.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/example/example/views.py#L4-L15
null
from django.shortcuts import render
mlavin/django-all-access
allaccess/clients.py
get_client
python
def get_client(provider, token=''): "Return the API client for the given provider." cls = OAuth2Client if provider.request_token_url: cls = OAuthClient return cls(provider, token)
Return the API client for the given provider.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L231-L236
null
from __future__ import unicode_literals import json import logging from django.utils.crypto import constant_time_compare, get_random_string from django.utils.encoding import force_text from requests.api import request from requests_oauthlib import OAuth1 from requests.exceptions import RequestException from .compat import urlencode, parse_qs logger = logging.getLogger('allaccess.clients') class BaseOAuthClient(object): def __init__(self, provider, token=''): self.provider = provider self.token = token def get_access_token(self, request, callback=None): "Fetch access token from callback request." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def get_profile_info(self, raw_token, profile_info_params={}): "Fetch user profile information." try: response = self.request('get', self.provider.profile_url, token=raw_token, params=profile_info_params) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch user profile: {0}'.format(e)) return None else: return response.json() or response.text def get_redirect_args(self, request, callback): "Get request parameters for redirect url." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def get_redirect_url(self, request, callback, parameters=None): "Build authentication redirect url." args = self.get_redirect_args(request, callback=callback) additional = parameters or {} args.update(additional) params = urlencode(args) return '{0}?{1}'.format(self.provider.authorization_url, params) def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def request(self, method, url, **kwargs): "Build remote url request." return request(method, url, **kwargs) @property def session_key(self): raise NotImplementedError('Defined in a sub-class') # pragma: no cover class OAuthClient(BaseOAuthClient): def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request('post', self.provider.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None def get_request_token(self, request, callback): "Fetch the OAuth request token. Only required for OAuth 1.0." callback = force_text(request.build_absolute_uri(callback)) try: response = self.request( 'post', self.provider.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[self.session_key] = raw_token return { 'oauth_token': token, 'oauth_callback': callback, } def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, secret) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oauth_verifier', None) oauth = OAuth1( resource_owner_key=token, resource_owner_secret=secret, client_key=self.provider.consumer_key, client_secret=self.provider.consumer_secret, verifier=verifier, callback_uri=callback, ) kwargs['auth'] = oauth return super(OAuthClient, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-token'.format(self.provider.name) class OAuth2Client(BaseOAuthClient): def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check = constant_time_compare(stored, returned) else: logger.error('No state parameter returned by the provider.') else: logger.error('No state stored in the sesssion.') return check def get_access_token(self, request, callback=None): "Fetch access token from callback request." callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request, callback): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'client_secret': self.provider.consumer_secret, 'code': request.GET['code'], 'grant_type': 'authorization_code', } else: logger.error('No code returned by the provider') return None try: response = self.request('post', self.provider.access_token_url, data=args) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text def get_application_state(self, request, callback): "Generate state optional parameter." return get_random_string(32) def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } state = self.get_application_state(request, callback) if state is not None: args['state'] = state request.session[self.session_key] = state return args def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access_token', [None])[0] else: token = token_data.get('access_token', None) return (token, None) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params return super(OAuth2Client, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-state'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
BaseOAuthClient.get_profile_info
python
def get_profile_info(self, raw_token, profile_info_params={}): "Fetch user profile information." try: response = self.request('get', self.provider.profile_url, token=raw_token, params=profile_info_params) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch user profile: {0}'.format(e)) return None else: return response.json() or response.text
Fetch user profile information.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L29-L38
[ "def request(self, method, url, **kwargs):\n \"Build remote url request.\"\n return request(method, url, **kwargs)\n" ]
class BaseOAuthClient(object): def __init__(self, provider, token=''): self.provider = provider self.token = token def get_access_token(self, request, callback=None): "Fetch access token from callback request." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def get_redirect_args(self, request, callback): "Get request parameters for redirect url." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def get_redirect_url(self, request, callback, parameters=None): "Build authentication redirect url." args = self.get_redirect_args(request, callback=callback) additional = parameters or {} args.update(additional) params = urlencode(args) return '{0}?{1}'.format(self.provider.authorization_url, params) def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." raise NotImplementedError('Defined in a sub-class') # pragma: no cover def request(self, method, url, **kwargs): "Build remote url request." return request(method, url, **kwargs) @property def session_key(self): raise NotImplementedError('Defined in a sub-class') # pragma: no cover
mlavin/django-all-access
allaccess/clients.py
OAuthClient.get_access_token
python
def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request('post', self.provider.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None
Fetch access token from callback request.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L67-L84
[ "def request(self, method, url, **kwargs):\n \"Build remote url request. Constructs necessary auth.\"\n user_token = kwargs.pop('token', self.token)\n token, secret = self.parse_raw_token(user_token)\n callback = kwargs.pop('oauth_callback', None)\n verifier = kwargs.get('data', {}).pop('oauth_verifier', None)\n oauth = OAuth1(\n resource_owner_key=token,\n resource_owner_secret=secret,\n client_key=self.provider.consumer_key,\n client_secret=self.provider.consumer_secret,\n verifier=verifier,\n callback_uri=callback,\n )\n kwargs['auth'] = oauth\n return super(OAuthClient, self).request(method, url, **kwargs)\n" ]
class OAuthClient(BaseOAuthClient): def get_request_token(self, request, callback): "Fetch the OAuth request token. Only required for OAuth 1.0." callback = force_text(request.build_absolute_uri(callback)) try: response = self.request( 'post', self.provider.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[self.session_key] = raw_token return { 'oauth_token': token, 'oauth_callback': callback, } def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, secret) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oauth_verifier', None) oauth = OAuth1( resource_owner_key=token, resource_owner_secret=secret, client_key=self.provider.consumer_key, client_secret=self.provider.consumer_secret, verifier=verifier, callback_uri=callback, ) kwargs['auth'] = oauth return super(OAuthClient, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-token'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuthClient.get_redirect_args
python
def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[self.session_key] = raw_token return { 'oauth_token': token, 'oauth_callback': callback, }
Get request parameters for redirect url.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L99-L109
[ "def get_request_token(self, request, callback):\n \"Fetch the OAuth request token. Only required for OAuth 1.0.\"\n callback = force_text(request.build_absolute_uri(callback))\n try:\n response = self.request(\n 'post', self.provider.request_token_url, oauth_callback=callback)\n response.raise_for_status()\n except RequestException as e:\n logger.error('Unable to fetch request token: {0}'.format(e))\n return None\n else:\n return response.text\n", "def parse_raw_token(self, raw_token):\n \"Parse token and secret from raw token response.\"\n if raw_token is None:\n return (None, None)\n qs = parse_qs(raw_token)\n token = qs.get('oauth_token', [None])[0]\n secret = qs.get('oauth_token_secret', [None])[0]\n return (token, secret)\n" ]
class OAuthClient(BaseOAuthClient): def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request('post', self.provider.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None def get_request_token(self, request, callback): "Fetch the OAuth request token. Only required for OAuth 1.0." callback = force_text(request.build_absolute_uri(callback)) try: response = self.request( 'post', self.provider.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, secret) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oauth_verifier', None) oauth = OAuth1( resource_owner_key=token, resource_owner_secret=secret, client_key=self.provider.consumer_key, client_secret=self.provider.consumer_secret, verifier=verifier, callback_uri=callback, ) kwargs['auth'] = oauth return super(OAuthClient, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-token'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuthClient.parse_raw_token
python
def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, secret)
Parse token and secret from raw token response.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L111-L118
null
class OAuthClient(BaseOAuthClient): def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request('post', self.provider.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None def get_request_token(self, request, callback): "Fetch the OAuth request token. Only required for OAuth 1.0." callback = force_text(request.build_absolute_uri(callback)) try: response = self.request( 'post', self.provider.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[self.session_key] = raw_token return { 'oauth_token': token, 'oauth_callback': callback, } def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oauth_verifier', None) oauth = OAuth1( resource_owner_key=token, resource_owner_secret=secret, client_key=self.provider.consumer_key, client_secret=self.provider.consumer_secret, verifier=verifier, callback_uri=callback, ) kwargs['auth'] = oauth return super(OAuthClient, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-token'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuthClient.request
python
def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oauth_verifier', None) oauth = OAuth1( resource_owner_key=token, resource_owner_secret=secret, client_key=self.provider.consumer_key, client_secret=self.provider.consumer_secret, verifier=verifier, callback_uri=callback, ) kwargs['auth'] = oauth return super(OAuthClient, self).request(method, url, **kwargs)
Build remote url request. Constructs necessary auth.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L120-L135
[ "def request(self, method, url, **kwargs):\n \"Build remote url request.\"\n return request(method, url, **kwargs)\n", "def parse_raw_token(self, raw_token):\n \"Parse token and secret from raw token response.\"\n if raw_token is None:\n return (None, None)\n qs = parse_qs(raw_token)\n token = qs.get('oauth_token', [None])[0]\n secret = qs.get('oauth_token_secret', [None])[0]\n return (token, secret)\n" ]
class OAuthClient(BaseOAuthClient): def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request('post', self.provider.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None def get_request_token(self, request, callback): "Fetch the OAuth request token. Only required for OAuth 1.0." callback = force_text(request.build_absolute_uri(callback)) try: response = self.request( 'post', self.provider.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[self.session_key] = raw_token return { 'oauth_token': token, 'oauth_callback': callback, } def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, secret) @property def session_key(self): return 'allaccess-{0}-request-token'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuth2Client.check_application_state
python
def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check = constant_time_compare(stored, returned) else: logger.error('No state parameter returned by the provider.') else: logger.error('No state stored in the sesssion.') return check
Check optional state parameter.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L144-L156
null
class OAuth2Client(BaseOAuthClient): def get_access_token(self, request, callback=None): "Fetch access token from callback request." callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request, callback): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'client_secret': self.provider.consumer_secret, 'code': request.GET['code'], 'grant_type': 'authorization_code', } else: logger.error('No code returned by the provider') return None try: response = self.request('post', self.provider.access_token_url, data=args) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text def get_application_state(self, request, callback): "Generate state optional parameter." return get_random_string(32) def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } state = self.get_application_state(request, callback) if state is not None: args['state'] = state request.session[self.session_key] = state return args def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access_token', [None])[0] else: token = token_data.get('access_token', None) return (token, None) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params return super(OAuth2Client, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-state'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuth2Client.get_redirect_args
python
def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } state = self.get_application_state(request, callback) if state is not None: args['state'] = state request.session[self.session_key] = state return args
Get request parameters for redirect url.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L188-L200
[ "def get_application_state(self, request, callback):\n \"Generate state optional parameter.\"\n return get_random_string(32)\n" ]
class OAuth2Client(BaseOAuthClient): def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check = constant_time_compare(stored, returned) else: logger.error('No state parameter returned by the provider.') else: logger.error('No state stored in the sesssion.') return check def get_access_token(self, request, callback=None): "Fetch access token from callback request." callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request, callback): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'client_secret': self.provider.consumer_secret, 'code': request.GET['code'], 'grant_type': 'authorization_code', } else: logger.error('No code returned by the provider') return None try: response = self.request('post', self.provider.access_token_url, data=args) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text def get_application_state(self, request, callback): "Generate state optional parameter." return get_random_string(32) def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access_token', [None])[0] else: token = token_data.get('access_token', None) return (token, None) def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params return super(OAuth2Client, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-state'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuth2Client.parse_raw_token
python
def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access_token', [None])[0] else: token = token_data.get('access_token', None) return (token, None)
Parse token and secret from raw token response.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L202-L214
null
class OAuth2Client(BaseOAuthClient): def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check = constant_time_compare(stored, returned) else: logger.error('No state parameter returned by the provider.') else: logger.error('No state stored in the sesssion.') return check def get_access_token(self, request, callback=None): "Fetch access token from callback request." callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request, callback): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'client_secret': self.provider.consumer_secret, 'code': request.GET['code'], 'grant_type': 'authorization_code', } else: logger.error('No code returned by the provider') return None try: response = self.request('post', self.provider.access_token_url, data=args) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text def get_application_state(self, request, callback): "Generate state optional parameter." return get_random_string(32) def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } state = self.get_application_state(request, callback) if state is not None: args['state'] = state request.session[self.session_key] = state return args def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params return super(OAuth2Client, self).request(method, url, **kwargs) @property def session_key(self): return 'allaccess-{0}-request-state'.format(self.provider.name)
mlavin/django-all-access
allaccess/clients.py
OAuth2Client.request
python
def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params return super(OAuth2Client, self).request(method, url, **kwargs)
Build remote url request. Constructs necessary auth.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L216-L224
[ "def request(self, method, url, **kwargs):\n \"Build remote url request.\"\n return request(method, url, **kwargs)\n", "def parse_raw_token(self, raw_token):\n \"Parse token and secret from raw token response.\"\n if raw_token is None:\n return (None, None)\n # Load as json first then parse as query string\n try:\n token_data = json.loads(raw_token)\n except ValueError:\n qs = parse_qs(raw_token)\n token = qs.get('access_token', [None])[0]\n else:\n token = token_data.get('access_token', None)\n return (token, None)\n" ]
class OAuth2Client(BaseOAuthClient): def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check = constant_time_compare(stored, returned) else: logger.error('No state parameter returned by the provider.') else: logger.error('No state stored in the sesssion.') return check def get_access_token(self, request, callback=None): "Fetch access token from callback request." callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request, callback): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'client_secret': self.provider.consumer_secret, 'code': request.GET['code'], 'grant_type': 'authorization_code', } else: logger.error('No code returned by the provider') return None try: response = self.request('post', self.provider.access_token_url, data=args) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text def get_application_state(self, request, callback): "Generate state optional parameter." return get_random_string(32) def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } state = self.get_application_state(request, callback) if state is not None: args['state'] = state request.session[self.session_key] = state return args def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access_token', [None])[0] else: token = token_data.get('access_token', None) return (token, None) @property def session_key(self): return 'allaccess-{0}-request-state'.format(self.provider.name)
mlavin/django-all-access
allaccess/backends.py
AuthorizedServiceBackend.authenticate
python
def authenticate(self, provider=None, identifier=None): "Fetch user for a given provider by id." provider_q = Q(provider__name=provider) if isinstance(provider, Provider): provider_q = Q(provider=provider) try: access = AccountAccess.objects.filter( provider_q, identifier=identifier ).select_related('user')[0] except IndexError: return None else: return access.user
Fetch user for a given provider by id.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/backends.py#L12-L24
null
class AuthorizedServiceBackend(ModelBackend): "Authentication backend for users registered with remote OAuth provider."
mlavin/django-all-access
allaccess/views.py
OAuthClientMixin.get_client
python
def get_client(self, provider): "Get instance of the OAuth client for this provider." if self.client_class is not None: return self.client_class(provider) return get_client(provider)
Get instance of the OAuth client for this provider.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L28-L32
[ "def get_client(provider, token=''):\n \"Return the API client for the given provider.\"\n cls = OAuth2Client\n if provider.request_token_url:\n cls = OAuthClient\n return cls(provider, token)\n" ]
class OAuthClientMixin(object): "Mixin for getting OAuth client for a provider." client_class = None
mlavin/django-all-access
allaccess/views.py
OAuthRedirect.get_redirect_url
python
def get_redirect_url(self, **kwargs): "Build redirect url for a given provider." name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if not provider.enabled(): raise Http404('Provider %s is not enabled.' % name) client = self.get_client(provider) callback = self.get_callback_url(provider) params = self.get_additional_parameters(provider) return client.get_redirect_url(self.request, callback=callback, parameters=params)
Build redirect url for a given provider.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L49-L62
null
class OAuthRedirect(OAuthClientMixin, RedirectView): "Redirect user to OAuth provider to enable access." permanent = False params = None def get_additional_parameters(self, provider): "Return additional redirect parameters for this provider." return self.params or {} def get_callback_url(self, provider): "Return the callback url for this provider." return reverse('allaccess-callback', kwargs={'provider': provider.name})
mlavin/django-all-access
allaccess/views.py
OAuthCallback.get_or_create_user
python
def get_or_create_user(self, provider, access, info): "Create a shell auth.User." digest = hashlib.sha1(smart_bytes(access)).digest() # Base 64 encode to get below 30 characters # Removed padding characters username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '') User = get_user_model() kwargs = { User.USERNAME_FIELD: username, 'email': '', 'password': None } return User.objects.create_user(**kwargs)
Create a shell auth.User.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L123-L135
null
class OAuthCallback(OAuthClientMixin, View): "Base OAuth callback view." provider_id = None profile_info_params = None def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if not provider.enabled(): raise Http404('Provider %s is not enabled.' % name) client = self.get_client(provider) callback = self.get_callback_url(provider) # Fetch access token raw_token = client.get_access_token(self.request, callback=callback) if raw_token is None: return self.handle_login_failure(provider, "Could not retrieve token.") # Fetch profile info params profile_info_params = self.get_profile_info_params() # Fetch profile info info = client.get_profile_info(raw_token, profile_info_params) if info is None: return self.handle_login_failure(provider, "Could not retrieve profile.") identifier = self.get_user_id(provider, info) if identifier is None: return self.handle_login_failure(provider, "Could not determine id.") # Get or create access record defaults = { 'access_token': raw_token, } access, created = AccountAccess.objects.get_or_create( provider=provider, identifier=identifier, defaults=defaults ) if not created: access.access_token = raw_token AccountAccess.objects.filter(pk=access.pk).update(**defaults) user = authenticate(provider=provider, identifier=identifier) if user is None: return self.handle_new_user(provider, access, info) else: return self.handle_existing_user(provider, user, access, info) def get_callback_url(self, provider): "Return callback url if different than the current url." return None def get_error_redirect(self, provider, reason): "Return url to redirect on login failure." return settings.LOGIN_URL def get_login_redirect(self, provider, user, access, new=False): "Return url to redirect authenticated users." return settings.LOGIN_REDIRECT_URL def get_profile_info_params(self): "Return params that are going to be sent when getting user profile info" return self.profile_info_params or {} def get_user_id(self, provider, info): "Return unique identifier from the profile info." id_key = self.provider_id or 'id' result = info try: for key in id_key.split('.'): result = result[key] return result except KeyError: return None def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access)) def handle_login_failure(self, provider, reason): "Message user and redirect on error." logger.error('Authenication Failure: {0}'.format(reason)) messages.error(self.request, 'Authenication Failed.') return redirect(self.get_error_redirect(provider, reason)) def handle_new_user(self, provider, access, info): "Create a shell auth.User and redirect." user = self.get_or_create_user(provider, access, info) access.user = user AccountAccess.objects.filter(pk=access.pk).update(user=user) user = authenticate(provider=access.provider, identifier=access.identifier) login(self.request, user) return redirect(self.get_login_redirect(provider, user, access, True))
mlavin/django-all-access
allaccess/views.py
OAuthCallback.get_user_id
python
def get_user_id(self, provider, info): "Return unique identifier from the profile info." id_key = self.provider_id or 'id' result = info try: for key in id_key.split('.'): result = result[key] return result except KeyError: return None
Return unique identifier from the profile info.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L141-L150
null
class OAuthCallback(OAuthClientMixin, View): "Base OAuth callback view." provider_id = None profile_info_params = None def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if not provider.enabled(): raise Http404('Provider %s is not enabled.' % name) client = self.get_client(provider) callback = self.get_callback_url(provider) # Fetch access token raw_token = client.get_access_token(self.request, callback=callback) if raw_token is None: return self.handle_login_failure(provider, "Could not retrieve token.") # Fetch profile info params profile_info_params = self.get_profile_info_params() # Fetch profile info info = client.get_profile_info(raw_token, profile_info_params) if info is None: return self.handle_login_failure(provider, "Could not retrieve profile.") identifier = self.get_user_id(provider, info) if identifier is None: return self.handle_login_failure(provider, "Could not determine id.") # Get or create access record defaults = { 'access_token': raw_token, } access, created = AccountAccess.objects.get_or_create( provider=provider, identifier=identifier, defaults=defaults ) if not created: access.access_token = raw_token AccountAccess.objects.filter(pk=access.pk).update(**defaults) user = authenticate(provider=provider, identifier=identifier) if user is None: return self.handle_new_user(provider, access, info) else: return self.handle_existing_user(provider, user, access, info) def get_callback_url(self, provider): "Return callback url if different than the current url." return None def get_error_redirect(self, provider, reason): "Return url to redirect on login failure." return settings.LOGIN_URL def get_login_redirect(self, provider, user, access, new=False): "Return url to redirect authenticated users." return settings.LOGIN_REDIRECT_URL def get_or_create_user(self, provider, access, info): "Create a shell auth.User." digest = hashlib.sha1(smart_bytes(access)).digest() # Base 64 encode to get below 30 characters # Removed padding characters username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '') User = get_user_model() kwargs = { User.USERNAME_FIELD: username, 'email': '', 'password': None } return User.objects.create_user(**kwargs) def get_profile_info_params(self): "Return params that are going to be sent when getting user profile info" return self.profile_info_params or {} def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access)) def handle_login_failure(self, provider, reason): "Message user and redirect on error." logger.error('Authenication Failure: {0}'.format(reason)) messages.error(self.request, 'Authenication Failed.') return redirect(self.get_error_redirect(provider, reason)) def handle_new_user(self, provider, access, info): "Create a shell auth.User and redirect." user = self.get_or_create_user(provider, access, info) access.user = user AccountAccess.objects.filter(pk=access.pk).update(user=user) user = authenticate(provider=access.provider, identifier=access.identifier) login(self.request, user) return redirect(self.get_login_redirect(provider, user, access, True))
mlavin/django-all-access
allaccess/views.py
OAuthCallback.handle_existing_user
python
def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access))
Login user and redirect.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L152-L155
null
class OAuthCallback(OAuthClientMixin, View): "Base OAuth callback view." provider_id = None profile_info_params = None def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if not provider.enabled(): raise Http404('Provider %s is not enabled.' % name) client = self.get_client(provider) callback = self.get_callback_url(provider) # Fetch access token raw_token = client.get_access_token(self.request, callback=callback) if raw_token is None: return self.handle_login_failure(provider, "Could not retrieve token.") # Fetch profile info params profile_info_params = self.get_profile_info_params() # Fetch profile info info = client.get_profile_info(raw_token, profile_info_params) if info is None: return self.handle_login_failure(provider, "Could not retrieve profile.") identifier = self.get_user_id(provider, info) if identifier is None: return self.handle_login_failure(provider, "Could not determine id.") # Get or create access record defaults = { 'access_token': raw_token, } access, created = AccountAccess.objects.get_or_create( provider=provider, identifier=identifier, defaults=defaults ) if not created: access.access_token = raw_token AccountAccess.objects.filter(pk=access.pk).update(**defaults) user = authenticate(provider=provider, identifier=identifier) if user is None: return self.handle_new_user(provider, access, info) else: return self.handle_existing_user(provider, user, access, info) def get_callback_url(self, provider): "Return callback url if different than the current url." return None def get_error_redirect(self, provider, reason): "Return url to redirect on login failure." return settings.LOGIN_URL def get_login_redirect(self, provider, user, access, new=False): "Return url to redirect authenticated users." return settings.LOGIN_REDIRECT_URL def get_or_create_user(self, provider, access, info): "Create a shell auth.User." digest = hashlib.sha1(smart_bytes(access)).digest() # Base 64 encode to get below 30 characters # Removed padding characters username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '') User = get_user_model() kwargs = { User.USERNAME_FIELD: username, 'email': '', 'password': None } return User.objects.create_user(**kwargs) def get_profile_info_params(self): "Return params that are going to be sent when getting user profile info" return self.profile_info_params or {} def get_user_id(self, provider, info): "Return unique identifier from the profile info." id_key = self.provider_id or 'id' result = info try: for key in id_key.split('.'): result = result[key] return result except KeyError: return None def handle_login_failure(self, provider, reason): "Message user and redirect on error." logger.error('Authenication Failure: {0}'.format(reason)) messages.error(self.request, 'Authenication Failed.') return redirect(self.get_error_redirect(provider, reason)) def handle_new_user(self, provider, access, info): "Create a shell auth.User and redirect." user = self.get_or_create_user(provider, access, info) access.user = user AccountAccess.objects.filter(pk=access.pk).update(user=user) user = authenticate(provider=access.provider, identifier=access.identifier) login(self.request, user) return redirect(self.get_login_redirect(provider, user, access, True))
mlavin/django-all-access
allaccess/views.py
OAuthCallback.handle_new_user
python
def handle_new_user(self, provider, access, info): "Create a shell auth.User and redirect." user = self.get_or_create_user(provider, access, info) access.user = user AccountAccess.objects.filter(pk=access.pk).update(user=user) user = authenticate(provider=access.provider, identifier=access.identifier) login(self.request, user) return redirect(self.get_login_redirect(provider, user, access, True))
Create a shell auth.User and redirect.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/views.py#L163-L170
null
class OAuthCallback(OAuthClientMixin, View): "Base OAuth callback view." provider_id = None profile_info_params = None def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if not provider.enabled(): raise Http404('Provider %s is not enabled.' % name) client = self.get_client(provider) callback = self.get_callback_url(provider) # Fetch access token raw_token = client.get_access_token(self.request, callback=callback) if raw_token is None: return self.handle_login_failure(provider, "Could not retrieve token.") # Fetch profile info params profile_info_params = self.get_profile_info_params() # Fetch profile info info = client.get_profile_info(raw_token, profile_info_params) if info is None: return self.handle_login_failure(provider, "Could not retrieve profile.") identifier = self.get_user_id(provider, info) if identifier is None: return self.handle_login_failure(provider, "Could not determine id.") # Get or create access record defaults = { 'access_token': raw_token, } access, created = AccountAccess.objects.get_or_create( provider=provider, identifier=identifier, defaults=defaults ) if not created: access.access_token = raw_token AccountAccess.objects.filter(pk=access.pk).update(**defaults) user = authenticate(provider=provider, identifier=identifier) if user is None: return self.handle_new_user(provider, access, info) else: return self.handle_existing_user(provider, user, access, info) def get_callback_url(self, provider): "Return callback url if different than the current url." return None def get_error_redirect(self, provider, reason): "Return url to redirect on login failure." return settings.LOGIN_URL def get_login_redirect(self, provider, user, access, new=False): "Return url to redirect authenticated users." return settings.LOGIN_REDIRECT_URL def get_or_create_user(self, provider, access, info): "Create a shell auth.User." digest = hashlib.sha1(smart_bytes(access)).digest() # Base 64 encode to get below 30 characters # Removed padding characters username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '') User = get_user_model() kwargs = { User.USERNAME_FIELD: username, 'email': '', 'password': None } return User.objects.create_user(**kwargs) def get_profile_info_params(self): "Return params that are going to be sent when getting user profile info" return self.profile_info_params or {} def get_user_id(self, provider, info): "Return unique identifier from the profile info." id_key = self.provider_id or 'id' result = info try: for key in id_key.split('.'): result = result[key] return result except KeyError: return None def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access)) def handle_login_failure(self, provider, reason): "Message user and redirect on error." logger.error('Authenication Failure: {0}'.format(reason)) messages.error(self.request, 'Authenication Failed.') return redirect(self.get_error_redirect(provider, reason))
mlavin/django-all-access
allaccess/context_processors.py
_get_enabled
python
def _get_enabled(): providers = Provider.objects.all() return [p for p in providers if p.enabled()]
Wrapped function for filtering enabled providers.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/context_processors.py#L10-L13
null
"Helpers to add provider and account access information to the template context." from __future__ import unicode_literals from django.utils.functional import SimpleLazyObject from .compat import APPENGINE from .models import Provider def available_providers(request): "Adds the list of enabled providers to the context." if APPENGINE: # Note: AppEngine inequality queries are limited to one property. # See https://developers.google.com/appengine/docs/python/datastore/queries#Python_Restrictions_on_queries # Users have also noted that the exclusion queries don't work # See https://github.com/mlavin/django-all-access/pull/46 # So this is lazily-filtered in Python qs = SimpleLazyObject(lambda: _get_enabled()) else: qs = Provider.objects.filter(consumer_secret__isnull=False, consumer_key__isnull=False) return {'allaccess_providers': qs}
mlavin/django-all-access
allaccess/context_processors.py
available_providers
python
def available_providers(request): "Adds the list of enabled providers to the context." if APPENGINE: # Note: AppEngine inequality queries are limited to one property. # See https://developers.google.com/appengine/docs/python/datastore/queries#Python_Restrictions_on_queries # Users have also noted that the exclusion queries don't work # See https://github.com/mlavin/django-all-access/pull/46 # So this is lazily-filtered in Python qs = SimpleLazyObject(lambda: _get_enabled()) else: qs = Provider.objects.filter(consumer_secret__isnull=False, consumer_key__isnull=False) return {'allaccess_providers': qs}
Adds the list of enabled providers to the context.
train
https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/context_processors.py#L16-L27
null
"Helpers to add provider and account access information to the template context." from __future__ import unicode_literals from django.utils.functional import SimpleLazyObject from .compat import APPENGINE from .models import Provider def _get_enabled(): """Wrapped function for filtering enabled providers.""" providers = Provider.objects.all() return [p for p in providers if p.enabled()]
PixelwarStudio/PyTree
Tree/core.py
generate_branches
python
def generate_branches(scales=None, angles=None, shift_angle=0): branches = [] for pos, scale in enumerate(scales): angle = -sum(angles)/2 + sum(angles[:pos]) + shift_angle branches.append([scale, angle]) return branches
Generates branches with alternative system. Args: scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age. angles (tuple/array): Holding the branch and shift angle in radians. shift_angle (float): Holding the rotation angle for all branches. Returns: branches (2d-array): A array constits of arrays holding scale and angle for every branch.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L225-L240
null
""" Module for creating trees """ from math import pi, log, sqrt from random import gauss from Tree.utils import Node from Tree.draw import SUPPORTED_CANVAS class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_rectangle
python
def get_rectangle(self): rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec)
Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2)
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L31-L46
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_size
python
def get_size(self): rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1]))
Get the size of the tree. Returns: tupel: (width, height)
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L48-L55
[ "def get_rectangle(self):\n \"\"\"Gets the coordinates of the rectangle, in which the tree can be put.\n\n Returns:\n tupel: (x1, y1, x2, y2)\n \"\"\"\n rec = [self.pos[0], self.pos[1]]*2\n for age in self.nodes:\n for node in age:\n # Check max/min for x/y coords\n for i in range(2):\n if rec[0+i] > node.pos[i]:\n rec[0+i] = node.pos[i]\n elif rec[2+i] < node.pos[i]:\n rec[2+i] = node.pos[i]\n return tuple(rec)\n" ]
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_branch_length
python
def get_branch_length(self, age=None, pos=0): if age is None: age = self.age return self.length * pow(self.branches[pos][0], age)
Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L57-L71
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_steps_branch_len
python
def get_steps_branch_len(self, length): return log(length/self.length, min(self.branches[0][0]))
Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L73-L79
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_node_sum
python
def get_node_sum(self, age=None): if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1))
Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L81-L90
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_node_age_sum
python
def get_node_age_sum(self, age=None): if age is None: age = self.age return pow(self.comp, age)
Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L92-L101
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_nodes
python
def get_nodes(self): nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes
Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ]
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L103-L121
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.get_branches
python
def get_branches(self): branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches
Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ]
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L123-L146
[ "def _get_node_parent(self, age, pos):\n \"\"\"Get the parent node of node, whch is located in tree's node list.\n\n Returns:\n object: The parent node.\n \"\"\"\n return self.nodes[age][int(pos / self.comp)]\n", "def get_tuple(self):\n \"\"\"Get the position of the node as tuple.\n\n Returns:\n tupel: (x, y)\n \"\"\"\n return self.pos\n" ]
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.move
python
def move(self, delta): pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta)
Move the tree. Args: delta (tupel): The adjustment of the position.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L148-L160
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.grow
python
def grow(self, times=1): self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1)
Let the tree grow. Args: times (integer): Indicate how many times the tree will grow.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L167-L189
[ "def grow(self, times=1):\n \"\"\"Let the tree grow.\n\n Args:\n times (integer): Indicate how many times the tree will grow.\n \"\"\"\n self.nodes.append([])\n\n for n, node in enumerate(self.nodes[self.age]):\n if self.age == 0:\n p_node = Node(self.pos[:2])\n else:\n p_node = self._get_node_parent(self.age-1, n)\n angle = node.get_node_angle(p_node)\n for i in range(self.comp):\n tot_angle = self.__get_total_angle(angle, i)\n length = self.__get_total_length(self.age+1, i)\n self.nodes[self.age+1].append(node.make_new_node(length, tot_angle))\n\n self.age += 1\n\n if times > 1:\n self.grow(times-1)\n", "def __get_total_angle(self, angle, pos):\n \"\"\"Get the total angle.\"\"\"\n tot_angle = angle - self.branches[pos][1]\n if self.sigma[1] != 0:\n tot_angle += gauss(0, self.sigma[1]) * pi\n return tot_angle\n", "def __get_total_length(self, age, pos):\n length = self.get_branch_length(age, pos)\n if self.sigma[0] != 0:\n length *= (1+gauss(0, self.sigma[0]))\n return length\n", "def _get_node_parent(self, age, pos):\n \"\"\"Get the parent node of node, whch is located in tree's node list.\n\n Returns:\n object: The parent node.\n \"\"\"\n return self.nodes[age][int(pos / self.comp)]\n" ]
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.draw_on
python
def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw()
Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L191-L202
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree.__get_total_angle
python
def __get_total_angle(self, angle, pos): tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle
Get the total angle.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L204-L209
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PixelwarStudio/PyTree
Tree/core.py
Tree._get_node_parent
python
def _get_node_parent(self, age, pos): return self.nodes[age][int(pos / self.comp)]
Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L217-L223
null
class Tree: """The standard tree.""" def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): """The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2) """ self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ [Node(pos[2:])] ] def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec) def get_size(self): """Get the size of the tree. Returns: tupel: (width, height) """ rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[1])) def get_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """ if age is None: age = self.age return self.length * pow(self.branches[pos][0], age) def get_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """ return log(length/self.length, min(self.branches[0][0])) def get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """ if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) def get_node_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """ if age is None: age = self.age return pow(self.comp, age) def get_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], [(100, 90), (120, 40), ...], ... ] """ nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes def get_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], [(100, 40, 120, 70), (100, 40, 150, 90), ...], ... ] """ branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches def move(self, delta): """Move the tree. Args: delta (tupel): The adjustment of the position. """ pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(delta) def move_in_rectangle(self): """Move the tree so that the tree fits in the rectangle.""" rec = self.get_rectangle() self.move((-rec[0], -rec[1])) def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-1) def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """ if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw() def __get_total_angle(self, angle, pos): """Get the total angle.""" tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle def __get_total_length(self, age, pos): length = self.get_branch_length(age, pos) if self.sigma[0] != 0: length *= (1+gauss(0, self.sigma[0])) return length
PixelwarStudio/PyTree
Tree/draw.py
Drawer._get_color
python
def _get_color(self, age): if age == self.tree.age: return self.leaf_color color = self.stem_color tree = self.tree if len(color) == 3: return color diff = [color[i+3]-color[i] for i in range(3)] per_age = [diff[i]/(tree.age-1) for i in range(3)] return tuple([int(color[i]+per_age[i]*age) for i in range(3)])
Get the fill color depending on age. Args: age (int): The age of the branch/es Returns: tuple: (r, g, b)
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/draw.py#L42-L62
null
class Drawer(object): """A generic class for drawing tree on acanvas.""" def __init__(self, tree, canvas, stem_color=(255, 255, 255), leaf_color=(230, 120, 34), thickness=1, ages=None): """Constructor of drawer. Args: tree (object): The tree, which should drawn on canvas. canvas (object): The canvas for drawing the tree. stem_color (tupel): Color or gradient for the steam of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. ages (array): Contains the ages you want to draw. Returns: int: The thickness of the branch/es """ self.canvas = canvas self.tree = tree self.stem_color = stem_color self.leaf_color = leaf_color self.thickness = thickness self.ages = range(tree.age+1) if ages is None else ages def _get_thickness(self, age): """Get the thickness depending on age. Args: age (int): The age of the branch/es Returns: int: The thickness of the branch/es """ return int((self.thickness*5)/(age+5)) def _draw_branch(self, branch, color, thickness, age): """Placeholder for specific draw methods for a branch. Args: branch (tupel): The coordinates of the branch. color (tupel): The color of the branch. thickness (int): The thickness of the branch. age (int): The age of the tree the branch is drawn. """ pass def draw(self): """Draws the tree. Args: ages (array): Contains the ages you want to draw. """ for age, level in enumerate(self.tree.get_branches()): if age in self.ages: thickness = self._get_thickness(age) color = self._get_color(age) for branch in level: self._draw_branch(branch, color, thickness, age)
PixelwarStudio/PyTree
Tree/draw.py
Drawer.draw
python
def draw(self): for age, level in enumerate(self.tree.get_branches()): if age in self.ages: thickness = self._get_thickness(age) color = self._get_color(age) for branch in level: self._draw_branch(branch, color, thickness, age)
Draws the tree. Args: ages (array): Contains the ages you want to draw.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/draw.py#L75-L86
[ "def _get_thickness(self, age):\n \"\"\"Get the thickness depending on age.\n\n Args:\n age (int): The age of the branch/es\n\n Returns:\n int: The thickness of the branch/es\n \"\"\"\n return int((self.thickness*5)/(age+5))\n", "def _get_color(self, age):\n \"\"\"Get the fill color depending on age.\n\n Args:\n age (int): The age of the branch/es\n\n Returns:\n tuple: (r, g, b)\n \"\"\"\n if age == self.tree.age:\n return self.leaf_color\n color = self.stem_color\n tree = self.tree\n\n if len(color) == 3:\n return color\n\n diff = [color[i+3]-color[i] for i in range(3)]\n per_age = [diff[i]/(tree.age-1) for i in range(3)]\n\n return tuple([int(color[i]+per_age[i]*age) for i in range(3)])\n", "def _draw_branch(self, branch, color, thickness, age):\n \"\"\"Placeholder for specific draw methods for a branch.\n\n Args:\n branch (tupel): The coordinates of the branch.\n color (tupel): The color of the branch.\n thickness (int): The thickness of the branch.\n age (int): The age of the tree the branch is drawn.\n \"\"\"\n pass\n", "def _draw_branch(self, branch, color, thickness, age):\n color = convert_color(color)\n self.group[age].add(\n self.canvas.line(\n start=branch[:2],\n end=branch[2:],\n stroke=color,\n stroke_width=thickness\n )\n )\n" ]
class Drawer(object): """A generic class for drawing tree on acanvas.""" def __init__(self, tree, canvas, stem_color=(255, 255, 255), leaf_color=(230, 120, 34), thickness=1, ages=None): """Constructor of drawer. Args: tree (object): The tree, which should drawn on canvas. canvas (object): The canvas for drawing the tree. stem_color (tupel): Color or gradient for the steam of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. ages (array): Contains the ages you want to draw. Returns: int: The thickness of the branch/es """ self.canvas = canvas self.tree = tree self.stem_color = stem_color self.leaf_color = leaf_color self.thickness = thickness self.ages = range(tree.age+1) if ages is None else ages def _get_thickness(self, age): """Get the thickness depending on age. Args: age (int): The age of the branch/es Returns: int: The thickness of the branch/es """ return int((self.thickness*5)/(age+5)) def _get_color(self, age): """Get the fill color depending on age. Args: age (int): The age of the branch/es Returns: tuple: (r, g, b) """ if age == self.tree.age: return self.leaf_color color = self.stem_color tree = self.tree if len(color) == 3: return color diff = [color[i+3]-color[i] for i in range(3)] per_age = [diff[i]/(tree.age-1) for i in range(3)] return tuple([int(color[i]+per_age[i]*age) for i in range(3)]) def _draw_branch(self, branch, color, thickness, age): """Placeholder for specific draw methods for a branch. Args: branch (tupel): The coordinates of the branch. color (tupel): The color of the branch. thickness (int): The thickness of the branch. age (int): The age of the tree the branch is drawn. """ pass
PixelwarStudio/PyTree
Tree/utils.py
Node.make_new_node
python
def make_new_node(self, distance, angle): return Node((cos(-angle)*distance+self.pos[0], sin(-angle)*distance+self.pos[1]))
Make a new node from an existing one. This method creates a new node with a distance and angle given. The position of the new node is calculated with: x2 = cos(-angle)*distance+x1 y2 = sin(-angle)*distance+y1 Args: distance (float): The distance of the original node to the new node. angle (rad): The angle between the old and new node, relative to the horizont. Returns: object: The node with calculated poistion.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/utils.py#L26-L42
null
class Node(object): """A node. Attributes: pos (tupel): The position of the node. (x, y) """ def __init__(self, pos): self.pos = pos def get_node_angle(self, node): """Get the angle beetween 2 nodes relative to the horizont. Args: node (object): The other node. Returns: rad: The angle """ return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2 def get_distance(self, node): """Get the distance beetween 2 nodes Args: node (object): The other node. """ delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1]) return sqrt(delta[0]**2+delta[1]**2) def get_tuple(self): """Get the position of the node as tuple. Returns: tupel: (x, y) """ return self.pos def move(self, delta): """Move the node. Args: delta (tupel): A tupel, holding the adjustment of the position. """ self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
PixelwarStudio/PyTree
Tree/utils.py
Node.get_node_angle
python
def get_node_angle(self, node): return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2
Get the angle beetween 2 nodes relative to the horizont. Args: node (object): The other node. Returns: rad: The angle
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/utils.py#L44-L53
null
class Node(object): """A node. Attributes: pos (tupel): The position of the node. (x, y) """ def __init__(self, pos): self.pos = pos def make_new_node(self, distance, angle): """Make a new node from an existing one. This method creates a new node with a distance and angle given. The position of the new node is calculated with: x2 = cos(-angle)*distance+x1 y2 = sin(-angle)*distance+y1 Args: distance (float): The distance of the original node to the new node. angle (rad): The angle between the old and new node, relative to the horizont. Returns: object: The node with calculated poistion. """ return Node((cos(-angle)*distance+self.pos[0], sin(-angle)*distance+self.pos[1])) def get_distance(self, node): """Get the distance beetween 2 nodes Args: node (object): The other node. """ delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1]) return sqrt(delta[0]**2+delta[1]**2) def get_tuple(self): """Get the position of the node as tuple. Returns: tupel: (x, y) """ return self.pos def move(self, delta): """Move the node. Args: delta (tupel): A tupel, holding the adjustment of the position. """ self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
PixelwarStudio/PyTree
Tree/utils.py
Node.get_distance
python
def get_distance(self, node): delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1]) return sqrt(delta[0]**2+delta[1]**2)
Get the distance beetween 2 nodes Args: node (object): The other node.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/utils.py#L55-L62
null
class Node(object): """A node. Attributes: pos (tupel): The position of the node. (x, y) """ def __init__(self, pos): self.pos = pos def make_new_node(self, distance, angle): """Make a new node from an existing one. This method creates a new node with a distance and angle given. The position of the new node is calculated with: x2 = cos(-angle)*distance+x1 y2 = sin(-angle)*distance+y1 Args: distance (float): The distance of the original node to the new node. angle (rad): The angle between the old and new node, relative to the horizont. Returns: object: The node with calculated poistion. """ return Node((cos(-angle)*distance+self.pos[0], sin(-angle)*distance+self.pos[1])) def get_node_angle(self, node): """Get the angle beetween 2 nodes relative to the horizont. Args: node (object): The other node. Returns: rad: The angle """ return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2 def get_tuple(self): """Get the position of the node as tuple. Returns: tupel: (x, y) """ return self.pos def move(self, delta): """Move the node. Args: delta (tupel): A tupel, holding the adjustment of the position. """ self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
PixelwarStudio/PyTree
Tree/utils.py
Node.move
python
def move(self, delta): self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
Move the node. Args: delta (tupel): A tupel, holding the adjustment of the position.
train
https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/utils.py#L72-L78
null
class Node(object): """A node. Attributes: pos (tupel): The position of the node. (x, y) """ def __init__(self, pos): self.pos = pos def make_new_node(self, distance, angle): """Make a new node from an existing one. This method creates a new node with a distance and angle given. The position of the new node is calculated with: x2 = cos(-angle)*distance+x1 y2 = sin(-angle)*distance+y1 Args: distance (float): The distance of the original node to the new node. angle (rad): The angle between the old and new node, relative to the horizont. Returns: object: The node with calculated poistion. """ return Node((cos(-angle)*distance+self.pos[0], sin(-angle)*distance+self.pos[1])) def get_node_angle(self, node): """Get the angle beetween 2 nodes relative to the horizont. Args: node (object): The other node. Returns: rad: The angle """ return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2 def get_distance(self, node): """Get the distance beetween 2 nodes Args: node (object): The other node. """ delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1]) return sqrt(delta[0]**2+delta[1]**2) def get_tuple(self): """Get the position of the node as tuple. Returns: tupel: (x, y) """ return self.pos
cablehead/vanilla
vanilla/message.py
Queue
python
def Queue(hub, size): assert size > 0 def main(upstream, downstream, size): queue = collections.deque() while True: if downstream.halted: # no one is downstream, so shutdown upstream.close() return watch = [] if queue: watch.append(downstream) else: # if the buffer is empty, and no one is upstream, shutdown if upstream.halted: downstream.close() return # if are upstream is still available, and there is spare room in # the buffer, watch upstream as well if not upstream.halted and len(queue) < size: watch.append(upstream) try: ch, item = hub.select(watch) except vanilla.exception.Halt: continue if ch == upstream: queue.append(item) elif ch == downstream: item = queue.popleft() downstream.send(item) upstream = hub.pipe() downstream = hub.pipe() # TODO: rethink this old_connect = upstream.sender.connect def connect(recver): old_connect(recver) return downstream.recver upstream.sender.connect = connect hub.spawn(main, upstream.recver, downstream.sender, size) return Pair(upstream.sender, downstream.recver)
:: +----------+ send --> | Queue | | (buffer) | --> recv +----------+ A Queue may also only have exactly one sender and recver. A Queue however has a fifo buffer of a custom size. Sends to the Queue won't block until the buffer becomes full:: h = vanilla.Hub() q = h.queue(1) q.send(1) # safe from deadlock # q.send(1) # this would deadlock however as the queue only has a # buffer size of 1 q.recv() # returns 1
train
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L438-L508
[ "def pipe(self):\n \"\"\"\n Returns a `Pipe`_ `Pair`_.\n \"\"\"\n return vanilla.message.Pipe(self)\n", "def spawn(self, f, *a):\n \"\"\"\n Schedules a new green thread to be created to run *f(\\*a)* on the next\n available tick::\n\n def echo(pipe, s):\n pipe.send(s)\n\n p = h.pipe()\n h.spawn(echo, p, 'hi')\n p.recv() # returns 'hi'\n \"\"\"\n self.ready.append((f, a))\n" ]
import collections import weakref from greenlet import getcurrent import vanilla.exception Pair = collections.namedtuple('Pair', ['sender', 'recver']) class NoState(object): """a marker to indicate no state""" class Pair(Pair): """ A Pair is a tuple of a `Sender`_ and a `Recver`_. The pair only share a weakref to each other so unless a reference is kept to both ends, the remaining end will be *abandoned* and the entire pair will be garbage collected. It's possible to call methods directly on the Pair tuple. A common pattern though is to split up the tuple with the `Sender`_ used in one closure and the `Recver`_ in another:: # create a Pipe Pair p = h.pipe() # call the Pair tuple directly h.spawn(p.send, '1') p.recv() # returns '1' # split the sender and recver sender, recver = p sender.send('2') recver.recv() # returns '2' """ def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ return self.sender.send(item, timeout=timeout) def clear(self): self.sender.clear() return self def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ return self.recver.recv(timeout=timeout) def recv_n(self, n, timeout=-1): return self.recver.recv_n(n, timeout=timeout) def recv_partition(self, sep, timeout=-1): return self.recver.recv_partition(sep, timeout=timeout) def recv_line(self, timeout=-1): return self.recver.recv_line(timeout=timeout) def pipe(self, target): """ Pipes are Recver to the target; see :meth:`vanilla.core.Recver.pipe` Returns a new Pair of our current Sender and the target's Recver. """ return self._replace(recver=self.recver.pipe(target)) def map(self, f): """ Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map` Returns a new Pair of our current Sender and the mapped target's Recver. """ return self._replace(recver=self.recver.map(f)) def consume(self, f): """ Consumes this Pair with *f*; see :meth:`vanilla.core.Recver.consume`. Returns only our Sender """ self.recver.consume(f) return self.sender def connect(self, recver): # TODO: shouldn't this return a new Pair? return self.sender.connect(recver) def onclose(self, f, *a, **kw): self.recver.onclose(f, *a, **kw) def close(self): """ Closes both ends of this Pair """ self.sender.close() self.recver.close() class Pipe(object): """ :: +------+ send --> | Pipe | --> recv +------+ The most basic primitive is the Pipe. A Pipe has exactly one sender and exactly one recver. A Pipe has no buffering, so send and recvs will block until there is a corresponding send or recv. For example, the following code will deadlock as the sender will block, preventing the recv from ever being called:: h = vanilla.Hub() p = h.pipe() p.send(1) # deadlock p.recv() The following is OK as the send is spawned to a background green thread:: h = vanilla.Hub() p = h.pipe() h.spawn(p.send, 1) p.recv() # returns 1 """ def __new__(cls, hub): self = super(Pipe, cls).__new__(cls) self.hub = hub self.closed = False recver = Recver(self) self.recver = weakref.ref(recver, self.on_abandoned) self.recver_current = None sender = Sender(self) self.sender = weakref.ref(sender, self.on_abandoned) self.sender_current = None return Pair(sender, recver) def on_abandoned(self, *a, **kw): remaining = self.recver() or self.sender() if remaining: # this is running from a preemptive callback triggered by the # garbage collector. we spawn the abandon clean up in order to pull # execution back under a green thread owned by our hub, and to # minimize the amount of code running while preempted. note this # means spawning needs to be atomic. self.hub.spawn(remaining.abandoned) class End(object): def __init__(self, pipe): self.middle = pipe @property def hub(self): return self.middle.hub @property def halted(self): return bool(self.middle.closed or self.other is None) @property def ready(self): if self.middle.closed: raise vanilla.exception.Closed if self.other is None: raise vanilla.exception.Abandoned return bool(self.other.current) def select(self): assert self.current is None self.current = getcurrent() def unselect(self): assert self.current == getcurrent() self.current = None def abandoned(self): if self.current: self.hub.throw_to(self.current, vanilla.exception.Abandoned) @property def peak(self): return self.current def pause(self, timeout=-1): self.select() try: _, ret = self.hub.pause(timeout=timeout) finally: self.unselect() return ret def onclose(self, f, *a, **kw): if not hasattr(self.middle, 'closers'): self.middle.closers = [(f, a, kw)] else: self.middle.closers.append((f, a, kw)) def close(self, exception=vanilla.exception.Closed): closers = getattr(self.middle, 'closers', []) if closers: del self.middle.closers self.middle.closed = True if self.other is not None and bool(self.other.current): self.hub.throw_to(self.other.current, exception) for f, a, kw in closers: try: f(*a, **kw) except vanilla.exception.Halt: pass def stop(self): self.close(exception=vanilla.exception.Stop) class Sender(End): @property def current(self): return self.middle.sender_current @current.setter def current(self, value): self.middle.sender_current = value @property def other(self): return self.middle.recver() def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ if not self.ready: self.pause(timeout=timeout) if isinstance(item, Exception): return self.hub.throw_to(self.other.peak, item) return self.hub.switch_to(self.other.peak, self.other, item) def handover(self, recver): assert recver.ready recver.select() # switch directly, as we need to pause _, ret = recver.other.peak.switch(recver.other, None) recver.unselect() return ret def clear(self): self.send(NoState) def connect(self, recver): """ Rewire: s1 -> m1 <- r1 --> s2 -> m2 <- r2 To: s1 -> m1 <- r2 """ r1 = recver m1 = r1.middle s2 = self m2 = self.middle r2 = self.other r2.middle = m1 del m2.sender del m2.recver del m1.recver m1.recver = weakref.ref(r2, m1.on_abandoned) m1.recver_current = m2.recver_current del r1.middle del s2.middle # if we are currently a chain, return the last recver of our chain while True: if getattr(r2, 'downstream', None) is None: break r2 = r2.downstream.other return r2 class Recver(End): @property def current(self): return self.middle.recver_current @current.setter def current(self, value): self.middle.recver_current = value @property def other(self): return self.middle.sender() def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ if self.ready: return self.other.handover(self) return self.pause(timeout=timeout) def __iter__(self): while True: try: yield self.recv() except vanilla.exception.Halt: break def pipe(self, target): """ Pipes this Recver to *target*. *target* can either be `Sender`_ (or `Pair`_) or a callable. If *target* is a Sender, the two pairs are rewired so that sending on this Recver's Sender will now be directed to the target's Recver:: sender1, recver1 = h.pipe() sender2, recver2 = h.pipe() recver1.pipe(sender2) h.spawn(sender1.send, 'foo') recver2.recv() # returns 'foo' If *target* is a callable, a new `Pipe`_ will be created. This Recver and the new Pipe's Sender are passed to the target callable to act as upstream and downstream. The callable can then do any processing desired including filtering, mapping and duplicating packets:: sender, recver = h.pipe() def pipeline(upstream, downstream): for i in upstream: if i % 2: downstream.send(i*2) recver = recver.pipe(pipeline) @h.spawn def _(): for i in xrange(10): sender.send(i) recver.recv() # returns 2 (0 is filtered, so 1*2) recver.recv() # returns 6 (2 is filtered, so 3*2) """ if callable(target): sender, recver = self.hub.pipe() # link the two ends in the closure with a strong reference to # prevent them from being garbage collected if this piped section # is used in a chain self.downstream = sender sender.upstream = self @self.hub.spawn def _(): try: target(self, sender) except vanilla.exception.Halt: sender.close() return recver else: return target.connect(self) def map(self, f): """ *f* is a callable that takes a single argument. All values sent on this Recver's Sender will be passed to *f* to be transformed:: def double(i): return i * 2 sender, recver = h.pipe() recver.map(double) h.spawn(sender.send, 2) recver.recv() # returns 4 """ @self.pipe def recver(recver, sender): for item in recver: try: sender.send(f(item)) except Exception, e: sender.send(e) return recver def consume(self, f): """ Creates a sink which consumes all values for this Recver. *f* is a callable which takes a single argument. All values sent on this Recver's Sender will be passed to *f* for processing. Unlike *map* however consume terminates this chain:: sender, recver = h.pipe @recver.consume def _(data): logging.info(data) sender.send('Hello') # logs 'Hello' """ @self.hub.spawn def _(): for item in self: # TODO: think through whether trapping for HALT here is a good # idea try: f(item) except vanilla.exception.Halt: self.close() break class Dealer(object): """ :: +--------+ /--> recv send --> | Dealer | -+ +--------+ \--> recv A Dealer has exactly one sender but can have many recvers. It has no buffer, so sends and recvs block until a corresponding green thread is ready. Sends are round robined to waiting recvers on a first come first serve basis:: h = vanilla.Hub() d = h.dealer() # d.send(1) # this would deadlock as there are no recvers h.spawn(lambda: 'recv 1: %s' % d.recv()) h.spawn(lambda: 'recv 2: %s' % d.recv()) d.send(1) d.send(2) """ class Recver(Recver): def select(self): assert getcurrent() not in self.current self.current.append(getcurrent()) def unselect(self): self.current.remove(getcurrent()) @property def peak(self): return self.current[0] def abandoned(self): waiters = list(self.current) for current in waiters: self.hub.throw_to(current, vanilla.exception.Abandoned) def __new__(cls, hub): sender, recver = hub.pipe() recver.__class__ = Dealer.Recver recver.current = collections.deque() return Pair(sender, recver) class Router(object): """ :: send --\ +--------+ +-> | Router | --> recv send --/ +--------+ A Router has exactly one recver but can have many senders. It has no buffer, so sends and recvs block until a corresponding thread is ready. Sends are accepted on a first come first servce basis:: h = vanilla.Hub() r = h.router() h.spawn(r.send, 3) h.spawn(r.send, 2) h.spawn(r.send, 1) r.recv() # returns 3 r.recv() # returns 2 r.recv() # returns 1 """ class Sender(Sender): def select(self): assert getcurrent() not in self.current self.current.append(getcurrent()) def unselect(self): self.current.remove(getcurrent()) @property def peak(self): return self.current[0] def abandoned(self): waiters = list(self.current) for current in waiters: self.hub.throw_to(current, vanilla.exception.Abandoned) def connect(self, recver): self.onclose(recver.close) recver.consume(self.send) def __new__(cls, hub): sender, recver = hub.pipe() sender.__class__ = Router.Sender sender.current = collections.deque() return Pair(sender, recver) class Broadcast(object): def __init__(self, hub): self.hub = hub self.subscribers = [] self.emptiers = [] def onempty(self, f, *a, **kw): self.emptiers.append((f, a, kw)) def send(self, item): for subscriber in self.subscribers: subscriber.send(item) def unsubscribe(self, sender): self.subscribers.remove(sender) if not self.subscribers: emptiers = self.emptiers self.emptiers = [] for f, a, kw in emptiers: f(*a, **kw) def subscribe(self): sender, recver = self.hub.pipe() recver.onclose(self.unsubscribe, sender) self.subscribers.append(sender) return recver def connect(self, recver): # TODO: this probably should wire onclose to recver.close recver.consume(self.send) class State(object): """ State is a specialized `Pipe`_ which maintains the state of a previous send. Sends never block, but modify the object's current state. When the current state is unset, a recv will block until the state is set. If state is set, recvs never block as well, and return the current state. State can cleared using the *clear* method:: s = h.state() s.recv() # this will deadlock as state is not set s.send(3) # sets state, note the send doesn't block even though there # is no recver s.recv() # 3 s.recv() # 3 - note subsequent recvs don't block s.clear() # clear the current state s.recv() # this will deadlock as state is not set """ class G(object): def __init__(self, hub, state): self.hub = hub self.state = state # ignore throws def throw(self, *a, **kw): self.hub.pause() def __nonzero__(self): return self.state != NoState class Sender(Sender): def init_state(self, item): self.current = State.G(self.hub, item) def send(self, item, timeout=-1): self.current.state = item if self.ready and self.current: return self.hub.switch_to(self.other.peak, self.other, item) def handover(self, recver): assert recver.ready return self.current.state def connect(self, recver): self.onclose(recver.close) recver.consume(self.send) return self.other def __new__(cls, hub, state=NoState): sender, recver = hub.pipe() sender.__class__ = State.Sender sender.init_state(state) return Pair(sender, recver) class Stream(object): """ A `Stream`_ is a specialized `Recver`_ which provides additional methods for working with streaming sources, particularly sockets and file descriptors. """ class Recver(Recver): def recv(self, timeout=-1): if self.extra: extra = self.extra self.extra = '' return extra return super(Stream.Recver, self).recv(timeout=timeout) def recv_n(self, n, timeout=-1): """ Blocks until *n* bytes of data are available, and then returns them. """ got = '' if n: while len(got) < n: got += self.recv(timeout=timeout) got, self.extra = got[:n], got[n:] return got def recv_partition(self, sep, timeout=-1): """ Blocks until the seperator *sep* is seen in the stream, and then returns all data received until *sep*. """ got = '' while True: got += self.recv(timeout=timeout) keep, matched, extra = got.partition(sep) if matched: self.extra = extra return keep def recv_line(self, timeout=-1): """ Short hand to receive a line from the stream. The line seperator defaults to '\\n' but can be changed by setting recver.sep on this recver. """ return self.recv_partition(self.sep, timeout=timeout) def __new__(cls, recver, sep='\n'): recver.__class__ = Stream.Recver recver.extra = '' recver.sep = sep return recver
cablehead/vanilla
vanilla/message.py
Pair.send
python
def send(self, item, timeout=-1): return self.sender.send(item, timeout=timeout)
Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds.
train
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L39-L44
null
class Pair(Pair): """ A Pair is a tuple of a `Sender`_ and a `Recver`_. The pair only share a weakref to each other so unless a reference is kept to both ends, the remaining end will be *abandoned* and the entire pair will be garbage collected. It's possible to call methods directly on the Pair tuple. A common pattern though is to split up the tuple with the `Sender`_ used in one closure and the `Recver`_ in another:: # create a Pipe Pair p = h.pipe() # call the Pair tuple directly h.spawn(p.send, '1') p.recv() # returns '1' # split the sender and recver sender, recver = p sender.send('2') recver.recv() # returns '2' """ def clear(self): self.sender.clear() return self def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ return self.recver.recv(timeout=timeout) def recv_n(self, n, timeout=-1): return self.recver.recv_n(n, timeout=timeout) def recv_partition(self, sep, timeout=-1): return self.recver.recv_partition(sep, timeout=timeout) def recv_line(self, timeout=-1): return self.recver.recv_line(timeout=timeout) def pipe(self, target): """ Pipes are Recver to the target; see :meth:`vanilla.core.Recver.pipe` Returns a new Pair of our current Sender and the target's Recver. """ return self._replace(recver=self.recver.pipe(target)) def map(self, f): """ Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map` Returns a new Pair of our current Sender and the mapped target's Recver. """ return self._replace(recver=self.recver.map(f)) def consume(self, f): """ Consumes this Pair with *f*; see :meth:`vanilla.core.Recver.consume`. Returns only our Sender """ self.recver.consume(f) return self.sender def connect(self, recver): # TODO: shouldn't this return a new Pair? return self.sender.connect(recver) def onclose(self, f, *a, **kw): self.recver.onclose(f, *a, **kw) def close(self): """ Closes both ends of this Pair """ self.sender.close() self.recver.close()
cablehead/vanilla
vanilla/message.py
Pair.pipe
python
def pipe(self, target): return self._replace(recver=self.recver.pipe(target))
Pipes are Recver to the target; see :meth:`vanilla.core.Recver.pipe` Returns a new Pair of our current Sender and the target's Recver.
train
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L66-L72
null
class Pair(Pair): """ A Pair is a tuple of a `Sender`_ and a `Recver`_. The pair only share a weakref to each other so unless a reference is kept to both ends, the remaining end will be *abandoned* and the entire pair will be garbage collected. It's possible to call methods directly on the Pair tuple. A common pattern though is to split up the tuple with the `Sender`_ used in one closure and the `Recver`_ in another:: # create a Pipe Pair p = h.pipe() # call the Pair tuple directly h.spawn(p.send, '1') p.recv() # returns '1' # split the sender and recver sender, recver = p sender.send('2') recver.recv() # returns '2' """ def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ return self.sender.send(item, timeout=timeout) def clear(self): self.sender.clear() return self def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ return self.recver.recv(timeout=timeout) def recv_n(self, n, timeout=-1): return self.recver.recv_n(n, timeout=timeout) def recv_partition(self, sep, timeout=-1): return self.recver.recv_partition(sep, timeout=timeout) def recv_line(self, timeout=-1): return self.recver.recv_line(timeout=timeout) def map(self, f): """ Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map` Returns a new Pair of our current Sender and the mapped target's Recver. """ return self._replace(recver=self.recver.map(f)) def consume(self, f): """ Consumes this Pair with *f*; see :meth:`vanilla.core.Recver.consume`. Returns only our Sender """ self.recver.consume(f) return self.sender def connect(self, recver): # TODO: shouldn't this return a new Pair? return self.sender.connect(recver) def onclose(self, f, *a, **kw): self.recver.onclose(f, *a, **kw) def close(self): """ Closes both ends of this Pair """ self.sender.close() self.recver.close()
cablehead/vanilla
vanilla/message.py
Pair.map
python
def map(self, f): return self._replace(recver=self.recver.map(f))
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map` Returns a new Pair of our current Sender and the mapped target's Recver.
train
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L74-L81
null
class Pair(Pair): """ A Pair is a tuple of a `Sender`_ and a `Recver`_. The pair only share a weakref to each other so unless a reference is kept to both ends, the remaining end will be *abandoned* and the entire pair will be garbage collected. It's possible to call methods directly on the Pair tuple. A common pattern though is to split up the tuple with the `Sender`_ used in one closure and the `Recver`_ in another:: # create a Pipe Pair p = h.pipe() # call the Pair tuple directly h.spawn(p.send, '1') p.recv() # returns '1' # split the sender and recver sender, recver = p sender.send('2') recver.recv() # returns '2' """ def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ return self.sender.send(item, timeout=timeout) def clear(self): self.sender.clear() return self def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ return self.recver.recv(timeout=timeout) def recv_n(self, n, timeout=-1): return self.recver.recv_n(n, timeout=timeout) def recv_partition(self, sep, timeout=-1): return self.recver.recv_partition(sep, timeout=timeout) def recv_line(self, timeout=-1): return self.recver.recv_line(timeout=timeout) def pipe(self, target): """ Pipes are Recver to the target; see :meth:`vanilla.core.Recver.pipe` Returns a new Pair of our current Sender and the target's Recver. """ return self._replace(recver=self.recver.pipe(target)) def consume(self, f): """ Consumes this Pair with *f*; see :meth:`vanilla.core.Recver.consume`. Returns only our Sender """ self.recver.consume(f) return self.sender def connect(self, recver): # TODO: shouldn't this return a new Pair? return self.sender.connect(recver) def onclose(self, f, *a, **kw): self.recver.onclose(f, *a, **kw) def close(self): """ Closes both ends of this Pair """ self.sender.close() self.recver.close()
cablehead/vanilla
vanilla/message.py
Sender.send
python
def send(self, item, timeout=-1): if not self.ready: self.pause(timeout=timeout) if isinstance(item, Exception): return self.hub.throw_to(self.other.peak, item) return self.hub.switch_to(self.other.peak, self.other, item)
Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds.
train
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L243-L254
[ "def pause(self, timeout=-1):\n self.select()\n try:\n _, ret = self.hub.pause(timeout=timeout)\n finally:\n self.unselect()\n return ret\n" ]
class Sender(End): @property def current(self): return self.middle.sender_current @current.setter def current(self, value): self.middle.sender_current = value @property def other(self): return self.middle.recver() def handover(self, recver): assert recver.ready recver.select() # switch directly, as we need to pause _, ret = recver.other.peak.switch(recver.other, None) recver.unselect() return ret def clear(self): self.send(NoState) def connect(self, recver): """ Rewire: s1 -> m1 <- r1 --> s2 -> m2 <- r2 To: s1 -> m1 <- r2 """ r1 = recver m1 = r1.middle s2 = self m2 = self.middle r2 = self.other r2.middle = m1 del m2.sender del m2.recver del m1.recver m1.recver = weakref.ref(r2, m1.on_abandoned) m1.recver_current = m2.recver_current del r1.middle del s2.middle # if we are currently a chain, return the last recver of our chain while True: if getattr(r2, 'downstream', None) is None: break r2 = r2.downstream.other return r2