signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def blink(self, blink):
|
if blink:<EOL><INDENT>self.displaycontrol |= LCD_BLINKON<EOL><DEDENT>else:<EOL><INDENT>self.displaycontrol &= ~LCD_BLINKON<EOL><DEDENT>self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)<EOL>
|
Turn on or off cursor blinking. Set blink to True to enable blinking.
|
f8408:c0:m6
|
def move_left(self):
|
self.write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT)<EOL>
|
Move display left one position.
|
f8408:c0:m7
|
def move_right(self):
|
self.write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT)<EOL>
|
Move display right one position.
|
f8408:c0:m8
|
def set_left_to_right(self):
|
self.displaymode |= LCD_ENTRYLEFT<EOL>self.write8(LCD_ENTRYMODESET | self.displaymode)<EOL>
|
Set text direction left to right.
|
f8408:c0:m9
|
def set_right_to_left(self):
|
self.displaymode &= ~LCD_ENTRYLEFT<EOL>self.write8(LCD_ENTRYMODESET | self.displaymode)<EOL>
|
Set text direction right to left.
|
f8408:c0:m10
|
def autoscroll(self, autoscroll):
|
if autoscroll:<EOL><INDENT>self.displaymode |= LCD_ENTRYSHIFTINCREMENT<EOL><DEDENT>else:<EOL><INDENT>self.displaymode &= ~LCD_ENTRYSHIFTINCREMENT<EOL><DEDENT>self.write8(LCD_ENTRYMODESET | self.displaymode)<EOL>
|
Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text.
|
f8408:c0:m11
|
def message(self, text):
|
line = <NUM_LIT:0><EOL>for char in text:<EOL><INDENT>if char == '<STR_LIT:\n>':<EOL><INDENT>line += <NUM_LIT:1><EOL>col = <NUM_LIT:0> if self.displaymode & LCD_ENTRYLEFT > <NUM_LIT:0> else self._cols-<NUM_LIT:1><EOL>self.set_cursor(col, line)<EOL><DEDENT>else:<EOL><INDENT>self.write8(ord(char), True)<EOL><DEDENT><DEDENT>
|
Write text to display. Note that text can include newlines.
|
f8408:c0:m12
|
def set_backlight(self, backlight):
|
if self._backlight is not None:<EOL><INDENT>if self._pwm_enabled:<EOL><INDENT>self._pwm.set_duty_cycle(self._backlight, self._pwm_duty_cycle(backlight))<EOL><DEDENT>else:<EOL><INDENT>self._gpio.output(self._backlight, self._blpol if backlight else not self._blpol)<EOL><DEDENT><DEDENT>
|
Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity backlight.
|
f8408:c0:m13
|
def write8(self, value, char_mode=False):
|
<EOL>self._delay_microseconds(<NUM_LIT:1000>)<EOL>self._gpio.output(self._rs, char_mode)<EOL>self._gpio.output_pins({ self._d4: ((value >> <NUM_LIT:4>) & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d5: ((value >> <NUM_LIT:5>) & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d6: ((value >> <NUM_LIT:6>) & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d7: ((value >> <NUM_LIT:7>) & <NUM_LIT:1>) > <NUM_LIT:0> })<EOL>self._pulse_enable()<EOL>self._gpio.output_pins({ self._d4: (value & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d5: ((value >> <NUM_LIT:1>) & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d6: ((value >> <NUM_LIT:2>) & <NUM_LIT:1>) > <NUM_LIT:0>,<EOL>self._d7: ((value >> <NUM_LIT:3>) & <NUM_LIT:1>) > <NUM_LIT:0> })<EOL>self._pulse_enable()<EOL>
|
Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default).
|
f8408:c0:m14
|
def create_char(self, location, pattern):
|
<EOL>location &= <NUM_LIT><EOL>self.write8(LCD_SETCGRAMADDR | (location << <NUM_LIT:3>))<EOL>for i in range(<NUM_LIT:8>):<EOL><INDENT>self.write8(pattern[i], char_mode=True)<EOL><DEDENT>
|
Fill one of the first 8 CGRAM locations with custom characters.
The location parameter should be between 0 and 7 and pattern should
provide an array of 8 bytes containing the pattern. E.g. you can easyly
design your custom character at http://www.quinapalus.com/hd44780udg.html
To show your custom character use eg. lcd.message('\x01')
|
f8408:c0:m15
|
def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, red, green, blue,<EOL>gpio=GPIO.get_platform_gpio(), <EOL>invert_polarity=True,<EOL>enable_pwm=False,<EOL>pwm=PWM.get_platform_pwm(),<EOL>initial_color=(<NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:1.0>)):
|
super(Adafruit_RGBCharLCD, self).__init__(rs, en, d4, d5, d6, d7,<EOL>cols,<EOL>lines, <EOL>enable_pwm=enable_pwm,<EOL>backlight=None,<EOL>invert_polarity=invert_polarity,<EOL>gpio=gpio, <EOL>pwm=pwm)<EOL>self._red = red<EOL>self._green = green<EOL>self._blue = blue<EOL>if enable_pwm:<EOL><INDENT>rdc, gdc, bdc = self._rgb_to_duty_cycle(initial_color)<EOL>pwm.start(red, rdc)<EOL>pwm.start(green, gdc)<EOL>pwm.start(blue, bdc)<EOL><DEDENT>else:<EOL><INDENT>gpio.setup(red, GPIO.OUT)<EOL>gpio.setup(green, GPIO.OUT)<EOL>gpio.setup(blue, GPIO.OUT)<EOL>self._gpio.output_pins(self._rgb_to_pins(initial_color))<EOL><DEDENT>
|
Initialize the LCD with RGB backlight. RS, EN, and D4...D7 parameters
should be the pins connected to the LCD RS, clock enable, and data line
4 through 7 connections. The LCD will be used in its 4-bit mode so these
6 lines are the only ones required to use the LCD. You must also pass in
the number of columns and lines on the LCD.
The red, green, and blue parameters define the pins which are connected
to the appropriate backlight LEDs. The invert_polarity parameter is a
boolean that controls if the LEDs are on with a LOW or HIGH signal. By
default invert_polarity is True, i.e. the backlight LEDs are on with a
low signal. If you want to enable PWM on the backlight LEDs (for finer
control of colors) and the hardware supports PWM on the provided pins,
set enable_pwm to True. Finally you can set an explicit initial backlight
color with the initial_color parameter. The default initial color is
white (all LEDs lit).
You can optionally pass in an explicit GPIO class,
for example if you want to use an MCP230xx GPIO extender. If you don't
pass in an GPIO instance, the default GPIO for the running platform will
be used.
|
f8408:c1:m0
|
def set_color(self, red, green, blue):
|
if self._pwm_enabled:<EOL><INDENT>rdc, gdc, bdc = self._rgb_to_duty_cycle((red, green, blue))<EOL>self._pwm.set_duty_cycle(self._red, rdc)<EOL>self._pwm.set_duty_cycle(self._green, gdc)<EOL>self._pwm.set_duty_cycle(self._blue, bdc)<EOL><DEDENT>else:<EOL><INDENT>self._gpio.output_pins({self._red: self._blpol if red else not self._blpol,<EOL>self._green: self._blpol if green else not self._blpol,<EOL>self._blue: self._blpol if blue else not self._blpol })<EOL><DEDENT>
|
Set backlight color to provided red, green, and blue values. If PWM
is enabled then color components can be values from 0.0 to 1.0, otherwise
components should be zero for off and non-zero for on.
|
f8408:c1:m3
|
def set_backlight(self, backlight):
|
self.set_color(backlight, backlight, backlight)<EOL>
|
Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity backlight. On an RGB display this
function will set the backlight to all white.
|
f8408:c1:m4
|
def __init__(self, address=<NUM_LIT>, busnum=I2C.get_default_bus(), cols=<NUM_LIT:16>, lines=<NUM_LIT:2>):
|
<EOL>self._mcp = MCP.MCP23017(address=address, busnum=busnum)<EOL>self._mcp.setup(LCD_PLATE_RW, GPIO.OUT)<EOL>self._mcp.output(LCD_PLATE_RW, GPIO.LOW)<EOL>for button in (SELECT, RIGHT, DOWN, UP, LEFT):<EOL><INDENT>self._mcp.setup(button, GPIO.IN)<EOL>self._mcp.pullup(button, True)<EOL><DEDENT>super(Adafruit_CharLCDPlate, self).__init__(LCD_PLATE_RS, LCD_PLATE_EN,<EOL>LCD_PLATE_D4, LCD_PLATE_D5, LCD_PLATE_D6, LCD_PLATE_D7, cols, lines,<EOL>LCD_PLATE_RED, LCD_PLATE_GREEN, LCD_PLATE_BLUE, enable_pwm=False, <EOL>gpio=self._mcp)<EOL>
|
Initialize the character LCD plate. Can optionally specify a separate
I2C address or bus number, but the defaults should suffice for most needs.
Can also optionally specify the number of columns and lines on the LCD
(default is 16x2).
|
f8408:c2:m0
|
def is_pressed(self, button):
|
if button not in set((SELECT, RIGHT, DOWN, UP, LEFT)):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self._mcp.input(button) == GPIO.LOW<EOL>
|
Return True if the provided button is pressed, False otherwise.
|
f8408:c2:m1
|
def __init__(self, address=<NUM_LIT>, busnum=I2C.get_default_bus(), cols=<NUM_LIT:16>, lines=<NUM_LIT:2>):
|
<EOL>self._mcp = MCP.MCP23008(address=address, busnum=busnum)<EOL>super(Adafruit_CharLCDBackpack, self).__init__(LCD_BACKPACK_RS, LCD_BACKPACK_EN,<EOL>LCD_BACKPACK_D4, LCD_BACKPACK_D5, LCD_BACKPACK_D6, LCD_BACKPACK_D7,<EOL>cols, lines, LCD_BACKPACK_LITE, enable_pwm=False, gpio=self._mcp)<EOL>
|
Initialize the character LCD plate. Can optionally specify a separate
I2C address or bus number, but the defaults should suffice for most needs.
Can also optionally specify the number of columns and lines on the LCD
(default is 16x2).
|
f8408:c3:m0
|
def match(obj, matchers=TYPES):
|
buf = get_bytes(obj)<EOL>for matcher in matchers:<EOL><INDENT>if matcher.match(buf):<EOL><INDENT>return matcher<EOL><DEDENT><DEDENT>return None<EOL>
|
Matches the given input againts the available
file type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if type matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m0
|
def image(obj):
|
return match(obj, image_matchers)<EOL>
|
Matches the given input againts the available
image type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m1
|
def font(obj):
|
return match(obj, font_matchers)<EOL>
|
Matches the given input againts the available
font type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m2
|
def video(obj):
|
return match(obj, video_matchers)<EOL>
|
Matches the given input againts the available
video type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m3
|
def audio(obj):
|
return match(obj, audio_matchers)<EOL>
|
Matches the given input againts the available
autio type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m4
|
def archive(obj):
|
return match(obj, archive_matchers)<EOL>
|
Matches the given input againts the available
archive type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8413:m5
|
def is_extension_supported(ext):
|
for kind in TYPES:<EOL><INDENT>if kind.extension is ext:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Checks if the given extension string is
one of the supported by the file matchers.
Args:
ext (str): file extension string. E.g: jpg, png, mp4, mp3
Returns:
True if the file extension is supported.
Otherwise False.
|
f8423:m0
|
def is_mime_supported(mime):
|
for kind in TYPES:<EOL><INDENT>if kind.mime is mime:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Checks if the given MIME type string is
one of the supported by the file matchers.
Args:
mime (str): MIME string. E.g: image/jpeg, video/mpeg
Returns:
True if the MIME type is supported.
Otherwise False.
|
f8423:m1
|
def is_image(obj):
|
return match.image(obj) is not None<EOL>
|
Checks if a given input is a supported type image.
Args:
obj: path to file, bytes or bytearray.
Returns:
True if obj is a valid image. Otherwise False.
Raises:
TypeError: if obj is not a supported type.
|
f8423:m2
|
def is_archive(obj):
|
return match.archive(obj) is not None<EOL>
|
Checks if a given input is a supported type archive.
Args:
obj: path to file, bytes or bytearray.
Returns:
True if obj is a valid archive. Otherwise False.
Raises:
TypeError: if obj is not a supported type.
|
f8423:m3
|
def is_audio(obj):
|
return match.audio(obj) is not None<EOL>
|
Checks if a given input is a supported type audio.
Args:
obj: path to file, bytes or bytearray.
Returns:
True if obj is a valid audio. Otherwise False.
Raises:
TypeError: if obj is not a supported type.
|
f8423:m4
|
def is_video(obj):
|
return match.video(obj) is not None<EOL>
|
Checks if a given input is a supported type video.
Args:
obj: path to file, bytes or bytearray.
Returns:
True if obj is a valid video. Otherwise False.
Raises:
TypeError: if obj is not a supported type.
|
f8423:m5
|
def is_font(obj):
|
return match.font(obj) is not None<EOL>
|
Checks if a given input is a supported type font.
Args:
obj: path to file, bytes or bytearray.
Returns:
True if obj is a valid font. Otherwise False.
Raises:
TypeError: if obj is not a supported type.
|
f8423:m6
|
def get_signature_bytes(path):
|
with open(path, '<STR_LIT:rb>') as fp:<EOL><INDENT>return bytearray(fp.read(_NUM_SIGNATURE_BYTES))<EOL><DEDENT>
|
Reads file from disk and returns the first 262 bytes
of data representing the magic number header signature.
Args:
path: path string to file.
Returns:
First 262 bytes of the file content as bytearray type.
|
f8424:m0
|
def signature(array):
|
length = len(array)<EOL>index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length<EOL>return array[:index]<EOL>
|
Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type.
|
f8424:m1
|
def get_bytes(obj):
|
try:<EOL><INDENT>obj = obj.read(_NUM_SIGNATURE_BYTES)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>kind = type(obj)<EOL>if kind is bytearray:<EOL><INDENT>return signature(obj)<EOL><DEDENT>if kind is str:<EOL><INDENT>return get_signature_bytes(obj)<EOL><DEDENT>if kind is bytes:<EOL><INDENT>return signature(obj)<EOL><DEDENT>if kind is memoryview:<EOL><INDENT>return signature(obj).tolist()<EOL><DEDENT>raise TypeError('<STR_LIT>' % kind)<EOL>
|
Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supported type.
|
f8424:m2
|
def guess(obj):
|
return match(obj) if obj else None<EOL>
|
Infers the type of the given input.
Function is overloaded to accept multiple types in input
and peform the needed type inference based on it.
Args:
obj: path to file, bytes or bytearray.
Returns:
The matched type instance. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8425:m0
|
def guess_mime(obj):
|
kind = guess(obj)<EOL>return kind.mime if kind else kind<EOL>
|
Infers the file type of the given input
and returns its MIME type.
Args:
obj: path to file, bytes or bytearray.
Returns:
The matched MIME type as string. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8425:m1
|
def guess_extension(obj):
|
kind = guess(obj)<EOL>return kind.extension if kind else kind<EOL>
|
Infers the file type of the given input
and returns its RFC file extension.
Args:
obj: path to file, bytes or bytearray.
Returns:
The matched file extension as string. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
|
f8425:m2
|
def get_type(mime=None, ext=None):
|
for kind in types:<EOL><INDENT>if kind.extension is ext or kind.mime is mime:<EOL><INDENT>return kind<EOL><DEDENT><DEDENT>return None<EOL>
|
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None.
|
f8425:m3
|
def add_type(instance):
|
if not isinstance(instance, Type):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>types.insert(<NUM_LIT:0>, instance)<EOL>
|
Adds a new type matcher instance to the supported types.
Args:
instance: Type inherited instance.
Returns:
None
|
f8425:m4
|
def bounding_box(locations):
|
x_values = list(map(itemgetter(<NUM_LIT:0>), locations))<EOL>x_min, x_max = min(x_values), max(x_values)<EOL>y_values = list(map(itemgetter(<NUM_LIT:1>), locations))<EOL>y_min, y_max = min(y_values), max(y_values)<EOL>return Rect(x_min, y_min, x_max - x_min, y_max - y_min)<EOL>
|
Computes the bounding box of an iterable of (x, y) coordinates.
Args:
locations: iterable of (x, y) tuples.
Returns:
`Rect`: Coordinates of the bounding box.
|
f8435:m0
|
def convex_hull(points):
|
def is_not_clockwise(p0, p1, p2):<EOL><INDENT>return <NUM_LIT:0> <= (<EOL>(p1[<NUM_LIT:0>] - p0[<NUM_LIT:0>]) * (p2[<NUM_LIT:1>] - p0[<NUM_LIT:1>]) -<EOL>(p1[<NUM_LIT:1>] - p0[<NUM_LIT:1>]) * (p2[<NUM_LIT:0>] - p0[<NUM_LIT:0>])<EOL>)<EOL><DEDENT>def go(points_):<EOL><INDENT>res = []<EOL>for p in points_:<EOL><INDENT>while <NUM_LIT:1> < len(res) and is_not_clockwise(res[-<NUM_LIT:2>], res[-<NUM_LIT:1>], p):<EOL><INDENT>res.pop()<EOL><DEDENT>res.append(p)<EOL><DEDENT>res.pop()<EOL>return res<EOL><DEDENT>points = sorted(set(points))<EOL>hull = (<EOL>points if len(points) < <NUM_LIT:2> else chain(go(points), go(reversed(points)))<EOL>)<EOL>return list(map(Point._make, hull))<EOL>
|
Computes the convex hull of an iterable of (x, y) coordinates.
Args:
points: iterable of (x, y) tuples.
Returns:
`list`: instances of `Point` - vertices of the convex hull in
counter-clockwise order, starting from the vertex with the
lexicographically smallest coordinates.
Andrew's monotone chain algorithm. O(n log n) complexity.
https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
|
f8435:m1
|
def _windows_fnames():
|
<EOL>if sys.maxsize > <NUM_LIT:2>**<NUM_LIT:32>:<EOL><INDENT>fname = '<STR_LIT>'<EOL>dependencies = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>fname = '<STR_LIT>'<EOL>dependencies = ['<STR_LIT>']<EOL><DEDENT>return fname, dependencies<EOL>
|
For convenience during development and to aid debugging, the DLL names
are specific to the bit depth of interpreter.
This logic has its own function to make testing easier
|
f8436:m0
|
def load():
|
if '<STR_LIT>' == platform.system():<EOL><INDENT>fname, dependencies = _windows_fnames()<EOL>def load_objects(directory):<EOL><INDENT>deps = [<EOL>cdll.LoadLibrary(str(directory.joinpath(dep)))<EOL>for dep in dependencies<EOL>]<EOL>libzbar = cdll.LoadLibrary(str(directory.joinpath(fname)))<EOL>return deps, libzbar<EOL><DEDENT>try:<EOL><INDENT>dependencies, libzbar = load_objects(Path('<STR_LIT>'))<EOL><DEDENT>except OSError:<EOL><INDENT>dependencies, libzbar = load_objects(Path(__file__).parent)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path = find_library('<STR_LIT>')<EOL>if not path:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>libzbar = cdll.LoadLibrary(path)<EOL>dependencies = []<EOL><DEDENT>return libzbar, dependencies<EOL>
|
Loads the libzar shared library and its dependencies.
|
f8436:m1
|
@contextmanager<EOL>def _image():
|
image = zbar_image_create()<EOL>if not image:<EOL><INDENT>raise PyZbarError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>yield image<EOL><DEDENT>finally:<EOL><INDENT>zbar_image_destroy(image)<EOL><DEDENT><DEDENT>
|
A context manager for `zbar_image`, created and destoyed by
`zbar_image_create` and `zbar_image_destroy`.
Yields:
POINTER(zbar_image): The created image
Raises:
PyZbarError: If the image could not be created.
|
f8438:m0
|
@contextmanager<EOL>def _image_scanner():
|
scanner = zbar_image_scanner_create()<EOL>if not scanner:<EOL><INDENT>raise PyZbarError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>yield scanner<EOL><DEDENT>finally:<EOL><INDENT>zbar_image_scanner_destroy(scanner)<EOL><DEDENT><DEDENT>
|
A context manager for `zbar_image_scanner`, created and destroyed by
`zbar_image_scanner_create` and `zbar_image_scanner_destroy`.
Yields:
POINTER(zbar_image_scanner): The created scanner
Raises:
PyZbarError: If the decoder could not be created.
|
f8438:m1
|
def _symbols_for_image(image):
|
symbol = zbar_image_first_symbol(image)<EOL>while symbol:<EOL><INDENT>yield symbol<EOL>symbol = zbar_symbol_next(symbol)<EOL><DEDENT>
|
Generator of symbols.
Args:
image: `zbar_image`
Yields:
POINTER(zbar_symbol): Symbol
|
f8438:m2
|
def _decode_symbols(symbols):
|
for symbol in symbols:<EOL><INDENT>data = string_at(zbar_symbol_get_data(symbol))<EOL>symbol_type = ZBarSymbol(symbol.contents.type).name<EOL>polygon = convex_hull(<EOL>(<EOL>zbar_symbol_get_loc_x(symbol, index),<EOL>zbar_symbol_get_loc_y(symbol, index)<EOL>)<EOL>for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))<EOL>)<EOL>yield Decoded(<EOL>data=data,<EOL>type=symbol_type,<EOL>rect=bounding_box(polygon),<EOL>polygon=polygon<EOL>)<EOL><DEDENT>
|
Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
|
f8438:m3
|
def _pixel_data(image):
|
<EOL>if '<STR_LIT>' in str(type(image)):<EOL><INDENT>if '<STR_LIT:L>' != image.mode:<EOL><INDENT>image = image.convert('<STR_LIT:L>')<EOL><DEDENT>pixels = image.tobytes()<EOL>width, height = image.size<EOL><DEDENT>elif '<STR_LIT>' in str(type(image)):<EOL><INDENT>if <NUM_LIT:3> == len(image.shape):<EOL><INDENT>image = image[:, :, <NUM_LIT:0>]<EOL><DEDENT>if '<STR_LIT>' != str(image.dtype):<EOL><INDENT>image = image.astype('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>pixels = image.tobytes()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pixels = image.tostring()<EOL><DEDENT>height, width = image.shape[:<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>pixels, width, height = image<EOL>if <NUM_LIT:0> != len(pixels) % (width * height):<EOL><INDENT>raise PyZbarError(<EOL>(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>).format(len(pixels), (width * height))<EOL>)<EOL><DEDENT><DEDENT>bpp = <NUM_LIT:8> * len(pixels) // (width * height)<EOL>if <NUM_LIT:8> != bpp:<EOL><INDENT>raise PyZbarError(<EOL>'<STR_LIT>'.format(<EOL>bpp<EOL>)<EOL>)<EOL><DEDENT>return pixels, width, height<EOL>
|
Returns (pixels, width, height)
Returns:
:obj: `tuple` (pixels, width, height)
|
f8438:m4
|
def decode(image, symbols=None):
|
pixels, width, height = _pixel_data(image)<EOL>results = []<EOL>with _image_scanner() as scanner:<EOL><INDENT>if symbols:<EOL><INDENT>disable = set(ZBarSymbol).difference(symbols)<EOL>for symbol in disable:<EOL><INDENT>zbar_image_scanner_set_config(<EOL>scanner, symbol, ZBarConfig.CFG_ENABLE, <NUM_LIT:0><EOL>)<EOL><DEDENT>for symbol in symbols:<EOL><INDENT>zbar_image_scanner_set_config(<EOL>scanner, symbol, ZBarConfig.CFG_ENABLE, <NUM_LIT:1><EOL>)<EOL><DEDENT><DEDENT>with _image() as img:<EOL><INDENT>zbar_image_set_format(img, _FOURCC['<STR_LIT>'])<EOL>zbar_image_set_size(img, width, height)<EOL>zbar_image_set_data(img, cast(pixels, c_void_p), len(pixels), None)<EOL>decoded = zbar_scan_image(scanner, img)<EOL>if decoded < <NUM_LIT:0>:<EOL><INDENT>raise PyZbarError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>results.extend(_decode_symbols(_symbols_for_image(img)))<EOL><DEDENT><DEDENT><DEDENT>return results<EOL>
|
Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses
`zbar`'s default behaviour, which is to decode all symbol types.
Returns:
:obj:`list` of :obj:`Decoded`: The values decoded from barcodes.
|
f8438:m5
|
def load_libzbar():
|
global LIBZBAR<EOL>global EXTERNAL_DEPENDENCIES<EOL>if not LIBZBAR:<EOL><INDENT>libzbar, dependencies = zbar_library.load()<EOL>LIBZBAR = libzbar<EOL>EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies<EOL><DEDENT>return LIBZBAR<EOL>
|
Loads the zbar shared library and its dependencies.
Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES.
|
f8441:m0
|
def zbar_function(fname, restype, *args):
|
prototype = CFUNCTYPE(restype, *args)<EOL>return prototype((fname, load_libzbar()))<EOL>
|
Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.CFunctionType: A wrapper around the function.
|
f8441:m1
|
def __init__(self,<EOL>normalizations=None,<EOL>language='<STR_LIT>',<EOL>logger=None,<EOL>debug=False,<EOL>verbose=False):
|
self.debug = debug<EOL>self.language = language<EOL>self.logger = logger or logging.initialize_logger(debug)<EOL>self.verbose = verbose or debug<EOL>if normalizations:<EOL><INDENT>if isinstance(normalizations, STR_TYPE):<EOL><INDENT>normalizations = self._load_from_file(normalizations)<EOL><DEDENT>self.normalizations = self._parse_normalizations(normalizations)<EOL><DEDENT>
|
Inits Config class.
|
f8448:c0:m0
|
@staticmethod<EOL><INDENT>def _load_from_file(path):<DEDENT>
|
config = []<EOL>try:<EOL><INDENT>with open(path, '<STR_LIT:r>') as config_file:<EOL><INDENT>config = yaml.load(config_file)['<STR_LIT>']<EOL><DEDENT><DEDENT>except EnvironmentError as e:<EOL><INDENT>raise ConfigError('<STR_LIT>' %<EOL>e.args[<NUM_LIT:1>] if len(e.args) > <NUM_LIT:1> else e)<EOL><DEDENT>except (TypeError, KeyError) as e:<EOL><INDENT>raise ConfigError('<STR_LIT>' % e)<EOL><DEDENT>except yaml.YAMLError:<EOL><INDENT>raise ConfigError('<STR_LIT>')<EOL><DEDENT>return config<EOL>
|
Load a config file from the given path.
Load all normalizations from the config file received as
argument. It expects to find a YAML file with a list of
normalizations and arguments under the key 'normalizations'.
Args:
path: Path to YAML file.
|
f8448:c0:m1
|
@staticmethod<EOL><INDENT>def _parse_normalization(normalization):<DEDENT>
|
parsed_normalization = None<EOL>if isinstance(normalization, dict):<EOL><INDENT>if len(normalization.keys()) == <NUM_LIT:1>:<EOL><INDENT>items = list(normalization.items())[<NUM_LIT:0>]<EOL>if len(items) == <NUM_LIT:2>: <EOL><INDENT>if items[<NUM_LIT:1>] and isinstance(items[<NUM_LIT:1>], dict):<EOL><INDENT>parsed_normalization = items<EOL><DEDENT>else:<EOL><INDENT>parsed_normalization = items[<NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(normalization, STR_TYPE):<EOL><INDENT>parsed_normalization = normalization<EOL><DEDENT>return parsed_normalization<EOL>
|
Parse a normalization item.
Transform dicts into a tuple containing the normalization
options. If a string is found, the actual value is used.
Args:
normalization: Normalization to parse.
Returns:
Tuple or string containing the parsed normalization.
|
f8448:c0:m2
|
def _parse_normalizations(self, normalizations):
|
parsed_normalizations = []<EOL>if isinstance(normalizations, list):<EOL><INDENT>for item in normalizations:<EOL><INDENT>normalization = self._parse_normalization(item)<EOL>if normalization:<EOL><INDENT>parsed_normalizations.append(normalization)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ConfigError('<STR_LIT>' % type(normalizations))<EOL><DEDENT>return parsed_normalizations<EOL>
|
Returns a list of parsed normalizations.
Iterates over a list of normalizations, removing those
not correctly defined. It also transform complex items
to have a common format (list of tuples and strings).
Args:
normalizations: List of normalizations to parse.
Returns:
A list of normalizations after being parsed and curated.
|
f8448:c0:m3
|
def initialize_logger(debug):
|
level = logging.DEBUG if debug else logging.INFO<EOL>logger = logging.getLogger('<STR_LIT>')<EOL>logger.setLevel(level)<EOL>formatter = logging.Formatter('<STR_LIT>')<EOL>console_handler = logging.StreamHandler()<EOL>console_handler.setLevel(level)<EOL>console_handler.setFormatter(formatter)<EOL>logger.addHandler(console_handler)<EOL>return logger<EOL>
|
Set up logger to be used by the library.
Args:
debug: Wheter to use debug level or not.
Returns:
A logger ready to be used.
|
f8449:m0
|
def files_generator(path, recursive):
|
if recursive:<EOL><INDENT>for (path, _, files) in os.walk(path):<EOL><INDENT>for file in files:<EOL><INDENT>if not file.endswith(BATCH_EXTENSION):<EOL><INDENT>yield (path, file)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for file in os.listdir(path):<EOL><INDENT>if (os.path.isfile(os.path.join(path, file)) and<EOL>not file.endswith(BATCH_EXTENSION)):<EOL><INDENT>yield (path, file)<EOL><DEDENT><DEDENT><DEDENT>
|
Yield files found in a given path.
Walk over a given path finding and yielding all
files found on it. This can be done only on the root
directory or recursively.
Args:
path: Path to the directory.
recursive: Whether to find files recursively or not.
Yields:
A tuple for each file in the given path containing
the path and the name of the file.
|
f8451:m0
|
def lines_generator(path):
|
with open(path, '<STR_LIT:r>') as file:<EOL><INDENT>for line in file:<EOL><INDENT>yield line<EOL><DEDENT><DEDENT>
|
Yield lines in a given file.
Iterates over a file lines yielding them.
Args:
path: Path to the file.
Yields:
Lines on a given file.
|
f8451:m1
|
def __init__(self, config, cucco):
|
self._config = config<EOL>self._cucco = cucco<EOL>self._logger = config.logger<EOL>self._observer = None<EOL>self._watch = False<EOL>
|
Inits Batch class.
|
f8451:c0:m0
|
def process_file(self, path):
|
if self._config.verbose:<EOL><INDENT>self._logger.info('<STR_LIT>', path)<EOL><DEDENT>output_path = '<STR_LIT>' % (path, BATCH_EXTENSION)<EOL>with open(output_path, '<STR_LIT:w>') as file:<EOL><INDENT>for line in lines_generator(path):<EOL><INDENT>file.write('<STR_LIT>' % self._cucco.normalize(<EOL>line.encode().decode('<STR_LIT:utf-8>')))<EOL><DEDENT><DEDENT>self._logger.debug('<STR_LIT>', output_path)<EOL>
|
Process a file applying normalizations.
Get a file as input and generate a new file with the
result of applying normalizations to every single line
in the original file. The extension for the new file
will be the one defined in BATCH_EXTENSION.
Args:
path: Path to the file.
|
f8451:c0:m1
|
def process_files(self, path, recursive=False):
|
self._logger.info('<STR_LIT>', path)<EOL>for (path, file) in files_generator(path, recursive):<EOL><INDENT>if not file.endswith(BATCH_EXTENSION):<EOL><INDENT>self.process_file(os.path.join(path, file))<EOL><DEDENT><DEDENT>
|
Apply normalizations over all files in the given directory.
Iterate over all files in a given directory. Normalizations
will be applied to each file, storing the result in a new file.
The extension for the new file will be the one defined in
BATCH_EXTENSION.
Args:
path: Path to the directory.
recursive: Whether to find files recursively or not.
|
f8451:c0:m2
|
def stop_watching(self):
|
self._watch = False<EOL>if self._observer:<EOL><INDENT>self._logger.info('<STR_LIT>')<EOL>self._observer.stop()<EOL>self._logger.info('<STR_LIT>')<EOL><DEDENT>
|
Stop watching for files.
Stop the observer started by watch function and finish
thread life.
|
f8451:c0:m3
|
def watch(self, path, recursive=False):
|
self._logger.info('<STR_LIT>', path)<EOL>handler = FileHandler(self)<EOL>self._observer = Observer()<EOL>self._observer.schedule(handler, path, recursive)<EOL>self._logger.info('<STR_LIT>')<EOL>self._observer.start()<EOL>self._watch = True<EOL>try:<EOL><INDENT>self._logger.info('<STR_LIT>')<EOL>while self._watch:<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>except KeyboardInterrupt: <EOL><INDENT>self.stop_watching()<EOL><DEDENT>self._observer.join()<EOL>
|
Watch for files in a directory and apply normalizations.
Watch for new or changed files in a directory and apply
normalizations over them.
Args:
path: Path to the directory.
recursive: Whether to find files recursively or not.
|
f8451:c0:m4
|
def __init__(self, batch):
|
self._batch = batch<EOL>self._logger = batch._logger<EOL>
|
Inits Batch class.
|
f8451:c1:m0
|
def _process_event(self, event):
|
if (not event.is_directory and<EOL>not event.src_path.endswith(BATCH_EXTENSION)):<EOL><INDENT>self._logger.info('<STR_LIT>', event.src_path)<EOL>self._batch.process_file(event.src_path)<EOL><DEDENT>
|
Process received events.
Process events received, applying normalization for those
events referencing a new or changed file and only if it's
not the result of a previous normalization.
Args:
event: Event to process.
|
f8451:c1:m1
|
def on_created(self, event):
|
self._logger.debug('<STR_LIT>', event.src_path)<EOL>self._process_event(event)<EOL>
|
Function called everytime a new file is created.
Args:
event: Event to process.
|
f8451:c1:m2
|
def on_modified(self, event):
|
self._logger.debug('<STR_LIT>', event.src_path)<EOL>self._process_event(event)<EOL>
|
Function called everytime a new file is modified.
Args:
event: Event to process.
|
f8451:c1:m3
|
@click.command()<EOL>@click.argument('<STR_LIT:path>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@click.pass_context<EOL>def batch(ctx, path, recursive, watch):
|
batch = Batch(ctx.obj['<STR_LIT>'], ctx.obj['<STR_LIT>'])<EOL>if os.path.exists(path):<EOL><INDENT>if watch:<EOL><INDENT>batch.watch(path, recursive)<EOL><DEDENT>elif os.path.isfile(path):<EOL><INDENT>batch.process_file(path)<EOL><DEDENT>else:<EOL><INDENT>batch.process_files(path, recursive)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>click.echo('<STR_LIT>', err=True)<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>
|
Normalize files in a path.
Apply normalizations over all files found in a given path.
The normalizations applied will be those defined in the config
file. If no config is specified, the default normalizations will
be used.
|
f8452:m0
|
@click.command()<EOL>@click.argument('<STR_LIT:text>', required=False)<EOL>@click.pass_context<EOL>def normalize(ctx, text):
|
if text:<EOL><INDENT>click.echo(ctx.obj['<STR_LIT>'].normalize(text))<EOL><DEDENT>else:<EOL><INDENT>for line in sys.stdin:<EOL><INDENT>click.echo(ctx.obj['<STR_LIT>'].normalize(line))<EOL><DEDENT><DEDENT>
|
Normalize text or piped input.
Normalize text passed as an argument to this command using
the specified config (default values if --config option is
not used).
Pipes can be used along this command to process the output
of another cli. This is the default behaviour when no text
is defined.
|
f8452:m1
|
@click.group()<EOL>@click.option('<STR_LIT>', '<STR_LIT:-c>',<EOL>help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', default='<STR_LIT>',<EOL>help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@click.version_option()<EOL>@click.pass_context<EOL>def cli(ctx, config, debug, language, verbose):
|
ctx.obj = {}<EOL>try:<EOL><INDENT>ctx.obj['<STR_LIT>'] = Config(normalizations=config,<EOL>language=language,<EOL>debug=debug,<EOL>verbose=verbose)<EOL><DEDENT>except ConfigError as e:<EOL><INDENT>click.echo(e.message)<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>ctx.obj['<STR_LIT>'] = Cucco(ctx.obj['<STR_LIT>'])<EOL>
|
Cucco allows to apply normalizations to a given text or file.
This normalizations include, among others, removal of accent
marks, stop words an extra white spaces, replacement of
punctuation symbols, emails, emojis, etc.
For more info on how to use and configure Cucco, check the
project website at https://cucco.io.
|
f8452:m2
|
def _load_stop_words(self, language=None):
|
self._logger.debug('<STR_LIT>')<EOL>loaded = False<EOL>if language:<EOL><INDENT>file_path = '<STR_LIT>' + language<EOL>loaded = self._parse_stop_words_file(os.path.join(PATH, file_path))<EOL><DEDENT>else:<EOL><INDENT>for file in os.listdir(os.path.join(PATH, '<STR_LIT:data>')):<EOL><INDENT>loaded = self._parse_stop_words_file(os.path.join(PATH, '<STR_LIT:data>', file)) or loaded<EOL><DEDENT><DEDENT>return loaded<EOL>
|
Load stop words into __stop_words set.
Stop words will be loaded according to the language code
received during instantiation.
Args:
language: Language code.
Returns:
A boolean indicating whether a file was loaded.
|
f8454:c0:m1
|
@staticmethod<EOL><INDENT>def _parse_normalizations(normalizations):<DEDENT>
|
str_type = str if sys.version_info[<NUM_LIT:0>] > <NUM_LIT:2> else (str, unicode)<EOL>for normalization in normalizations:<EOL><INDENT>yield (normalization, {}) if isinstance(normalization, str_type) else normalization<EOL><DEDENT>
|
Parse and yield normalizations.
Parse normalizations parameter that yield all normalizations and
arguments found on it.
Args:
normalizations: List of normalizations.
Yields:
A tuple with a parsed normalization. The first item will
contain the normalization name and the second will be a dict
with the arguments to be used for the normalization.
|
f8454:c0:m2
|
def _parse_stop_words_file(self, path):
|
language = None<EOL>loaded = False<EOL>if os.path.isfile(path):<EOL><INDENT>self._logger.debug('<STR_LIT>', path)<EOL>language = path.split('<STR_LIT:->')[-<NUM_LIT:1>]<EOL>if not language in self.__stop_words:<EOL><INDENT>self.__stop_words[language] = set()<EOL><DEDENT>with codecs.open(path, '<STR_LIT:r>', '<STR_LIT>') as file:<EOL><INDENT>loaded = True<EOL>for word in file:<EOL><INDENT>self.__stop_words[language].add(word.strip())<EOL><DEDENT><DEDENT><DEDENT>return loaded<EOL>
|
Load stop words from the given path.
Parse the stop words file, saving each word found in it in a set
for the language of the file. This language is obtained from
the file name. If the file doesn't exist, the method will have
no effect.
Args:
path: Path to the stop words file.
Returns:
A boolean indicating whether the file was loaded.
|
f8454:c0:m3
|
def normalize(self, text, normalizations=None):
|
for normalization, kwargs in self._parse_normalizations(<EOL>normalizations or self._config.normalizations):<EOL><INDENT>try:<EOL><INDENT>text = getattr(self, normalization)(text, **kwargs)<EOL><DEDENT>except AttributeError as e:<EOL><INDENT>self._logger.debug('<STR_LIT>', e)<EOL><DEDENT><DEDENT>return text<EOL>
|
Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list of
parameters and will be executed in that order.
Args:
text: The text to be processed.
normalizations: List of normalizations to apply.
Returns:
The text normalized.
|
f8454:c0:m4
|
@staticmethod<EOL><INDENT>def remove_accent_marks(text, excluded=None):<DEDENT>
|
if excluded is None:<EOL><INDENT>excluded = set()<EOL><DEDENT>return unicodedata.normalize(<EOL>'<STR_LIT>', '<STR_LIT>'.join(<EOL>c for c in unicodedata.normalize(<EOL>'<STR_LIT>', text) if unicodedata.category(c) != '<STR_LIT>' or c in excluded))<EOL>
|
Remove accent marks from input text.
This function removes accent marks in the text, but leaves
unicode characters defined in the 'excluded' parameter.
Args:
text: The text to be processed.
excluded: Set of unicode characters to exclude.
Returns:
The text without accent marks.
|
f8454:c0:m5
|
@staticmethod<EOL><INDENT>def remove_extra_white_spaces(text):<DEDENT>
|
return '<STR_LIT:U+0020>'.join(text.split())<EOL>
|
Remove extra white spaces from input text.
This function removes white spaces from the beginning and
the end of the string, but also duplicates white spaces
between words.
Args:
text: The text to be processed.
Returns:
The text without extra white spaces.
|
f8454:c0:m6
|
def remove_stop_words(self, text, ignore_case=True, language=None):
|
if not language:<EOL><INDENT>language = self._config.language<EOL><DEDENT>if language not in self.__stop_words:<EOL><INDENT>if not self._load_stop_words(language):<EOL><INDENT>self._logger.error('<STR_LIT>')<EOL>return text<EOL><DEDENT><DEDENT>return '<STR_LIT:U+0020>'.join(word for word in text.split('<STR_LIT:U+0020>') if (<EOL>word.lower() if ignore_case else word) not in self.__stop_words[language])<EOL>
|
Remove stop words.
Stop words are loaded on class instantiation according
to the specified language.
Args:
text: The text to be processed.
ignore_case: Whether or not to ignore case.
language: Code of the language to use (defaults to 'en').
Returns:
The text without stop words.
|
f8454:c0:m7
|
def replace_characters(self, text, characters, replacement='<STR_LIT>'):
|
if not characters:<EOL><INDENT>return text<EOL><DEDENT>characters = '<STR_LIT>'.join(sorted(characters))<EOL>if characters in self._characters_regexes:<EOL><INDENT>characters_regex = self._characters_regexes[characters]<EOL><DEDENT>else:<EOL><INDENT>characters_regex = re.compile("<STR_LIT>" % re.escape(characters))<EOL>self._characters_regexes[characters] = characters_regex<EOL><DEDENT>return characters_regex.sub(replacement, text)<EOL>
|
Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
replacement: New text that will replace the custom characters.
Returns:
The text without the given characters.
|
f8454:c0:m8
|
@staticmethod<EOL><INDENT>def replace_emails(text, replacement='<STR_LIT>'):<DEDENT>
|
return re.sub(regex.EMAIL_REGEX, replacement, text)<EOL>
|
Remove emails address from text.
Removes email addresses from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
replacement: New text that will replace email addresses.
Returns:
The text without email addresses.
|
f8454:c0:m9
|
@staticmethod<EOL><INDENT>def replace_emojis(text, replacement='<STR_LIT>'):<DEDENT>
|
return regex.EMOJI_REGEX.sub(replacement, text)<EOL>
|
Remove emojis from text.
Removes emojis from input text or replaces them with a
string if specified.
Args:
text: The text to be processed.
replacement: New text that will replace emojis.
Returns:
The text without emojis.
|
f8454:c0:m10
|
@staticmethod<EOL><INDENT>def replace_hyphens(text, replacement='<STR_LIT:U+0020>'):<DEDENT>
|
return text.replace('<STR_LIT:->', replacement)<EOL>
|
Replace hyphens in text.
Replaces hyphens from input text with a whitespace or a
string if specified.
Args:
text: The text to be processed.
replacement: New text that will replace the hyphens.
Returns:
The text without hyphens.
|
f8454:c0:m11
|
def replace_punctuation(self, text, excluded=None, replacement='<STR_LIT>'):
|
if excluded is None:<EOL><INDENT>excluded = set()<EOL><DEDENT>elif not isinstance(excluded, set):<EOL><INDENT>excluded = set(excluded)<EOL><DEDENT>punct = '<STR_LIT>'.join(self.__punctuation.difference(excluded))<EOL>return self.replace_characters(<EOL>text, characters=punct, replacement=replacement)<EOL>
|
Replace punctuation symbols in text.
Removes punctuation from input text or replaces them with a
string if specified. Characters replaced will be those
in string.punctuation.
Args:
text: The text to be processed.
excluded: Set of characters to exclude.
replacement: New text that will replace punctuation.
Returns:
The text without punctuation.
|
f8454:c0:m12
|
@staticmethod<EOL><INDENT>def replace_symbols(<EOL>text,<EOL>form='<STR_LIT>',<EOL>excluded=None,<EOL>replacement='<STR_LIT>'):<DEDENT>
|
if excluded is None:<EOL><INDENT>excluded = set()<EOL><DEDENT>categories = set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>return '<STR_LIT>'.join(c if unicodedata.category(c) not in categories or c in excluded<EOL>else replacement for c in unicodedata.normalize(form, text))<EOL>
|
Replace symbols in text.
Removes symbols from input text or replaces them with a
string if specified.
Args:
text: The text to be processed.
form: Unicode form.
excluded: Set of unicode characters to exclude.
replacement: New text that will replace symbols.
Returns:
The text without symbols.
|
f8454:c0:m13
|
@staticmethod<EOL><INDENT>def replace_urls(text, replacement='<STR_LIT>'):<DEDENT>
|
return re.sub(regex.URL_REGEX, replacement, text)<EOL>
|
Replace URLs in text.
Removes URLs from input text or replaces them with a
string if specified.
Args:
text: The text to be processed.
replacement: New text that will replace URLs.
Returns:
The text without URLs.
|
f8454:c0:m14
|
def preprocess_xarray(func):
|
@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>args = tuple(a.metpy.unit_array if isinstance(a, xr.DataArray) else a for a in args)<EOL>kwargs = {name: (v.metpy.unit_array if isinstance(v, xr.DataArray) else v)<EOL>for name, v in kwargs.items()}<EOL>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
|
Decorate a function to convert all DataArray arguments to pint.Quantities.
This uses the metpy xarray accessors to do the actual conversion.
|
f8456:m0
|
def check_matching_coordinates(func):
|
@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>data_arrays = ([a for a in args if isinstance(a, xr.DataArray)]<EOL>+ [a for a in kwargs.values() if isinstance(a, xr.DataArray)])<EOL>if len(data_arrays) > <NUM_LIT:1>:<EOL><INDENT>first = data_arrays[<NUM_LIT:0>]<EOL>for other in data_arrays[<NUM_LIT:1>:]:<EOL><INDENT>if not first.metpy.coordinates_identical(other):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
|
Decorate a function to make sure all given DataArrays have matching coordinates.
|
f8456:m1
|
def _reassign_quantity_indexer(data, indexers):
|
def _to_magnitude(val, unit):<EOL><INDENT>try:<EOL><INDENT>return val.to(unit).m<EOL><DEDENT>except AttributeError:<EOL><INDENT>return val<EOL><DEDENT><DEDENT>for coord_name in indexers:<EOL><INDENT>if (isinstance(data, xr.DataArray) and coord_name not in data.dims<EOL>and coord_name in readable_to_cf_axes):<EOL><INDENT>axis = coord_name<EOL>coord_name = next(data.metpy.coordinates(axis)).name<EOL>indexers[coord_name] = indexers[axis]<EOL>del indexers[axis]<EOL><DEDENT>if isinstance(indexers[coord_name], slice):<EOL><INDENT>start = _to_magnitude(indexers[coord_name].start, data[coord_name].metpy.units)<EOL>stop = _to_magnitude(indexers[coord_name].stop, data[coord_name].metpy.units)<EOL>step = _to_magnitude(indexers[coord_name].step, data[coord_name].metpy.units)<EOL>indexers[coord_name] = slice(start, stop, step)<EOL><DEDENT>indexers[coord_name] = _to_magnitude(indexers[coord_name],<EOL>data[coord_name].metpy.units)<EOL><DEDENT>return indexers<EOL>
|
Reassign a units.Quantity indexer to units of relevant coordinate.
|
f8456:m2
|
def __init__(self, data_array):
|
self._data_array = data_array<EOL>self._units = self._data_array.attrs.get('<STR_LIT>', '<STR_LIT>')<EOL>
|
Initialize accessor with a DataArray.
|
f8456:c0:m0
|
@property<EOL><INDENT>def unit_array(self):<DEDENT>
|
return self._data_array.values * self.units<EOL>
|
Return data values as a `pint.Quantity`.
|
f8456:c0:m2
|
@unit_array.setter<EOL><INDENT>def unit_array(self, values):<DEDENT>
|
self._data_array.values = values<EOL>self._units = self._data_array.attrs['<STR_LIT>'] = str(values.units)<EOL>
|
Set data values as a `pint.Quantity`.
|
f8456:c0:m3
|
def convert_units(self, units):
|
self.unit_array = self.unit_array.to(units)<EOL>
|
Convert the data values to different units in-place.
|
f8456:c0:m4
|
@property<EOL><INDENT>def crs(self):<DEDENT>
|
if '<STR_LIT>' in self._data_array.coords:<EOL><INDENT>return self._data_array.coords['<STR_LIT>'].item()<EOL><DEDENT>raise AttributeError('<STR_LIT>')<EOL>
|
Provide easy access to the `crs` coordinate.
|
f8456:c0:m5
|
@property<EOL><INDENT>def cartopy_crs(self):<DEDENT>
|
return self.crs.to_cartopy()<EOL>
|
Return the coordinate reference system (CRS) as a cartopy object.
|
f8456:c0:m6
|
@property<EOL><INDENT>def cartopy_globe(self):<DEDENT>
|
return self.crs.cartopy_globe<EOL>
|
Return the globe belonging to the coordinate reference system (CRS).
|
f8456:c0:m7
|
def _axis(self, axis):
|
if axis in readable_to_cf_axes:<EOL><INDENT>for coord_var in self._data_array.coords.values():<EOL><INDENT>if coord_var.attrs.get('<STR_LIT>') == readable_to_cf_axes[axis]:<EOL><INDENT>return coord_var<EOL><DEDENT><DEDENT>raise AttributeError(axis + '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise AttributeError('<STR_LIT>' + axis + '<STR_LIT>')<EOL><DEDENT>
|
Return the coordinate variable corresponding to the given individual axis type.
|
f8456:c0:m8
|
def coordinates(self, *args):
|
for arg in args:<EOL><INDENT>yield self._axis(arg)<EOL><DEDENT>
|
Return the coordinate variables corresponding to the given axes types.
|
f8456:c0:m9
|
def coordinates_identical(self, other):
|
<EOL>if len(self._data_array.coords) != len(other.coords):<EOL><INDENT>return False<EOL><DEDENT>for coord_name, coord_var in self._data_array.coords.items():<EOL><INDENT>if coord_name not in other.coords or not other[coord_name].identical(coord_var):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
|
Return whether or not the coordinates of other match this DataArray's.
|
f8456:c0:m14
|
def as_timestamp(self):
|
attrs = {key: self._data_array.attrs[key] for key in<EOL>{'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}<EOL>& set(self._data_array.attrs)}<EOL>attrs['<STR_LIT>'] = '<STR_LIT>'<EOL>return xr.DataArray(self._data_array.values.astype('<STR_LIT>').astype('<STR_LIT:int>'),<EOL>name=self._data_array.name,<EOL>coords=self._data_array.coords,<EOL>dims=self._data_array.dims,<EOL>attrs=attrs)<EOL>
|
Return the data as unix timestamp (for easier time derivatives).
|
f8456:c0:m15
|
def find_axis_name(self, axis):
|
if isinstance(axis, int):<EOL><INDENT>return self._data_array.dims[axis]<EOL><DEDENT>elif axis not in self._data_array.dims and axis in readable_to_cf_axes:<EOL><INDENT>return self._axis(axis).name<EOL><DEDENT>elif axis in self._data_array.dims and axis in self._data_array.coords:<EOL><INDENT>return axis<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>
|
Return the name of the axis corresponding to the given identifier.
The given indentifer can be an axis number (integer), dimension coordinate name
(string) or a standard axis type (string).
|
f8456:c0:m16
|
@property<EOL><INDENT>def loc(self):<DEDENT>
|
return self._LocIndexer(self._data_array)<EOL>
|
Make the LocIndexer available as a property.
|
f8456:c0:m17
|
def sel(self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs):
|
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, '<STR_LIT>')<EOL>indexers = _reassign_quantity_indexer(self._data_array, indexers)<EOL>return self._data_array.sel(indexers, method=method, tolerance=tolerance, drop=drop)<EOL>
|
Wrap DataArray.sel to handle units.
|
f8456:c0:m18
|
def __init__(self, dataset):
|
self._dataset = dataset<EOL>
|
Initialize accessor with a Dataset.
|
f8456:c1:m0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.