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 |
|---|---|---|---|---|---|---|---|---|---|
kevinconway/venvctrl | venvctrl/venv/base.py | ActivateFile.vpath | python | def vpath(self, new_vpath):
_, line_number = self._find_vpath()
new_vpath = self.write_pattern.format(new_vpath)
self.writeline(new_vpath, line_number) | Change the path to the virtual environment. | train | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L207-L211 | [
"def writeline(self, line, line_number):\n \"\"\"Rewrite a single line in the file.\n\n Args:\n line (str): The new text to write to the file.\n line_number (int): The line of the file to rewrite. Numbering\n starts at 0.\n \"\"\"\n tmp_file = tempfile.TemporaryFile('w+')\n i... | class ActivateFile(BinFile):
"""The virtual environment /bin/activate script."""
read_pattern = re.compile(r'^VIRTUAL_ENV="(.*)"$')
write_pattern = 'VIRTUAL_ENV="{0}"'
def _find_vpath(self):
"""Find the VIRTUAL_ENV path entry."""
with open(self.path, 'r') as file_handle:
for count, line in enumerate(file_handle):
match = self.read_pattern.match(line)
if match:
return match.group(1), count
return None, None
@property
def vpath(self):
"""Get the path to the virtual environment."""
return self._find_vpath()[0]
@vpath.setter
|
kevinconway/venvctrl | venvctrl/venv/base.py | BinDir.files | python | def files(self):
contents = self.paths
contents = (BinFile(path.path) for path in contents if path.is_file)
return contents | Get an iter of VenvFiles within the directory. | train | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L255-L259 | null | class BinDir(VenvDir):
"""Specialized VenvDir for the /bin directory."""
@property
def activates(self):
"""Get an iter of activate files in the virtual environment."""
return (self.activate_sh, self.activate_csh, self.activate_fish)
@property
def activate_sh(self):
"""Get the /bin/activate script."""
return ActivateFile(os.path.join(self.path, 'activate'))
@property
def activate_csh(self):
"""Get the /bin/activate.csh script."""
return ActivateCshFile(os.path.join(self.path, 'activate.csh'))
@property
def activate_fish(self):
"""Get the /bin/activate.fish script."""
return ActivateFishFile(os.path.join(self.path, 'activate.fish'))
@property
@property
def dirs(self):
"""Get an iter of VenvDirs within the directory."""
contents = self.paths
contents = (BinDir(path.path) for path in contents if path.is_dir)
return contents
@property
def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
BinFile(path.path) if path.is_file else BinDir(path.path)
for path in contents
)
return contents
|
kevinconway/venvctrl | venvctrl/venv/base.py | BinDir.dirs | python | def dirs(self):
contents = self.paths
contents = (BinDir(path.path) for path in contents if path.is_dir)
return contents | Get an iter of VenvDirs within the directory. | train | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L262-L266 | null | class BinDir(VenvDir):
"""Specialized VenvDir for the /bin directory."""
@property
def activates(self):
"""Get an iter of activate files in the virtual environment."""
return (self.activate_sh, self.activate_csh, self.activate_fish)
@property
def activate_sh(self):
"""Get the /bin/activate script."""
return ActivateFile(os.path.join(self.path, 'activate'))
@property
def activate_csh(self):
"""Get the /bin/activate.csh script."""
return ActivateCshFile(os.path.join(self.path, 'activate.csh'))
@property
def activate_fish(self):
"""Get the /bin/activate.fish script."""
return ActivateFishFile(os.path.join(self.path, 'activate.fish'))
@property
def files(self):
"""Get an iter of VenvFiles within the directory."""
contents = self.paths
contents = (BinFile(path.path) for path in contents if path.is_file)
return contents
@property
@property
def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
BinFile(path.path) if path.is_file else BinDir(path.path)
for path in contents
)
return contents
|
kevinconway/venvctrl | venvctrl/venv/base.py | BinDir.items | python | def items(self):
contents = self.paths
contents = (
BinFile(path.path) if path.is_file else BinDir(path.path)
for path in contents
)
return contents | Get an iter of VenvDirs and VenvFiles within the directory. | train | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L269-L276 | null | class BinDir(VenvDir):
"""Specialized VenvDir for the /bin directory."""
@property
def activates(self):
"""Get an iter of activate files in the virtual environment."""
return (self.activate_sh, self.activate_csh, self.activate_fish)
@property
def activate_sh(self):
"""Get the /bin/activate script."""
return ActivateFile(os.path.join(self.path, 'activate'))
@property
def activate_csh(self):
"""Get the /bin/activate.csh script."""
return ActivateCshFile(os.path.join(self.path, 'activate.csh'))
@property
def activate_fish(self):
"""Get the /bin/activate.fish script."""
return ActivateFishFile(os.path.join(self.path, 'activate.fish'))
@property
def files(self):
"""Get an iter of VenvFiles within the directory."""
contents = self.paths
contents = (BinFile(path.path) for path in contents if path.is_file)
return contents
@property
def dirs(self):
"""Get an iter of VenvDirs within the directory."""
contents = self.paths
contents = (BinDir(path.path) for path in contents if path.is_dir)
return contents
@property
|
koriakin/binflakes | binflakes/types/word.py | BinWord.to_sint | python | def to_sint(self):
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit) | Converts the word to a BinInt, treating it as a signed number. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L85-L90 | null | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.sar | python | def sar(self, count):
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True) | Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case). | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L206-L220 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n"
] | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.sext | python | def sext(self, width):
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True) | Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits). | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L242-L249 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n"
] | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.zext | python | def zext(self, width):
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val) | Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits). | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L251-L258 | null | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.slt | python | def slt(self, other):
self._check_match(other)
return self.to_sint() < other.to_sint() | Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L307-L312 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n",
"def _check_match(self, other):\n if not isinstance(other, BinWord):\n ... | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.sle | python | def sle(self, other):
self._check_match(other)
return self.to_sint() <= other.to_sint() | Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L314-L319 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n",
"def _check_match(self, other):\n if not isinstance(other, BinWord):\n ... | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.sgt | python | def sgt(self, other):
self._check_match(other)
return self.to_sint() > other.to_sint() | Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L321-L326 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n",
"def _check_match(self, other):\n if not isinstance(other, BinWord):\n ... | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.sge | python | def sge(self, other):
self._check_match(other)
return self.to_sint() >= other.to_sint() | Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L328-L333 | [
"def to_sint(self):\n \"\"\"Converts the word to a BinInt, treating it as a signed number.\"\"\"\n if self._width == 0:\n return BinInt(0)\n sbit = 1 << (self._width - 1)\n return BinInt((self._val - sbit) ^ -sbit)\n",
"def _check_match(self, other):\n if not isinstance(other, BinWord):\n ... | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
@classmethod
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords,
in LSB-first order.
"""
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val)
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/word.py | BinWord.concat | python | def concat(cls, *args):
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val) | Returns a BinWord made from concatenating several BinWords,
in LSB-first order. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L336-L347 | null | class BinWord:
"""A class representing a binary word value. Its width (in bits) can be
an arbitrary positive integer and is specified on creation.
Values of this class are immutable once created.
Most operations on BinWords treat them as two's complement numbers,
complete with wrapping semantics (and require their widths to match).
Can be treated as a sequence of individual bits (which are represented
as BinWords of width 1), with bit 0 being the LSB and width-1 being
the MSB.
"""
__slots__ = '_width', '_val'
def __init__(self, width, val, *, trunc=False):
"""Creates a word with a given width corresponding to a given
unsigned integer value.
If ``trunc`` is True, values out of range are masked to fit.
Otherwise, it is an error to pass a value that doesn't fit in
the given width.
"""
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
self._width = width
val = BinInt(operator.index(val))
if trunc:
val &= self.mask
elif val & ~self.mask:
raise ValueError('value does not fit in the given bit width')
assert isinstance(val, BinInt)
self._val = val
@property
def width(self):
"""Returns the width of this word in bits."""
return self._width
@property
def mask(self):
"""Returns a BinInt with low self.width bits set, corresponding
to a bitmask of valid bits for words of this size.
"""
return BinInt.mask(self._width)
def to_uint(self):
"""Converts the word to a BinInt, treating it as an unsigned number."""
return self._val
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit)
def __index__(self):
"""Converts the word to an int, treating it as an unsigned number."""
return int(self._val)
__int__ = __index__
def __eq__(self, other):
"""Compares for equality with another object. BinWords are only
considered equal to other BinWords with the same width and value.
"""
if not isinstance(other, BinWord):
return False
return self._width == other._width and self._val == other._val
def __hash__(self):
return hash((self._width, self._val))
def __len__(self):
"""Returns the width of this word in bits."""
return self._width
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(self._width)
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
else:
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self._val >> ipos & 1) << opos
return BinWord(len(r), val)
else:
idx = operator.index(idx)
if idx < 0:
idx += self._width
return self.extract(idx, 1)
def __bool__(self):
"""Converts a BinWord to a bool. All words not equal to all-zeros
are considered to be true.
"""
return bool(self._val)
def _check_match(self, other):
if not isinstance(other, BinWord):
raise TypeError('need another BinWord')
if self._width != other._width:
raise ValueError('mismatched widths in BinWord operation')
def __add__(self, other):
"""Performs a wrapping addition of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val + other._val, trunc=True)
def __sub__(self, other):
"""Performs a wrapping subtraction of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val - other._val, trunc=True)
def __mul__(self, other):
"""Performs a wrapping multiplication of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val * other._val, trunc=True)
def __and__(self, other):
"""Performs a bitwise AND of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val & other._val)
def __or__(self, other):
"""Performs a bitwise OR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val | other._val)
def __xor__(self, other):
"""Performs a bitwise XOR of two equal-sized BinWords."""
self._check_match(other)
return BinWord(self._width, self._val ^ other._val)
def __lshift__(self, count):
"""Performs a left-shift of a BinWord by the given number of bits.
Bits shifted out of the word are lost.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val << count, trunc=True)
def __rshift__(self, count):
"""Performs a logical right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with 0 bits.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (0 is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self._val >> count)
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number
of bits. Bits shifted out of the word are lost. The word is
filled on the left with copies of the top bit.
The shift count can be an arbitrary non-negative number, including
counts larger than the word (a word filled with copies of the sign bit
is returned in this case).
"""
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=True)
def __neg__(self):
"""Returns a two's complement of the BinWord."""
return BinWord(self._width, -self._val, trunc=True)
def __invert__(self):
"""Returns a one's complement of the BinWord (ie. inverts all bits)."""
return BinWord(self._width, ~self._val, trunc=True)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position. It is an error to extract out-of-range bits.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0 or pos + width > self._width:
raise ValueError('extracting out of range')
return BinWord(width, self._val >> pos, trunc=True)
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width')
return BinWord(width, self.to_sint(), trunc=True)
def zext(self, width):
"""Zero-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('zero extending to a smaller width')
return BinWord(width, self._val)
def deposit(self, pos, val):
"""Returns a copy of this BinWord, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
bit bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0 or val._width + pos > self._width:
raise ValueError('depositing out of range')
res = self._val
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return BinWord(self._width, res)
def __lt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller. Use ``slt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val < other._val
def __le__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is smaller or equal.
Use ``sle`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val <= other._val
def __gt__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger. Use ``sgt``
to compare as signed integers instead.
"""
self._check_match(other)
return self._val > other._val
def __ge__(self, other):
"""Compares two equal-sized BinWords, treating them as unsigned
integers, and returning True if the first is bigger or equal.
Use ``sge`` to compare as signed integers instead.
"""
self._check_match(other)
return self._val >= other._val
def slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller.
"""
self._check_match(other)
return self.to_sint() < other.to_sint()
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is smaller or equal.
"""
self._check_match(other)
return self.to_sint() <= other.to_sint()
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint()
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger or equal.
"""
self._check_match(other)
return self.to_sint() >= other.to_sint()
@classmethod
@property
def _width_in_nibbles(self):
return (self._width + 3) // 4
def __repr__(self):
val = f'0x{self._val:0{self._width_in_nibbles}x}'
return f'BinWord({self._width}, {val})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x<value as a hexadecimal number>``.
This format is directly accepted by the S-expression parser.
"""
return f'{self._width}\'0x{self._val:0{self._width_in_nibbles}x}'
|
koriakin/binflakes | binflakes/types/array.py | BinArray._init | python | def _init(self, width, len_):
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(8)) | Initializes internal data representation of the BinArray to all-0.
The internal data representation is simply tightly-packed bits of all
words, starting from LSB, split into bytes and stored in a bytearray.
The unused trailing padding bits in the last byte must always be set
to 0. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/array.py#L77-L87 | [
"def ceildiv(self, other):\n \"\"\"Returns ceil(a / b).\"\"\"\n return -(-self // other)\n"
] | class BinArray:
"""Represents an array of equal-width BinWords. Conceptually behaves
like bytearray, except that element width can be different than 8,
and item accesses return BinWord instances.
"""
__slots__ = '_width', '_len', '_data'
def __init__(self, data=None, *, width=None, length=None):
"""Creates a new BinArray. The following forms are valid:
- ``BinArray(bytes or bytearray)``: creates a BinArray of width 8
with items from the given bytearray.
- ``BinArray(BinArray instance)``: creates a copy of a BinArray.
- ``BinArray(width=w)``: creates empty BinArray of given width.
- ``BinArray(width=w, length=n)``: creates a zero-filled BinArray of
given width and length.
- ``BinArray(iterable, width=n)``: creates a BinArray from the given
iterable of items. Items should be ints, BinInts, or BinWords
of the correct width.
- ``BinArray(iterable)``: creates a BinArray from a non-empty array
of BinWords.
"""
if data is not None and length is not None:
raise TypeError('data and length are mutually exclusive')
if data is None:
if length is None:
length = 0
if width is None:
raise TypeError('width not specified')
length = operator.index(length)
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, length)
else:
try:
len(data)
except TypeError:
data = list(data)
if width is None:
if isinstance(data, (bytes, bytearray)):
width = 8
elif isinstance(data, BinArray):
width = data.width
else:
raise TypeError('width not specified')
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, len(data))
for i, x in enumerate(data):
self[i] = x
def _locate(self, idx):
"""Locates an element in the internal data representation. Returns
starting byte index, starting bit index in the starting byte, and
one past the final byte index.
"""
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte
@property
def width(self):
"""Returns word width of the BinArray."""
return self._width
def __len__(self):
"""Returns length of the array in words."""
return self._len
def __getitem__(self, idx):
"""Returns a word at the given index (as a BinWord instance),
or a slice of the array (as a new BinArray instance).
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
res = BinArray(width=self._width, length=len(r))
for opos, ipos in enumerate(r):
res[opos] = self[ipos]
return res
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
return raw.extract(sbit, self._width)
def __setitem__(self, idx, val):
"""Assigns to the word at a given index, or to a subslice of
the array. When assigning words, the assigned value must be
a BinWord instance of the same width as the array, or an int
or BinInt instance that will be automatically converted
to BinWord. It is an error if an int or BinInt is assigned
that does not fit in ``width`` bits.
"""
if isinstance(idx, slice):
if not isinstance(val, BinArray):
raise TypeError('assigning non-BinArray to a slice')
if self._width != val._width:
raise ValueError('mismatched widths in slice assignment')
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
if len(r) != len(val):
raise ValueError('mismatched lengths in slice assignment')
for idx, item in zip(r, val):
self[idx] = item
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
if isinstance(val, BinWord) and val._width != self._width:
raise ValueError('word width mismatch')
val = BinWord(self._width, val)
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
raw = raw.deposit(sbit, val)
self._data[sbyte:ebyte] = raw.to_bytes(ebyte - sbyte, 'little')
def __repr__(self):
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ', '.join(f'0x{x.to_uint():{fmt}}' for x in self)
return f'BinArray([{elems}], width={self._width})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x(<space-separated words as hexadecimal
numbers>)``. This format is directly accepted by the S-expression
parser.
"""
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ' '.join(format(x.to_uint(), fmt) for x in self)
return f'{self._width}\'0x({elems})'
def __eq__(self, other):
"""Compares for equality with another object. BinArrays are only
considered equal to other BinArrays with the same width, length,
and contents.
"""
if not isinstance(other, BinArray):
return False
if self._width != other._width:
return False
if self._len != other._len:
return False
return self._data == other._data
def _check_match(self, other):
if not isinstance(other, BinArray):
raise TypeError(
'argument to bitwise operation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for bitwise operation')
if self._len != other._len:
raise ValueError('mismatched lengths for bitwise operation')
def __and__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise AND operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x & y for x, y in zip(self._data, other._data))
return res
def __or__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise OR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x | y for x, y in zip(self._data, other._data))
return res
def __xor__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise XOR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x ^ y for x, y in zip(self._data, other._data))
return res
def __iand__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] &= val
return self
def __ior__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] |= val
return self
def __ixor__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] ^= val
return self
def __invert__(self):
"""Creates a new BinArray with all bits inverted."""
return BinArray([~x for x in self], width=self._width)
def __add__(self, other):
"""Concatenates two equal-width BinArray instances together, returning
a new BinArray.
"""
if not isinstance(other, BinArray):
raise TypeError(
'argument to concatenation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for concatenation')
res = BinArray(width=self._width, length=len(self) + len(other))
res[:len(self)] = self
res[len(self):] = other
return res
def __mul__(self, count):
"""Repeats a BinArray count times, returning a new BinArray."""
count = operator.index(count)
if count < 0:
raise ValueError('negative repetition count')
sl = len(self)
res = BinArray(width=self._width, length=sl * count)
for idx in range(count):
res[idx * sl:(idx + 1) * sl] = self
return res
__rmul__ = __mul__
def repack(self, to_width, *, msb_first, start=0, start_bit=0,
length=None):
"""Extracts a part of a BinArray's data and converts it to a BinArray
of a different width.
For the purposes of this conversion, words in this BinArray are joined
side-by-side, starting from a given start index (defaulting to 0),
skipping ``start_bit`` first bits of the first word, then the resulting
stream is split into ``to_width``-sized words and ``length`` first
such words are returned as a new BinArray.
If ``msb_first`` is False, everything proceeds with little endian
ordering: the first word provides the least significant bits of the
combined stream, ``start_bit`` skips bits starting from the LSB,
and the first output word is made from the lowest bits of the combined
stream. Otherwise (``msb_first`` is True), everything proceeds
with big endian ordering: the first word provides the most
significant bits of the combined stream, ``start_bit`` skips bits
starting from the MSB, and the first output word is made from the
highest bits of the combined stream.
``start_bits`` must be smaller than the width of the input word.
It is an error to request a larger length than can be provided from
the input array. If ``length`` is not provided, this function
returns as many words as can be extracted.
For example, consider a 10-to-3 repack with start_bit=2, length=4
msb_first=True:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |X|X|a|b|c|d|e|f|g|h|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |i|j|k|l|X|X|X|X|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
is repacked to:
+-+-+-+-+
|0|a|b|c|
+-+-+-+-+
|1|d|e|f|
+-+-+-+-+
|2|g|h|i|
+-+-+-+-+
|3|j|k|l|
+-+-+-+-+
The same repack for msb_first=False is performed as follows:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |h|g|f|e|d|c|b|a|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |X|X|X|X|X|X|l|k|j|i|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
into:
+-+-+-+-+
|0|c|b|a|
+-+-+-+-+
|1|f|e|d|
+-+-+-+-+
|2|i|h|g|
+-+-+-+-+
|3|l|k|j|
+-+-+-+-+
"""
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
return res
def repack_source_required(src_width, to_width, length, *, # noqa: N805
start_bit=0):
"""Calculates how many source words would be read for an invocation of
repack with a given length, including possible partial words at
the beginning and the end of the repack source. This can be called
either on a concrete BinArray instance (assuming its width as the
source width), or on the BinArray class (providing the source width
as an extra first argument). This function doesn't take ``start``
or ``msb_first`` parameters, since they wouldn't affect the
computation.
"""
if isinstance(src_width, BinArray):
src_width = src_width._width
src_width = operator.index(src_width)
to_width = operator.index(to_width)
length = operator.index(length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if length < 0:
raise ValueError('length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
return BinInt(start_bit + to_width * length).ceildiv(src_width)
def repack_data_available(src_width, to_width, *, # noqa: N805
src_length=None, start=None, start_bit=0):
"""Calculates the maximum number of words that can be requested
from a repack invocation with the given settings.
This function can be called either on a BinArray instance (assuming
its width as the source width), or on the BinArray class (passing
the source width as an extra first argument). If called in the
second form, ``src_length`` must be provided. Otherwise, it will
default to the number of words in the source array from the given
``start`` index (defaulting to 0) until the end.
"""
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width
|
koriakin/binflakes | binflakes/types/array.py | BinArray._locate | python | def _locate(self, idx):
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte | Locates an element in the internal data representation. Returns
starting byte index, starting bit index in the starting byte, and
one past the final byte index. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/array.py#L89-L98 | null | class BinArray:
"""Represents an array of equal-width BinWords. Conceptually behaves
like bytearray, except that element width can be different than 8,
and item accesses return BinWord instances.
"""
__slots__ = '_width', '_len', '_data'
def __init__(self, data=None, *, width=None, length=None):
"""Creates a new BinArray. The following forms are valid:
- ``BinArray(bytes or bytearray)``: creates a BinArray of width 8
with items from the given bytearray.
- ``BinArray(BinArray instance)``: creates a copy of a BinArray.
- ``BinArray(width=w)``: creates empty BinArray of given width.
- ``BinArray(width=w, length=n)``: creates a zero-filled BinArray of
given width and length.
- ``BinArray(iterable, width=n)``: creates a BinArray from the given
iterable of items. Items should be ints, BinInts, or BinWords
of the correct width.
- ``BinArray(iterable)``: creates a BinArray from a non-empty array
of BinWords.
"""
if data is not None and length is not None:
raise TypeError('data and length are mutually exclusive')
if data is None:
if length is None:
length = 0
if width is None:
raise TypeError('width not specified')
length = operator.index(length)
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, length)
else:
try:
len(data)
except TypeError:
data = list(data)
if width is None:
if isinstance(data, (bytes, bytearray)):
width = 8
elif isinstance(data, BinArray):
width = data.width
else:
raise TypeError('width not specified')
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, len(data))
for i, x in enumerate(data):
self[i] = x
def _init(self, width, len_):
"""Initializes internal data representation of the BinArray to all-0.
The internal data representation is simply tightly-packed bits of all
words, starting from LSB, split into bytes and stored in a bytearray.
The unused trailing padding bits in the last byte must always be set
to 0.
"""
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(8))
@property
def width(self):
"""Returns word width of the BinArray."""
return self._width
def __len__(self):
"""Returns length of the array in words."""
return self._len
def __getitem__(self, idx):
"""Returns a word at the given index (as a BinWord instance),
or a slice of the array (as a new BinArray instance).
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
res = BinArray(width=self._width, length=len(r))
for opos, ipos in enumerate(r):
res[opos] = self[ipos]
return res
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
return raw.extract(sbit, self._width)
def __setitem__(self, idx, val):
"""Assigns to the word at a given index, or to a subslice of
the array. When assigning words, the assigned value must be
a BinWord instance of the same width as the array, or an int
or BinInt instance that will be automatically converted
to BinWord. It is an error if an int or BinInt is assigned
that does not fit in ``width`` bits.
"""
if isinstance(idx, slice):
if not isinstance(val, BinArray):
raise TypeError('assigning non-BinArray to a slice')
if self._width != val._width:
raise ValueError('mismatched widths in slice assignment')
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
if len(r) != len(val):
raise ValueError('mismatched lengths in slice assignment')
for idx, item in zip(r, val):
self[idx] = item
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
if isinstance(val, BinWord) and val._width != self._width:
raise ValueError('word width mismatch')
val = BinWord(self._width, val)
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
raw = raw.deposit(sbit, val)
self._data[sbyte:ebyte] = raw.to_bytes(ebyte - sbyte, 'little')
def __repr__(self):
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ', '.join(f'0x{x.to_uint():{fmt}}' for x in self)
return f'BinArray([{elems}], width={self._width})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x(<space-separated words as hexadecimal
numbers>)``. This format is directly accepted by the S-expression
parser.
"""
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ' '.join(format(x.to_uint(), fmt) for x in self)
return f'{self._width}\'0x({elems})'
def __eq__(self, other):
"""Compares for equality with another object. BinArrays are only
considered equal to other BinArrays with the same width, length,
and contents.
"""
if not isinstance(other, BinArray):
return False
if self._width != other._width:
return False
if self._len != other._len:
return False
return self._data == other._data
def _check_match(self, other):
if not isinstance(other, BinArray):
raise TypeError(
'argument to bitwise operation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for bitwise operation')
if self._len != other._len:
raise ValueError('mismatched lengths for bitwise operation')
def __and__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise AND operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x & y for x, y in zip(self._data, other._data))
return res
def __or__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise OR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x | y for x, y in zip(self._data, other._data))
return res
def __xor__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise XOR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x ^ y for x, y in zip(self._data, other._data))
return res
def __iand__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] &= val
return self
def __ior__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] |= val
return self
def __ixor__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] ^= val
return self
def __invert__(self):
"""Creates a new BinArray with all bits inverted."""
return BinArray([~x for x in self], width=self._width)
def __add__(self, other):
"""Concatenates two equal-width BinArray instances together, returning
a new BinArray.
"""
if not isinstance(other, BinArray):
raise TypeError(
'argument to concatenation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for concatenation')
res = BinArray(width=self._width, length=len(self) + len(other))
res[:len(self)] = self
res[len(self):] = other
return res
def __mul__(self, count):
"""Repeats a BinArray count times, returning a new BinArray."""
count = operator.index(count)
if count < 0:
raise ValueError('negative repetition count')
sl = len(self)
res = BinArray(width=self._width, length=sl * count)
for idx in range(count):
res[idx * sl:(idx + 1) * sl] = self
return res
__rmul__ = __mul__
def repack(self, to_width, *, msb_first, start=0, start_bit=0,
length=None):
"""Extracts a part of a BinArray's data and converts it to a BinArray
of a different width.
For the purposes of this conversion, words in this BinArray are joined
side-by-side, starting from a given start index (defaulting to 0),
skipping ``start_bit`` first bits of the first word, then the resulting
stream is split into ``to_width``-sized words and ``length`` first
such words are returned as a new BinArray.
If ``msb_first`` is False, everything proceeds with little endian
ordering: the first word provides the least significant bits of the
combined stream, ``start_bit`` skips bits starting from the LSB,
and the first output word is made from the lowest bits of the combined
stream. Otherwise (``msb_first`` is True), everything proceeds
with big endian ordering: the first word provides the most
significant bits of the combined stream, ``start_bit`` skips bits
starting from the MSB, and the first output word is made from the
highest bits of the combined stream.
``start_bits`` must be smaller than the width of the input word.
It is an error to request a larger length than can be provided from
the input array. If ``length`` is not provided, this function
returns as many words as can be extracted.
For example, consider a 10-to-3 repack with start_bit=2, length=4
msb_first=True:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |X|X|a|b|c|d|e|f|g|h|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |i|j|k|l|X|X|X|X|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
is repacked to:
+-+-+-+-+
|0|a|b|c|
+-+-+-+-+
|1|d|e|f|
+-+-+-+-+
|2|g|h|i|
+-+-+-+-+
|3|j|k|l|
+-+-+-+-+
The same repack for msb_first=False is performed as follows:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |h|g|f|e|d|c|b|a|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |X|X|X|X|X|X|l|k|j|i|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
into:
+-+-+-+-+
|0|c|b|a|
+-+-+-+-+
|1|f|e|d|
+-+-+-+-+
|2|i|h|g|
+-+-+-+-+
|3|l|k|j|
+-+-+-+-+
"""
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
return res
def repack_source_required(src_width, to_width, length, *, # noqa: N805
start_bit=0):
"""Calculates how many source words would be read for an invocation of
repack with a given length, including possible partial words at
the beginning and the end of the repack source. This can be called
either on a concrete BinArray instance (assuming its width as the
source width), or on the BinArray class (providing the source width
as an extra first argument). This function doesn't take ``start``
or ``msb_first`` parameters, since they wouldn't affect the
computation.
"""
if isinstance(src_width, BinArray):
src_width = src_width._width
src_width = operator.index(src_width)
to_width = operator.index(to_width)
length = operator.index(length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if length < 0:
raise ValueError('length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
return BinInt(start_bit + to_width * length).ceildiv(src_width)
def repack_data_available(src_width, to_width, *, # noqa: N805
src_length=None, start=None, start_bit=0):
"""Calculates the maximum number of words that can be requested
from a repack invocation with the given settings.
This function can be called either on a BinArray instance (assuming
its width as the source width), or on the BinArray class (passing
the source width as an extra first argument). If called in the
second form, ``src_length`` must be provided. Otherwise, it will
default to the number of words in the source array from the given
``start`` index (defaulting to 0) until the end.
"""
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width
|
koriakin/binflakes | binflakes/types/array.py | BinArray.repack | python | def repack(self, to_width, *, msb_first, start=0, start_bit=0,
length=None):
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
return res | Extracts a part of a BinArray's data and converts it to a BinArray
of a different width.
For the purposes of this conversion, words in this BinArray are joined
side-by-side, starting from a given start index (defaulting to 0),
skipping ``start_bit`` first bits of the first word, then the resulting
stream is split into ``to_width``-sized words and ``length`` first
such words are returned as a new BinArray.
If ``msb_first`` is False, everything proceeds with little endian
ordering: the first word provides the least significant bits of the
combined stream, ``start_bit`` skips bits starting from the LSB,
and the first output word is made from the lowest bits of the combined
stream. Otherwise (``msb_first`` is True), everything proceeds
with big endian ordering: the first word provides the most
significant bits of the combined stream, ``start_bit`` skips bits
starting from the MSB, and the first output word is made from the
highest bits of the combined stream.
``start_bits`` must be smaller than the width of the input word.
It is an error to request a larger length than can be provided from
the input array. If ``length`` is not provided, this function
returns as many words as can be extracted.
For example, consider a 10-to-3 repack with start_bit=2, length=4
msb_first=True:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |X|X|a|b|c|d|e|f|g|h|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |i|j|k|l|X|X|X|X|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
is repacked to:
+-+-+-+-+
|0|a|b|c|
+-+-+-+-+
|1|d|e|f|
+-+-+-+-+
|2|g|h|i|
+-+-+-+-+
|3|j|k|l|
+-+-+-+-+
The same repack for msb_first=False is performed as follows:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |h|g|f|e|d|c|b|a|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |X|X|X|X|X|X|l|k|j|i|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
into:
+-+-+-+-+
|0|c|b|a|
+-+-+-+-+
|1|f|e|d|
+-+-+-+-+
|2|i|h|g|
+-+-+-+-+
|3|l|k|j|
+-+-+-+-+ | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/array.py#L289-L410 | [
"def repack_data_available(src_width, to_width, *, # noqa: N805\n src_length=None, start=None, start_bit=0):\n \"\"\"Calculates the maximum number of words that can be requested\n from a repack invocation with the given settings.\n\n This function can be called either on a BinArra... | class BinArray:
"""Represents an array of equal-width BinWords. Conceptually behaves
like bytearray, except that element width can be different than 8,
and item accesses return BinWord instances.
"""
__slots__ = '_width', '_len', '_data'
def __init__(self, data=None, *, width=None, length=None):
"""Creates a new BinArray. The following forms are valid:
- ``BinArray(bytes or bytearray)``: creates a BinArray of width 8
with items from the given bytearray.
- ``BinArray(BinArray instance)``: creates a copy of a BinArray.
- ``BinArray(width=w)``: creates empty BinArray of given width.
- ``BinArray(width=w, length=n)``: creates a zero-filled BinArray of
given width and length.
- ``BinArray(iterable, width=n)``: creates a BinArray from the given
iterable of items. Items should be ints, BinInts, or BinWords
of the correct width.
- ``BinArray(iterable)``: creates a BinArray from a non-empty array
of BinWords.
"""
if data is not None and length is not None:
raise TypeError('data and length are mutually exclusive')
if data is None:
if length is None:
length = 0
if width is None:
raise TypeError('width not specified')
length = operator.index(length)
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, length)
else:
try:
len(data)
except TypeError:
data = list(data)
if width is None:
if isinstance(data, (bytes, bytearray)):
width = 8
elif isinstance(data, BinArray):
width = data.width
else:
raise TypeError('width not specified')
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, len(data))
for i, x in enumerate(data):
self[i] = x
def _init(self, width, len_):
"""Initializes internal data representation of the BinArray to all-0.
The internal data representation is simply tightly-packed bits of all
words, starting from LSB, split into bytes and stored in a bytearray.
The unused trailing padding bits in the last byte must always be set
to 0.
"""
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(8))
def _locate(self, idx):
"""Locates an element in the internal data representation. Returns
starting byte index, starting bit index in the starting byte, and
one past the final byte index.
"""
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte
@property
def width(self):
"""Returns word width of the BinArray."""
return self._width
def __len__(self):
"""Returns length of the array in words."""
return self._len
def __getitem__(self, idx):
"""Returns a word at the given index (as a BinWord instance),
or a slice of the array (as a new BinArray instance).
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
res = BinArray(width=self._width, length=len(r))
for opos, ipos in enumerate(r):
res[opos] = self[ipos]
return res
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
return raw.extract(sbit, self._width)
def __setitem__(self, idx, val):
"""Assigns to the word at a given index, or to a subslice of
the array. When assigning words, the assigned value must be
a BinWord instance of the same width as the array, or an int
or BinInt instance that will be automatically converted
to BinWord. It is an error if an int or BinInt is assigned
that does not fit in ``width`` bits.
"""
if isinstance(idx, slice):
if not isinstance(val, BinArray):
raise TypeError('assigning non-BinArray to a slice')
if self._width != val._width:
raise ValueError('mismatched widths in slice assignment')
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
if len(r) != len(val):
raise ValueError('mismatched lengths in slice assignment')
for idx, item in zip(r, val):
self[idx] = item
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
if isinstance(val, BinWord) and val._width != self._width:
raise ValueError('word width mismatch')
val = BinWord(self._width, val)
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
raw = raw.deposit(sbit, val)
self._data[sbyte:ebyte] = raw.to_bytes(ebyte - sbyte, 'little')
def __repr__(self):
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ', '.join(f'0x{x.to_uint():{fmt}}' for x in self)
return f'BinArray([{elems}], width={self._width})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x(<space-separated words as hexadecimal
numbers>)``. This format is directly accepted by the S-expression
parser.
"""
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ' '.join(format(x.to_uint(), fmt) for x in self)
return f'{self._width}\'0x({elems})'
def __eq__(self, other):
"""Compares for equality with another object. BinArrays are only
considered equal to other BinArrays with the same width, length,
and contents.
"""
if not isinstance(other, BinArray):
return False
if self._width != other._width:
return False
if self._len != other._len:
return False
return self._data == other._data
def _check_match(self, other):
if not isinstance(other, BinArray):
raise TypeError(
'argument to bitwise operation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for bitwise operation')
if self._len != other._len:
raise ValueError('mismatched lengths for bitwise operation')
def __and__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise AND operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x & y for x, y in zip(self._data, other._data))
return res
def __or__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise OR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x | y for x, y in zip(self._data, other._data))
return res
def __xor__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise XOR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x ^ y for x, y in zip(self._data, other._data))
return res
def __iand__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] &= val
return self
def __ior__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] |= val
return self
def __ixor__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] ^= val
return self
def __invert__(self):
"""Creates a new BinArray with all bits inverted."""
return BinArray([~x for x in self], width=self._width)
def __add__(self, other):
"""Concatenates two equal-width BinArray instances together, returning
a new BinArray.
"""
if not isinstance(other, BinArray):
raise TypeError(
'argument to concatenation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for concatenation')
res = BinArray(width=self._width, length=len(self) + len(other))
res[:len(self)] = self
res[len(self):] = other
return res
def __mul__(self, count):
"""Repeats a BinArray count times, returning a new BinArray."""
count = operator.index(count)
if count < 0:
raise ValueError('negative repetition count')
sl = len(self)
res = BinArray(width=self._width, length=sl * count)
for idx in range(count):
res[idx * sl:(idx + 1) * sl] = self
return res
__rmul__ = __mul__
def repack_source_required(src_width, to_width, length, *, # noqa: N805
start_bit=0):
"""Calculates how many source words would be read for an invocation of
repack with a given length, including possible partial words at
the beginning and the end of the repack source. This can be called
either on a concrete BinArray instance (assuming its width as the
source width), or on the BinArray class (providing the source width
as an extra first argument). This function doesn't take ``start``
or ``msb_first`` parameters, since they wouldn't affect the
computation.
"""
if isinstance(src_width, BinArray):
src_width = src_width._width
src_width = operator.index(src_width)
to_width = operator.index(to_width)
length = operator.index(length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if length < 0:
raise ValueError('length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
return BinInt(start_bit + to_width * length).ceildiv(src_width)
def repack_data_available(src_width, to_width, *, # noqa: N805
src_length=None, start=None, start_bit=0):
"""Calculates the maximum number of words that can be requested
from a repack invocation with the given settings.
This function can be called either on a BinArray instance (assuming
its width as the source width), or on the BinArray class (passing
the source width as an extra first argument). If called in the
second form, ``src_length`` must be provided. Otherwise, it will
default to the number of words in the source array from the given
``start`` index (defaulting to 0) until the end.
"""
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width
|
koriakin/binflakes | binflakes/types/array.py | BinArray.repack_source_required | python | def repack_source_required(src_width, to_width, length, *, # noqa: N805
start_bit=0):
if isinstance(src_width, BinArray):
src_width = src_width._width
src_width = operator.index(src_width)
to_width = operator.index(to_width)
length = operator.index(length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if length < 0:
raise ValueError('length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
return BinInt(start_bit + to_width * length).ceildiv(src_width) | Calculates how many source words would be read for an invocation of
repack with a given length, including possible partial words at
the beginning and the end of the repack source. This can be called
either on a concrete BinArray instance (assuming its width as the
source width), or on the BinArray class (providing the source width
as an extra first argument). This function doesn't take ``start``
or ``msb_first`` parameters, since they wouldn't affect the
computation. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/array.py#L412-L437 | [
"def ceildiv(self, other):\n \"\"\"Returns ceil(a / b).\"\"\"\n return -(-self // other)\n"
] | class BinArray:
"""Represents an array of equal-width BinWords. Conceptually behaves
like bytearray, except that element width can be different than 8,
and item accesses return BinWord instances.
"""
__slots__ = '_width', '_len', '_data'
def __init__(self, data=None, *, width=None, length=None):
"""Creates a new BinArray. The following forms are valid:
- ``BinArray(bytes or bytearray)``: creates a BinArray of width 8
with items from the given bytearray.
- ``BinArray(BinArray instance)``: creates a copy of a BinArray.
- ``BinArray(width=w)``: creates empty BinArray of given width.
- ``BinArray(width=w, length=n)``: creates a zero-filled BinArray of
given width and length.
- ``BinArray(iterable, width=n)``: creates a BinArray from the given
iterable of items. Items should be ints, BinInts, or BinWords
of the correct width.
- ``BinArray(iterable)``: creates a BinArray from a non-empty array
of BinWords.
"""
if data is not None and length is not None:
raise TypeError('data and length are mutually exclusive')
if data is None:
if length is None:
length = 0
if width is None:
raise TypeError('width not specified')
length = operator.index(length)
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, length)
else:
try:
len(data)
except TypeError:
data = list(data)
if width is None:
if isinstance(data, (bytes, bytearray)):
width = 8
elif isinstance(data, BinArray):
width = data.width
else:
raise TypeError('width not specified')
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, len(data))
for i, x in enumerate(data):
self[i] = x
def _init(self, width, len_):
"""Initializes internal data representation of the BinArray to all-0.
The internal data representation is simply tightly-packed bits of all
words, starting from LSB, split into bytes and stored in a bytearray.
The unused trailing padding bits in the last byte must always be set
to 0.
"""
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(8))
def _locate(self, idx):
"""Locates an element in the internal data representation. Returns
starting byte index, starting bit index in the starting byte, and
one past the final byte index.
"""
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte
@property
def width(self):
"""Returns word width of the BinArray."""
return self._width
def __len__(self):
"""Returns length of the array in words."""
return self._len
def __getitem__(self, idx):
"""Returns a word at the given index (as a BinWord instance),
or a slice of the array (as a new BinArray instance).
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
res = BinArray(width=self._width, length=len(r))
for opos, ipos in enumerate(r):
res[opos] = self[ipos]
return res
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
return raw.extract(sbit, self._width)
def __setitem__(self, idx, val):
"""Assigns to the word at a given index, or to a subslice of
the array. When assigning words, the assigned value must be
a BinWord instance of the same width as the array, or an int
or BinInt instance that will be automatically converted
to BinWord. It is an error if an int or BinInt is assigned
that does not fit in ``width`` bits.
"""
if isinstance(idx, slice):
if not isinstance(val, BinArray):
raise TypeError('assigning non-BinArray to a slice')
if self._width != val._width:
raise ValueError('mismatched widths in slice assignment')
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
if len(r) != len(val):
raise ValueError('mismatched lengths in slice assignment')
for idx, item in zip(r, val):
self[idx] = item
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
if isinstance(val, BinWord) and val._width != self._width:
raise ValueError('word width mismatch')
val = BinWord(self._width, val)
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
raw = raw.deposit(sbit, val)
self._data[sbyte:ebyte] = raw.to_bytes(ebyte - sbyte, 'little')
def __repr__(self):
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ', '.join(f'0x{x.to_uint():{fmt}}' for x in self)
return f'BinArray([{elems}], width={self._width})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x(<space-separated words as hexadecimal
numbers>)``. This format is directly accepted by the S-expression
parser.
"""
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ' '.join(format(x.to_uint(), fmt) for x in self)
return f'{self._width}\'0x({elems})'
def __eq__(self, other):
"""Compares for equality with another object. BinArrays are only
considered equal to other BinArrays with the same width, length,
and contents.
"""
if not isinstance(other, BinArray):
return False
if self._width != other._width:
return False
if self._len != other._len:
return False
return self._data == other._data
def _check_match(self, other):
if not isinstance(other, BinArray):
raise TypeError(
'argument to bitwise operation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for bitwise operation')
if self._len != other._len:
raise ValueError('mismatched lengths for bitwise operation')
def __and__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise AND operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x & y for x, y in zip(self._data, other._data))
return res
def __or__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise OR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x | y for x, y in zip(self._data, other._data))
return res
def __xor__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise XOR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x ^ y for x, y in zip(self._data, other._data))
return res
def __iand__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] &= val
return self
def __ior__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] |= val
return self
def __ixor__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] ^= val
return self
def __invert__(self):
"""Creates a new BinArray with all bits inverted."""
return BinArray([~x for x in self], width=self._width)
def __add__(self, other):
"""Concatenates two equal-width BinArray instances together, returning
a new BinArray.
"""
if not isinstance(other, BinArray):
raise TypeError(
'argument to concatenation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for concatenation')
res = BinArray(width=self._width, length=len(self) + len(other))
res[:len(self)] = self
res[len(self):] = other
return res
def __mul__(self, count):
"""Repeats a BinArray count times, returning a new BinArray."""
count = operator.index(count)
if count < 0:
raise ValueError('negative repetition count')
sl = len(self)
res = BinArray(width=self._width, length=sl * count)
for idx in range(count):
res[idx * sl:(idx + 1) * sl] = self
return res
__rmul__ = __mul__
def repack(self, to_width, *, msb_first, start=0, start_bit=0,
length=None):
"""Extracts a part of a BinArray's data and converts it to a BinArray
of a different width.
For the purposes of this conversion, words in this BinArray are joined
side-by-side, starting from a given start index (defaulting to 0),
skipping ``start_bit`` first bits of the first word, then the resulting
stream is split into ``to_width``-sized words and ``length`` first
such words are returned as a new BinArray.
If ``msb_first`` is False, everything proceeds with little endian
ordering: the first word provides the least significant bits of the
combined stream, ``start_bit`` skips bits starting from the LSB,
and the first output word is made from the lowest bits of the combined
stream. Otherwise (``msb_first`` is True), everything proceeds
with big endian ordering: the first word provides the most
significant bits of the combined stream, ``start_bit`` skips bits
starting from the MSB, and the first output word is made from the
highest bits of the combined stream.
``start_bits`` must be smaller than the width of the input word.
It is an error to request a larger length than can be provided from
the input array. If ``length`` is not provided, this function
returns as many words as can be extracted.
For example, consider a 10-to-3 repack with start_bit=2, length=4
msb_first=True:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |X|X|a|b|c|d|e|f|g|h|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |i|j|k|l|X|X|X|X|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
is repacked to:
+-+-+-+-+
|0|a|b|c|
+-+-+-+-+
|1|d|e|f|
+-+-+-+-+
|2|g|h|i|
+-+-+-+-+
|3|j|k|l|
+-+-+-+-+
The same repack for msb_first=False is performed as follows:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |h|g|f|e|d|c|b|a|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |X|X|X|X|X|X|l|k|j|i|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
into:
+-+-+-+-+
|0|c|b|a|
+-+-+-+-+
|1|f|e|d|
+-+-+-+-+
|2|i|h|g|
+-+-+-+-+
|3|l|k|j|
+-+-+-+-+
"""
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
return res
def repack_data_available(src_width, to_width, *, # noqa: N805
src_length=None, start=None, start_bit=0):
"""Calculates the maximum number of words that can be requested
from a repack invocation with the given settings.
This function can be called either on a BinArray instance (assuming
its width as the source width), or on the BinArray class (passing
the source width as an extra first argument). If called in the
second form, ``src_length`` must be provided. Otherwise, it will
default to the number of words in the source array from the given
``start`` index (defaulting to 0) until the end.
"""
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width
|
koriakin/binflakes | binflakes/types/array.py | BinArray.repack_data_available | python | def repack_data_available(src_width, to_width, *, # noqa: N805
src_length=None, start=None, start_bit=0):
start_bit = operator.index(start_bit)
if isinstance(src_width, BinArray):
self = src_width
if src_length is None:
if start is None:
start = 0
else:
start = operator.index(start)
if start < 0:
raise ValueError('start must not be negative')
src_length = len(self) - start
start = None
src_width = self.width
if src_length is None:
raise TypeError('no length given')
if start is not None:
raise TypeError('start is redundant with explicit src_length')
src_width = operator.index(src_width)
to_width = operator.index(to_width)
src_length = operator.index(src_length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if src_length < 0:
raise ValueError('src_length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
if src_length == 0 and start_bit != 0:
raise ValueError(
'src_length must be positive if start_bit is not zero')
return (src_width * src_length - start_bit) // to_width | Calculates the maximum number of words that can be requested
from a repack invocation with the given settings.
This function can be called either on a BinArray instance (assuming
its width as the source width), or on the BinArray class (passing
the source width as an extra first argument). If called in the
second form, ``src_length`` must be provided. Otherwise, it will
default to the number of words in the source array from the given
``start`` index (defaulting to 0) until the end. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/array.py#L439-L483 | null | class BinArray:
"""Represents an array of equal-width BinWords. Conceptually behaves
like bytearray, except that element width can be different than 8,
and item accesses return BinWord instances.
"""
__slots__ = '_width', '_len', '_data'
def __init__(self, data=None, *, width=None, length=None):
"""Creates a new BinArray. The following forms are valid:
- ``BinArray(bytes or bytearray)``: creates a BinArray of width 8
with items from the given bytearray.
- ``BinArray(BinArray instance)``: creates a copy of a BinArray.
- ``BinArray(width=w)``: creates empty BinArray of given width.
- ``BinArray(width=w, length=n)``: creates a zero-filled BinArray of
given width and length.
- ``BinArray(iterable, width=n)``: creates a BinArray from the given
iterable of items. Items should be ints, BinInts, or BinWords
of the correct width.
- ``BinArray(iterable)``: creates a BinArray from a non-empty array
of BinWords.
"""
if data is not None and length is not None:
raise TypeError('data and length are mutually exclusive')
if data is None:
if length is None:
length = 0
if width is None:
raise TypeError('width not specified')
length = operator.index(length)
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, length)
else:
try:
len(data)
except TypeError:
data = list(data)
if width is None:
if isinstance(data, (bytes, bytearray)):
width = 8
elif isinstance(data, BinArray):
width = data.width
else:
raise TypeError('width not specified')
width = operator.index(width)
if width < 0:
raise ValueError('width cannot be negative')
self._init(width, len(data))
for i, x in enumerate(data):
self[i] = x
def _init(self, width, len_):
"""Initializes internal data representation of the BinArray to all-0.
The internal data representation is simply tightly-packed bits of all
words, starting from LSB, split into bytes and stored in a bytearray.
The unused trailing padding bits in the last byte must always be set
to 0.
"""
self._width = width
self._len = len_
bits = len_ * width
self._data = bytearray(BinInt(bits).ceildiv(8))
def _locate(self, idx):
"""Locates an element in the internal data representation. Returns
starting byte index, starting bit index in the starting byte, and
one past the final byte index.
"""
start = idx * self._width
end = (idx + 1) * self._width
sbyte, sbit = divmod(start, 8)
ebyte = BinInt(end).ceildiv(8)
return sbyte, sbit, ebyte
@property
def width(self):
"""Returns word width of the BinArray."""
return self._width
def __len__(self):
"""Returns length of the array in words."""
return self._len
def __getitem__(self, idx):
"""Returns a word at the given index (as a BinWord instance),
or a slice of the array (as a new BinArray instance).
"""
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
res = BinArray(width=self._width, length=len(r))
for opos, ipos in enumerate(r):
res[opos] = self[ipos]
return res
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
return raw.extract(sbit, self._width)
def __setitem__(self, idx, val):
"""Assigns to the word at a given index, or to a subslice of
the array. When assigning words, the assigned value must be
a BinWord instance of the same width as the array, or an int
or BinInt instance that will be automatically converted
to BinWord. It is an error if an int or BinInt is assigned
that does not fit in ``width`` bits.
"""
if isinstance(idx, slice):
if not isinstance(val, BinArray):
raise TypeError('assigning non-BinArray to a slice')
if self._width != val._width:
raise ValueError('mismatched widths in slice assignment')
start, stop, step = idx.indices(len(self))
r = range(start, stop, step)
if len(r) != len(val):
raise ValueError('mismatched lengths in slice assignment')
for idx, item in zip(r, val):
self[idx] = item
else:
idx = operator.index(idx)
if idx < 0:
idx += len(self)
if idx not in range(len(self)):
raise IndexError('index out of range')
if isinstance(val, BinWord) and val._width != self._width:
raise ValueError('word width mismatch')
val = BinWord(self._width, val)
sbyte, sbit, ebyte = self._locate(idx)
raw = self._data[sbyte:ebyte]
raw = BinInt.from_bytes(raw, 'little')
raw = raw.deposit(sbit, val)
self._data[sbyte:ebyte] = raw.to_bytes(ebyte - sbyte, 'little')
def __repr__(self):
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ', '.join(f'0x{x.to_uint():{fmt}}' for x in self)
return f'BinArray([{elems}], width={self._width})'
def __str__(self):
"""Returns a textual representation in the following format:
``<width as a decimal number>'0x(<space-separated words as hexadecimal
numbers>)``. This format is directly accepted by the S-expression
parser.
"""
width_nibbles = BinInt(self._width).ceildiv(4)
fmt = f'0{width_nibbles}x'
elems = ' '.join(format(x.to_uint(), fmt) for x in self)
return f'{self._width}\'0x({elems})'
def __eq__(self, other):
"""Compares for equality with another object. BinArrays are only
considered equal to other BinArrays with the same width, length,
and contents.
"""
if not isinstance(other, BinArray):
return False
if self._width != other._width:
return False
if self._len != other._len:
return False
return self._data == other._data
def _check_match(self, other):
if not isinstance(other, BinArray):
raise TypeError(
'argument to bitwise operation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for bitwise operation')
if self._len != other._len:
raise ValueError('mismatched lengths for bitwise operation')
def __and__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise AND operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x & y for x, y in zip(self._data, other._data))
return res
def __or__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise OR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x | y for x, y in zip(self._data, other._data))
return res
def __xor__(self, other):
"""Creates a new BinArray from two equal-width, equal-length
BinArrays by applying the bitwise XOR operation to every pair
of corresponding words.
"""
self._check_match(other)
res = BinArray.__new__(BinArray)
res._width = self._width
res._len = self._len
res._data = bytearray(x ^ y for x, y in zip(self._data, other._data))
return res
def __iand__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] &= val
return self
def __ior__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] |= val
return self
def __ixor__(self, other):
self._check_match(other)
for idx, val in enumerate(other._data):
self._data[idx] ^= val
return self
def __invert__(self):
"""Creates a new BinArray with all bits inverted."""
return BinArray([~x for x in self], width=self._width)
def __add__(self, other):
"""Concatenates two equal-width BinArray instances together, returning
a new BinArray.
"""
if not isinstance(other, BinArray):
raise TypeError(
'argument to concatenation must be another BinArray')
if self._width != other._width:
raise ValueError('mismatched widths for concatenation')
res = BinArray(width=self._width, length=len(self) + len(other))
res[:len(self)] = self
res[len(self):] = other
return res
def __mul__(self, count):
"""Repeats a BinArray count times, returning a new BinArray."""
count = operator.index(count)
if count < 0:
raise ValueError('negative repetition count')
sl = len(self)
res = BinArray(width=self._width, length=sl * count)
for idx in range(count):
res[idx * sl:(idx + 1) * sl] = self
return res
__rmul__ = __mul__
def repack(self, to_width, *, msb_first, start=0, start_bit=0,
length=None):
"""Extracts a part of a BinArray's data and converts it to a BinArray
of a different width.
For the purposes of this conversion, words in this BinArray are joined
side-by-side, starting from a given start index (defaulting to 0),
skipping ``start_bit`` first bits of the first word, then the resulting
stream is split into ``to_width``-sized words and ``length`` first
such words are returned as a new BinArray.
If ``msb_first`` is False, everything proceeds with little endian
ordering: the first word provides the least significant bits of the
combined stream, ``start_bit`` skips bits starting from the LSB,
and the first output word is made from the lowest bits of the combined
stream. Otherwise (``msb_first`` is True), everything proceeds
with big endian ordering: the first word provides the most
significant bits of the combined stream, ``start_bit`` skips bits
starting from the MSB, and the first output word is made from the
highest bits of the combined stream.
``start_bits`` must be smaller than the width of the input word.
It is an error to request a larger length than can be provided from
the input array. If ``length`` is not provided, this function
returns as many words as can be extracted.
For example, consider a 10-to-3 repack with start_bit=2, length=4
msb_first=True:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |X|X|a|b|c|d|e|f|g|h|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |i|j|k|l|X|X|X|X|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
is repacked to:
+-+-+-+-+
|0|a|b|c|
+-+-+-+-+
|1|d|e|f|
+-+-+-+-+
|2|g|h|i|
+-+-+-+-+
|3|j|k|l|
+-+-+-+-+
The same repack for msb_first=False is performed as follows:
+---------+-+-+-+-+-+-+-+-+-+-+
| | MSB ... LSB |
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
| start |h|g|f|e|d|c|b|a|X|X|
+---------+-+-+-+-+-+-+-+-+-+-+
| start+1 |X|X|X|X|X|X|l|k|j|i|
+---------+-+-+-+-+-+-+-+-+-+-+
| | ... |
+---------+-+-+-+-+-+-+-+-+-+-+
into:
+-+-+-+-+
|0|c|b|a|
+-+-+-+-+
|1|f|e|d|
+-+-+-+-+
|2|i|h|g|
+-+-+-+-+
|3|l|k|j|
+-+-+-+-+
"""
to_width = operator.index(to_width)
if not isinstance(msb_first, bool):
raise TypeError('msb_first must be a bool')
available = self.repack_data_available(
to_width, start=start, start_bit=start_bit)
if length is None:
length = available
else:
length = operator.index(length)
if length > available:
raise ValueError('not enough data available')
if length < 0:
raise ValueError('length cannot be negative')
start = operator.index(start)
start_bit = operator.index(start_bit)
pos = start
accum = BinWord(0, 0)
if start_bit:
accum = self[pos]
pos += 1
rest = accum.width - start_bit
if msb_first:
accum = accum.extract(0, rest)
else:
accum = accum.extract(start_bit, rest)
res = BinArray(width=to_width, length=length)
for idx in range(length):
while len(accum) < to_width:
cur = self[pos]
pos += 1
if msb_first:
accum = BinWord.concat(cur, accum)
else:
accum = BinWord.concat(accum, cur)
rest = accum.width - to_width
if msb_first:
cur = accum.extract(rest, to_width)
accum = accum.extract(0, rest)
else:
cur = accum.extract(0, to_width)
accum = accum.extract(to_width, rest)
res[idx] = cur
return res
def repack_source_required(src_width, to_width, length, *, # noqa: N805
start_bit=0):
"""Calculates how many source words would be read for an invocation of
repack with a given length, including possible partial words at
the beginning and the end of the repack source. This can be called
either on a concrete BinArray instance (assuming its width as the
source width), or on the BinArray class (providing the source width
as an extra first argument). This function doesn't take ``start``
or ``msb_first`` parameters, since they wouldn't affect the
computation.
"""
if isinstance(src_width, BinArray):
src_width = src_width._width
src_width = operator.index(src_width)
to_width = operator.index(to_width)
length = operator.index(length)
start_bit = operator.index(start_bit)
if src_width <= 0:
raise ValueError('source width must be positive')
if to_width <= 0:
raise ValueError('destination width must be positive')
if length < 0:
raise ValueError('length must not be negative')
if start_bit not in range(src_width):
raise ValueError('start bit must be in [0, src_width)')
return BinInt(start_bit + to_width * length).ceildiv(src_width)
|
koriakin/binflakes | binflakes/sexpr/read.py | read_file | python | def read_file(file, filename='<input>'):
reader = Reader(filename)
for line in file:
yield from reader.feed_line(line)
reader.finish() | This is a generator that yields all top-level S-expression nodes from
a given file object. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/read.py#L340-L346 | [
"def feed_line(self, line):\n \"\"\"Feeds one line of input into the reader machine. This method is\n a generator that yields all top-level S-expressions that have been\n recognized on this line (including multi-line expressions whose last\n character is on this line).\n \"\"\"\n self.line += 1\n... | import re
from enum import Enum
from io import StringIO
from attr import attrs, attrib
from attr.validators import instance_of
from binflakes.types import BinWord, BinArray
from .string import ESCAPE_TO_CHAR
from .symbol import Symbol
from .location import TextLocationSingle, TextLocationRange
from .nodes import GenericNode
class ReadError(Exception):
"""An exception class used for all problems noticed by the reader."""
pass
class State(Enum):
"""Represents the reader state (between tokens, inside a string token,
inside a BinArray token.
"""
NORMAL = 'normal'
STRING = 'string'
BINARRAY = 'binarray'
@attrs(slots=True)
class StackEntryList:
"""A reader stack entry representing a list currently being parsed.
``items`` are the items parsed so far, ``start`` is the location of
the opening paren.
"""
start = attrib(validator=instance_of(TextLocationSingle))
items = attrib(validator=instance_of(list))
def raise_unclosed_error(self):
raise ReadError(f'{self.start}: unmatched opening paren')
@attrs(slots=True)
class StackEntryComment:
"""A reader stack entry representing a commented-out S-expression
currently being parsed. ``start`` is the location of the opening
comment sign.
"""
start = attrib(validator=instance_of(TextLocationRange))
def raise_unclosed_error(self):
raise ReadError(f'{self.start}: unclosed S-expr comment')
RE_TOKEN = re.compile(r'''
# Any amount of whitespace.
(?P<whitespace>[ \t\r\n\f]+) |
# Line comment (hash followed by space).
(?P<line_comment>\#\ .*$) |
# Left paren.
(?P<lparen>\() |
# Start of string (switches parser to STRING state).
(?:(?P<string_width>[0-9]+)')? (?P<start_quote>") |
# Start of BinArray (switches parser to BINARRAY state).
(?P<array_width>[0-9]+)'(?P<array_base>0[box])?\( |
# These tokens must be followed by whitespace, end of line,
# or a right paren.
(?:
# A right paren.
(?P<rparen>\)) |
# The singletons.
(?P<nil_value>@nil) |
(?P<bool_value>@true|@false) |
# Ints and words.
(?:(?P<word_width>[0-9]+)')? (?P<int_or_word>
(?P<number>
-? 0b [0-1]+ |
-? 0o [0-7]+ |
-? 0x [0-9a-fA-F]+ |
-? [1-9][0-9]* |
-? 0
) |
'(?:
# Simple unescaped character.
(?P<raw_char>[^\\']) |
# A single-character escape.
\\(?P<simple_escape>[abtnfre\\"]) |
# A hex character escape.
\\[xuU](?P<hex_code>
(?<=x)[0-9a-fA-F]{2} |
(?<=u)[0-9a-fA-F]{4} |
(?<=U)[0-9a-fA-F]{6}
)
)'
) |
# Symbols.
(?P<symbol>
[a-zA-Z*+=<>!?/$%_][0-9a-zA-Z*+=<>!?/$%_-]* |
-
)
)(?= $ | [ \t\r\n\f)] | (?P<ws_error>)) |
# S-expr comment.
(?P<sexpr_comment>\#\#)
''', re.VERBOSE)
RE_STRING_ITEM = re.compile(r'''
# End of string (must be followed by whitespace, end of line,
# or right paren.
(?P<end_quote>") (?= $ | [ \t\r\n\f)] | (?P<ws_error>)) |
# Simple unescaped characters.
(?P<raw_chars>[^\\"]+) |
# A single-character escape.
\\(?P<simple_escape>[abtnfre\\"]) |
# A hex character escape.
\\[xuU](?P<hex_code>
(?<=x)[0-9a-fA-F]{2} |
(?<=u)[0-9a-fA-F]{4} |
(?<=U)[0-9a-fA-F]{6}
)
''', re.VERBOSE)
# Patterns common to all BINARRAY bases.
def _re_binarray_item(digits):
return re.compile(r'''
# Any amount of whitespace.
(?P<whitespace>[ \t\r\n\f]+) |
# Line comment.
(?P<line_comment>\# .*$) |
# These tokens must be followed by whitespace, end of line,
# or a right paren.
(?:
(?P<rparen>\)) |
''' + digits + r'''
) (?= $ | [ \t\r\n\f)] | (?P<ws_error>))
''', re.VERBOSE)
RE_BINARRAY_ITEM = {
2: _re_binarray_item(r'''(?P<digits>-?[0-1]+)'''),
8: _re_binarray_item(r'''(?P<digits>-?[0-7]+)'''),
10: _re_binarray_item(r'''
(?P<digits>
-? [1-9][0-9]* |
-? 0
)
'''),
16: _re_binarray_item(r'''(?P<digits>-?[0-9a-fA-F]+)'''),
}
class Reader:
"""A class for reading S-expressions and converting them to a node tree.
Accepts the input line-by-line, yielding top-level S-expressions as they
are recognized.
"""
def __init__(self, filename):
"""Initializes internal state. ``filename`` affects only the location
tags that will be attached to nodes.
"""
self.filename = filename
self.stack = []
self.state = State.NORMAL
self.line = 0
# Only valid when state is STRING.
self.string_buffer = None
# Only valid when state is BINARRAY.
self.binarray_base = None
self.binarray_data = None
# Only valid when state is STRING or BINARRAY.
self.binarray_width = None
self.token_start = None
def feed_line(self, line):
"""Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line).
"""
self.line += 1
pos = 0
while pos < len(line):
loc_start = TextLocationSingle(self.filename, self.line, pos + 1)
if self.state is State.NORMAL:
item_re = RE_TOKEN
thing = 'token'
elif self.state is State.STRING:
item_re = RE_STRING_ITEM
thing = 'escape sequence'
elif self.state is State.BINARRAY:
item_re = RE_BINARRAY_ITEM[self.binarray_base]
thing = 'binarray item'
else:
assert 0
match = item_re.match(line, pos)
if not match:
raise ReadError(f'{loc_start}: unknown {thing}')
pos = match.end()
loc_end = TextLocationSingle(self.filename, self.line, pos + 1)
loc = loc_start - loc_end
if match['ws_error'] is not None:
raise ReadError(f'{loc_end}: no whitespace after token')
if self.state is State.NORMAL:
# Normal state -- read tokens.
if match['lparen'] is not None:
self.stack.append(StackEntryList(loc_start, []))
elif match['rparen'] is not None:
if not self.stack:
raise ReadError(f'{loc}: unmatched closing paren')
top = self.stack.pop()
if not isinstance(top, StackEntryList):
top.raise_unclosed_error()
yield from self._feed_node(top.items, top.start - loc_end)
elif match['symbol'] is not None:
value = Symbol(match['symbol'])
yield from self._feed_node(value, loc)
elif match['sexpr_comment'] is not None:
self.stack.append(StackEntryComment(loc))
elif match['bool_value'] is not None:
value = match['bool_value'] == '@true'
yield from self._feed_node(value, loc)
elif match['nil_value'] is not None:
yield from self._feed_node(None, loc)
elif match['int_or_word'] is not None:
if match['number'] is not None:
value = int(match['number'], 0)
elif match['raw_char'] is not None:
value = ord(match['raw_char'])
elif match['simple_escape'] is not None:
value = ord(ESCAPE_TO_CHAR[match['simple_escape']])
elif match['hex_code'] is not None:
value = int(match['hex_code'], 16)
if value not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
else:
assert 0
if match['word_width'] is not None:
width = int(match['word_width'])
if value < 0:
value += 1 << width
if value not in range(1 << width):
raise ReadError(f'{loc}: word value out of range')
value = BinWord(width, value)
yield from self._feed_node(value, loc)
elif match['array_width'] is not None:
self.binarray_base = {
'0b': 2,
'0o': 8,
None: 10,
'0x': 16,
}[match['array_base']]
self.binarray_data = []
self.binarray_width = int(match['array_width'])
self.token_start = loc_start
self.state = State.BINARRAY
elif match['start_quote'] is not None:
self.state = State.STRING
self.token_start = loc_start
self.string_buffer = StringIO()
if match['string_width'] is not None:
self.binarray_width = int(match['string_width'])
else:
self.binarray_width = None
elif self.state is State.STRING:
# Inside a string.
if match['end_quote'] is not None:
self.state = State.NORMAL
value = self.string_buffer.getvalue()
loc = self.token_start - loc_end
if self.binarray_width is not None:
vals = [ord(x) for x in value]
for x in vals:
if x not in range(1 << self.binarray_width):
raise ReadError(
f'{loc}: character code out of range')
value = BinArray(vals, width=self.binarray_width)
yield from self._feed_node(value, loc)
elif match['raw_chars'] is not None:
self.string_buffer.write(match['raw_chars'])
elif match['simple_escape'] is not None:
c = ESCAPE_TO_CHAR[match['simple_escape']]
self.string_buffer.write(c)
elif match['hex_code'] is not None:
code = int(match['hex_code'], 16)
if code not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
self.string_buffer.write(chr(code))
else:
assert 0
elif self.state is State.BINARRAY:
# In a BinArray.
if match['rparen'] is not None:
self.state = State.NORMAL
value = BinArray(self.binarray_data,
width=self.binarray_width)
loc = self.token_start - loc_end
yield from self._feed_node(value, loc)
elif match['digits'] is not None:
value = int(match['digits'], self.binarray_base)
if value < 0:
value += 1 << self.binarray_width
if value not in range(1 << self.binarray_width):
raise ReadError(f'{loc}: word value out of range')
self.binarray_data.append(value)
else:
assert 0
def _feed_node(self, value, loc):
"""A helper method called when an S-expression has been recognized.
Like feed_line, this is a generator that yields newly recognized
top-level expressions. If the reader is currently at the top level,
simply yields the passed expression. Otherwise, it appends it
to whatever is currently being parsed and yields nothing.
"""
node = GenericNode(value, loc)
if not self.stack:
yield node
else:
top = self.stack[-1]
if isinstance(top, StackEntryList):
top.items.append(node)
elif isinstance(top, StackEntryComment):
self.stack.pop()
else:
assert 0
def finish(self):
"""Ensures the reader is in clean state (no unclosed S-expression
is currently being parsed). Should be called after the last
``feed_line``.
"""
if self.state is not State.NORMAL:
raise ReadError(f'EOF while in {self.state.name} state')
if self.stack:
top = self.stack[-1]
top.raise_unclosed_error()
def read_string(s, filename='<string>'):
"""Reads all S-expressions from a given string and returns a list
of nodes."""
return list(read_file(StringIO(s), filename))
|
koriakin/binflakes | binflakes/sexpr/read.py | Reader.feed_line | python | def feed_line(self, line):
self.line += 1
pos = 0
while pos < len(line):
loc_start = TextLocationSingle(self.filename, self.line, pos + 1)
if self.state is State.NORMAL:
item_re = RE_TOKEN
thing = 'token'
elif self.state is State.STRING:
item_re = RE_STRING_ITEM
thing = 'escape sequence'
elif self.state is State.BINARRAY:
item_re = RE_BINARRAY_ITEM[self.binarray_base]
thing = 'binarray item'
else:
assert 0
match = item_re.match(line, pos)
if not match:
raise ReadError(f'{loc_start}: unknown {thing}')
pos = match.end()
loc_end = TextLocationSingle(self.filename, self.line, pos + 1)
loc = loc_start - loc_end
if match['ws_error'] is not None:
raise ReadError(f'{loc_end}: no whitespace after token')
if self.state is State.NORMAL:
# Normal state -- read tokens.
if match['lparen'] is not None:
self.stack.append(StackEntryList(loc_start, []))
elif match['rparen'] is not None:
if not self.stack:
raise ReadError(f'{loc}: unmatched closing paren')
top = self.stack.pop()
if not isinstance(top, StackEntryList):
top.raise_unclosed_error()
yield from self._feed_node(top.items, top.start - loc_end)
elif match['symbol'] is not None:
value = Symbol(match['symbol'])
yield from self._feed_node(value, loc)
elif match['sexpr_comment'] is not None:
self.stack.append(StackEntryComment(loc))
elif match['bool_value'] is not None:
value = match['bool_value'] == '@true'
yield from self._feed_node(value, loc)
elif match['nil_value'] is not None:
yield from self._feed_node(None, loc)
elif match['int_or_word'] is not None:
if match['number'] is not None:
value = int(match['number'], 0)
elif match['raw_char'] is not None:
value = ord(match['raw_char'])
elif match['simple_escape'] is not None:
value = ord(ESCAPE_TO_CHAR[match['simple_escape']])
elif match['hex_code'] is not None:
value = int(match['hex_code'], 16)
if value not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
else:
assert 0
if match['word_width'] is not None:
width = int(match['word_width'])
if value < 0:
value += 1 << width
if value not in range(1 << width):
raise ReadError(f'{loc}: word value out of range')
value = BinWord(width, value)
yield from self._feed_node(value, loc)
elif match['array_width'] is not None:
self.binarray_base = {
'0b': 2,
'0o': 8,
None: 10,
'0x': 16,
}[match['array_base']]
self.binarray_data = []
self.binarray_width = int(match['array_width'])
self.token_start = loc_start
self.state = State.BINARRAY
elif match['start_quote'] is not None:
self.state = State.STRING
self.token_start = loc_start
self.string_buffer = StringIO()
if match['string_width'] is not None:
self.binarray_width = int(match['string_width'])
else:
self.binarray_width = None
elif self.state is State.STRING:
# Inside a string.
if match['end_quote'] is not None:
self.state = State.NORMAL
value = self.string_buffer.getvalue()
loc = self.token_start - loc_end
if self.binarray_width is not None:
vals = [ord(x) for x in value]
for x in vals:
if x not in range(1 << self.binarray_width):
raise ReadError(
f'{loc}: character code out of range')
value = BinArray(vals, width=self.binarray_width)
yield from self._feed_node(value, loc)
elif match['raw_chars'] is not None:
self.string_buffer.write(match['raw_chars'])
elif match['simple_escape'] is not None:
c = ESCAPE_TO_CHAR[match['simple_escape']]
self.string_buffer.write(c)
elif match['hex_code'] is not None:
code = int(match['hex_code'], 16)
if code not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
self.string_buffer.write(chr(code))
else:
assert 0
elif self.state is State.BINARRAY:
# In a BinArray.
if match['rparen'] is not None:
self.state = State.NORMAL
value = BinArray(self.binarray_data,
width=self.binarray_width)
loc = self.token_start - loc_end
yield from self._feed_node(value, loc)
elif match['digits'] is not None:
value = int(match['digits'], self.binarray_base)
if value < 0:
value += 1 << self.binarray_width
if value not in range(1 << self.binarray_width):
raise ReadError(f'{loc}: word value out of range')
self.binarray_data.append(value)
else:
assert 0 | Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line). | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/read.py#L173-L307 | [
"def _feed_node(self, value, loc):\n \"\"\"A helper method called when an S-expression has been recognized.\n Like feed_line, this is a generator that yields newly recognized\n top-level expressions. If the reader is currently at the top level,\n simply yields the passed expression. Otherwise, it appe... | class Reader:
"""A class for reading S-expressions and converting them to a node tree.
Accepts the input line-by-line, yielding top-level S-expressions as they
are recognized.
"""
def __init__(self, filename):
"""Initializes internal state. ``filename`` affects only the location
tags that will be attached to nodes.
"""
self.filename = filename
self.stack = []
self.state = State.NORMAL
self.line = 0
# Only valid when state is STRING.
self.string_buffer = None
# Only valid when state is BINARRAY.
self.binarray_base = None
self.binarray_data = None
# Only valid when state is STRING or BINARRAY.
self.binarray_width = None
self.token_start = None
def _feed_node(self, value, loc):
"""A helper method called when an S-expression has been recognized.
Like feed_line, this is a generator that yields newly recognized
top-level expressions. If the reader is currently at the top level,
simply yields the passed expression. Otherwise, it appends it
to whatever is currently being parsed and yields nothing.
"""
node = GenericNode(value, loc)
if not self.stack:
yield node
else:
top = self.stack[-1]
if isinstance(top, StackEntryList):
top.items.append(node)
elif isinstance(top, StackEntryComment):
self.stack.pop()
else:
assert 0
def finish(self):
"""Ensures the reader is in clean state (no unclosed S-expression
is currently being parsed). Should be called after the last
``feed_line``.
"""
if self.state is not State.NORMAL:
raise ReadError(f'EOF while in {self.state.name} state')
if self.stack:
top = self.stack[-1]
top.raise_unclosed_error()
|
koriakin/binflakes | binflakes/sexpr/read.py | Reader._feed_node | python | def _feed_node(self, value, loc):
node = GenericNode(value, loc)
if not self.stack:
yield node
else:
top = self.stack[-1]
if isinstance(top, StackEntryList):
top.items.append(node)
elif isinstance(top, StackEntryComment):
self.stack.pop()
else:
assert 0 | A helper method called when an S-expression has been recognized.
Like feed_line, this is a generator that yields newly recognized
top-level expressions. If the reader is currently at the top level,
simply yields the passed expression. Otherwise, it appends it
to whatever is currently being parsed and yields nothing. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/read.py#L309-L326 | null | class Reader:
"""A class for reading S-expressions and converting them to a node tree.
Accepts the input line-by-line, yielding top-level S-expressions as they
are recognized.
"""
def __init__(self, filename):
"""Initializes internal state. ``filename`` affects only the location
tags that will be attached to nodes.
"""
self.filename = filename
self.stack = []
self.state = State.NORMAL
self.line = 0
# Only valid when state is STRING.
self.string_buffer = None
# Only valid when state is BINARRAY.
self.binarray_base = None
self.binarray_data = None
# Only valid when state is STRING or BINARRAY.
self.binarray_width = None
self.token_start = None
def feed_line(self, line):
"""Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line).
"""
self.line += 1
pos = 0
while pos < len(line):
loc_start = TextLocationSingle(self.filename, self.line, pos + 1)
if self.state is State.NORMAL:
item_re = RE_TOKEN
thing = 'token'
elif self.state is State.STRING:
item_re = RE_STRING_ITEM
thing = 'escape sequence'
elif self.state is State.BINARRAY:
item_re = RE_BINARRAY_ITEM[self.binarray_base]
thing = 'binarray item'
else:
assert 0
match = item_re.match(line, pos)
if not match:
raise ReadError(f'{loc_start}: unknown {thing}')
pos = match.end()
loc_end = TextLocationSingle(self.filename, self.line, pos + 1)
loc = loc_start - loc_end
if match['ws_error'] is not None:
raise ReadError(f'{loc_end}: no whitespace after token')
if self.state is State.NORMAL:
# Normal state -- read tokens.
if match['lparen'] is not None:
self.stack.append(StackEntryList(loc_start, []))
elif match['rparen'] is not None:
if not self.stack:
raise ReadError(f'{loc}: unmatched closing paren')
top = self.stack.pop()
if not isinstance(top, StackEntryList):
top.raise_unclosed_error()
yield from self._feed_node(top.items, top.start - loc_end)
elif match['symbol'] is not None:
value = Symbol(match['symbol'])
yield from self._feed_node(value, loc)
elif match['sexpr_comment'] is not None:
self.stack.append(StackEntryComment(loc))
elif match['bool_value'] is not None:
value = match['bool_value'] == '@true'
yield from self._feed_node(value, loc)
elif match['nil_value'] is not None:
yield from self._feed_node(None, loc)
elif match['int_or_word'] is not None:
if match['number'] is not None:
value = int(match['number'], 0)
elif match['raw_char'] is not None:
value = ord(match['raw_char'])
elif match['simple_escape'] is not None:
value = ord(ESCAPE_TO_CHAR[match['simple_escape']])
elif match['hex_code'] is not None:
value = int(match['hex_code'], 16)
if value not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
else:
assert 0
if match['word_width'] is not None:
width = int(match['word_width'])
if value < 0:
value += 1 << width
if value not in range(1 << width):
raise ReadError(f'{loc}: word value out of range')
value = BinWord(width, value)
yield from self._feed_node(value, loc)
elif match['array_width'] is not None:
self.binarray_base = {
'0b': 2,
'0o': 8,
None: 10,
'0x': 16,
}[match['array_base']]
self.binarray_data = []
self.binarray_width = int(match['array_width'])
self.token_start = loc_start
self.state = State.BINARRAY
elif match['start_quote'] is not None:
self.state = State.STRING
self.token_start = loc_start
self.string_buffer = StringIO()
if match['string_width'] is not None:
self.binarray_width = int(match['string_width'])
else:
self.binarray_width = None
elif self.state is State.STRING:
# Inside a string.
if match['end_quote'] is not None:
self.state = State.NORMAL
value = self.string_buffer.getvalue()
loc = self.token_start - loc_end
if self.binarray_width is not None:
vals = [ord(x) for x in value]
for x in vals:
if x not in range(1 << self.binarray_width):
raise ReadError(
f'{loc}: character code out of range')
value = BinArray(vals, width=self.binarray_width)
yield from self._feed_node(value, loc)
elif match['raw_chars'] is not None:
self.string_buffer.write(match['raw_chars'])
elif match['simple_escape'] is not None:
c = ESCAPE_TO_CHAR[match['simple_escape']]
self.string_buffer.write(c)
elif match['hex_code'] is not None:
code = int(match['hex_code'], 16)
if code not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
self.string_buffer.write(chr(code))
else:
assert 0
elif self.state is State.BINARRAY:
# In a BinArray.
if match['rparen'] is not None:
self.state = State.NORMAL
value = BinArray(self.binarray_data,
width=self.binarray_width)
loc = self.token_start - loc_end
yield from self._feed_node(value, loc)
elif match['digits'] is not None:
value = int(match['digits'], self.binarray_base)
if value < 0:
value += 1 << self.binarray_width
if value not in range(1 << self.binarray_width):
raise ReadError(f'{loc}: word value out of range')
self.binarray_data.append(value)
else:
assert 0
def finish(self):
"""Ensures the reader is in clean state (no unclosed S-expression
is currently being parsed). Should be called after the last
``feed_line``.
"""
if self.state is not State.NORMAL:
raise ReadError(f'EOF while in {self.state.name} state')
if self.stack:
top = self.stack[-1]
top.raise_unclosed_error()
|
koriakin/binflakes | binflakes/sexpr/read.py | Reader.finish | python | def finish(self):
if self.state is not State.NORMAL:
raise ReadError(f'EOF while in {self.state.name} state')
if self.stack:
top = self.stack[-1]
top.raise_unclosed_error() | Ensures the reader is in clean state (no unclosed S-expression
is currently being parsed). Should be called after the last
``feed_line``. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/read.py#L328-L337 | null | class Reader:
"""A class for reading S-expressions and converting them to a node tree.
Accepts the input line-by-line, yielding top-level S-expressions as they
are recognized.
"""
def __init__(self, filename):
"""Initializes internal state. ``filename`` affects only the location
tags that will be attached to nodes.
"""
self.filename = filename
self.stack = []
self.state = State.NORMAL
self.line = 0
# Only valid when state is STRING.
self.string_buffer = None
# Only valid when state is BINARRAY.
self.binarray_base = None
self.binarray_data = None
# Only valid when state is STRING or BINARRAY.
self.binarray_width = None
self.token_start = None
def feed_line(self, line):
"""Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line).
"""
self.line += 1
pos = 0
while pos < len(line):
loc_start = TextLocationSingle(self.filename, self.line, pos + 1)
if self.state is State.NORMAL:
item_re = RE_TOKEN
thing = 'token'
elif self.state is State.STRING:
item_re = RE_STRING_ITEM
thing = 'escape sequence'
elif self.state is State.BINARRAY:
item_re = RE_BINARRAY_ITEM[self.binarray_base]
thing = 'binarray item'
else:
assert 0
match = item_re.match(line, pos)
if not match:
raise ReadError(f'{loc_start}: unknown {thing}')
pos = match.end()
loc_end = TextLocationSingle(self.filename, self.line, pos + 1)
loc = loc_start - loc_end
if match['ws_error'] is not None:
raise ReadError(f'{loc_end}: no whitespace after token')
if self.state is State.NORMAL:
# Normal state -- read tokens.
if match['lparen'] is not None:
self.stack.append(StackEntryList(loc_start, []))
elif match['rparen'] is not None:
if not self.stack:
raise ReadError(f'{loc}: unmatched closing paren')
top = self.stack.pop()
if not isinstance(top, StackEntryList):
top.raise_unclosed_error()
yield from self._feed_node(top.items, top.start - loc_end)
elif match['symbol'] is not None:
value = Symbol(match['symbol'])
yield from self._feed_node(value, loc)
elif match['sexpr_comment'] is not None:
self.stack.append(StackEntryComment(loc))
elif match['bool_value'] is not None:
value = match['bool_value'] == '@true'
yield from self._feed_node(value, loc)
elif match['nil_value'] is not None:
yield from self._feed_node(None, loc)
elif match['int_or_word'] is not None:
if match['number'] is not None:
value = int(match['number'], 0)
elif match['raw_char'] is not None:
value = ord(match['raw_char'])
elif match['simple_escape'] is not None:
value = ord(ESCAPE_TO_CHAR[match['simple_escape']])
elif match['hex_code'] is not None:
value = int(match['hex_code'], 16)
if value not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
else:
assert 0
if match['word_width'] is not None:
width = int(match['word_width'])
if value < 0:
value += 1 << width
if value not in range(1 << width):
raise ReadError(f'{loc}: word value out of range')
value = BinWord(width, value)
yield from self._feed_node(value, loc)
elif match['array_width'] is not None:
self.binarray_base = {
'0b': 2,
'0o': 8,
None: 10,
'0x': 16,
}[match['array_base']]
self.binarray_data = []
self.binarray_width = int(match['array_width'])
self.token_start = loc_start
self.state = State.BINARRAY
elif match['start_quote'] is not None:
self.state = State.STRING
self.token_start = loc_start
self.string_buffer = StringIO()
if match['string_width'] is not None:
self.binarray_width = int(match['string_width'])
else:
self.binarray_width = None
elif self.state is State.STRING:
# Inside a string.
if match['end_quote'] is not None:
self.state = State.NORMAL
value = self.string_buffer.getvalue()
loc = self.token_start - loc_end
if self.binarray_width is not None:
vals = [ord(x) for x in value]
for x in vals:
if x not in range(1 << self.binarray_width):
raise ReadError(
f'{loc}: character code out of range')
value = BinArray(vals, width=self.binarray_width)
yield from self._feed_node(value, loc)
elif match['raw_chars'] is not None:
self.string_buffer.write(match['raw_chars'])
elif match['simple_escape'] is not None:
c = ESCAPE_TO_CHAR[match['simple_escape']]
self.string_buffer.write(c)
elif match['hex_code'] is not None:
code = int(match['hex_code'], 16)
if code not in range(0x110000):
raise ReadError(
f'{loc}: not a valid unicode codepoint')
self.string_buffer.write(chr(code))
else:
assert 0
elif self.state is State.BINARRAY:
# In a BinArray.
if match['rparen'] is not None:
self.state = State.NORMAL
value = BinArray(self.binarray_data,
width=self.binarray_width)
loc = self.token_start - loc_end
yield from self._feed_node(value, loc)
elif match['digits'] is not None:
value = int(match['digits'], self.binarray_base)
if value < 0:
value += 1 << self.binarray_width
if value not in range(1 << self.binarray_width):
raise ReadError(f'{loc}: word value out of range')
self.binarray_data.append(value)
else:
assert 0
def _feed_node(self, value, loc):
"""A helper method called when an S-expression has been recognized.
Like feed_line, this is a generator that yields newly recognized
top-level expressions. If the reader is currently at the top level,
simply yields the passed expression. Otherwise, it appends it
to whatever is currently being parsed and yields nothing.
"""
node = GenericNode(value, loc)
if not self.stack:
yield node
else:
top = self.stack[-1]
if isinstance(top, StackEntryList):
top.items.append(node)
elif isinstance(top, StackEntryComment):
self.stack.pop()
else:
assert 0
|
koriakin/binflakes | binflakes/sexpr/string.py | escape_string | python | def escape_string(value):
res = StringIO()
res.write('"')
for c in value:
if c in CHAR_TO_ESCAPE:
res.write(f'\\{CHAR_TO_ESCAPE[c]}')
elif c.isprintable():
res.write(c)
elif ord(c) < 0x100:
res.write(f'\\x{ord(c):02x}')
elif ord(c) < 0x10000:
res.write(f'\\u{ord(c):04x}')
else:
res.write(f'\\U{ord(c):06x}')
res.write('"')
return res.getvalue() | Converts a string to its S-expression representation, adding quotes
and escaping funny characters. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/string.py#L18-L36 | null | from io import StringIO
ESCAPE_TO_CHAR = {
'a': '\a',
'b': '\b',
't': '\t',
'n': '\n',
'f': '\f',
'r': '\r',
'e': '\x1b',
'\\': '\\',
'"': '"',
}
CHAR_TO_ESCAPE = {v: k for k, v in ESCAPE_TO_CHAR.items()}
|
koriakin/binflakes | binflakes/types/int.py | BinInt.extract | python | def extract(self, pos, width):
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0:
raise ValueError('extracting out of range')
return BinWord(width, self >> pos, trunc=True) | Extracts a subword with a given width, starting from a given
bit position. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/int.py#L72-L82 | null | class BinInt(int):
"""A class representing an arbitrary-precision binary integer number.
This is just a python int with some extra methods.
Can be treated as an infinite sequence of individual bits (which are
represented as BinWords of width 1), with bit 0 being the LSB.
For non-negative numbers, all bits from a certain point are equal to 0.
For negative numbers, all bits from a certain point are equal to 1
(following two's complement convention).
"""
__slots__ = ()
@classmethod
def mask(cls, width):
"""Creates a new BinInt with low ``width`` bits set."""
return cls((1 << width) - 1)
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
Since BinInt is, conceptually, an infinite sequence of bits,
it is an error to use negative indices. However, it is fine
to omit the stop index, returning an infinite subsequence
of bits -- a BigInt is returned in this case. For finite
sequences, a BinWord is returned.
"""
if not isinstance(idx, slice):
return self.extract(idx, 1)
step = 1 if idx.step is None else operator.index(idx.step)
if step == 0:
raise ValueError('step cannot be 0')
if step < 0 and idx.start is None:
raise ValueError('start cannot be None for reverse slicing')
start = 0 if idx.start is None else operator.index(idx.start)
stop = None if idx.stop is None else operator.index(idx.stop)
if start < 0:
raise ValueError(
'indexing from the end doesn\'t make sense for a BinInt')
if stop is not None and stop < 0:
raise ValueError(
'indexing from the end doesn\'t make sense for a BinInt')
if stop is None and step > 0:
if step == 1:
return self >> start
bits = self.bit_length()
r = range(start, bits, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self >> ipos & 1) << opos
if self < 0:
val |= -1 << len(r)
return BinInt(val)
else:
if stop is None:
stop = -1
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self >> ipos & 1) << opos
return BinWord(len(r), val)
def deposit(self, pos, val):
"""Returns a copy of this BinInt, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
with bits from val).
"""
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0:
raise ValueError('depositing out of range')
res = self
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return res
def __repr__(self):
return f'BinInt({self})'
def __add__(self, other):
return BinInt(super().__add__(other))
def __radd__(self, other):
return BinInt(super().__radd__(other))
def __sub__(self, other):
return BinInt(super().__sub__(other))
def __rsub__(self, other):
return BinInt(super().__rsub__(other))
def __mul__(self, other):
return BinInt(super().__mul__(other))
def __rmul__(self, other):
return BinInt(super().__rmul__(other))
def __floordiv__(self, other):
return BinInt(super().__floordiv__(other))
def __rfloordiv__(self, other):
return BinInt(super().__rfloordiv__(other))
def __mod__(self, other):
return BinInt(super().__mod__(other))
def __rmod__(self, other):
return BinInt(super().__rmod__(other))
def __and__(self, other):
return BinInt(super().__and__(other))
def __rand__(self, other):
return BinInt(super().__rand__(other))
def __or__(self, other):
return BinInt(super().__or__(other))
def __ror__(self, other):
return BinInt(super().__ror__(other))
def __xor__(self, other):
return BinInt(super().__xor__(other))
def __rxor__(self, other):
return BinInt(super().__rxor__(other))
def __lshift__(self, other):
return BinInt(super().__lshift__(other))
def __rshift__(self, other):
return BinInt(super().__rshift__(other))
def __neg__(self):
return BinInt(super().__neg__())
def __invert__(self):
return BinInt(super().__invert__())
def __abs__(self):
return BinInt(super().__abs__())
def __pos__(self):
return BinInt(super().__pos__())
def ceildiv(self, other):
"""Returns ceil(a / b)."""
return -(-self // other)
|
koriakin/binflakes | binflakes/types/int.py | BinInt.deposit | python | def deposit(self, pos, val):
if not isinstance(val, BinWord):
raise TypeError('deposit needs a BinWord')
pos = operator.index(pos)
if pos < 0:
raise ValueError('depositing out of range')
res = self
res &= ~(val.mask << pos)
res |= val.to_uint() << pos
return res | Returns a copy of this BinInt, with a given word deposited
at a given position (ie. with bits pos:pos+len(val) replaced
with bits from val). | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/int.py#L84-L97 | [
"def to_uint(self):\n \"\"\"Converts the word to a BinInt, treating it as an unsigned number.\"\"\"\n return self._val\n"
] | class BinInt(int):
"""A class representing an arbitrary-precision binary integer number.
This is just a python int with some extra methods.
Can be treated as an infinite sequence of individual bits (which are
represented as BinWords of width 1), with bit 0 being the LSB.
For non-negative numbers, all bits from a certain point are equal to 0.
For negative numbers, all bits from a certain point are equal to 1
(following two's complement convention).
"""
__slots__ = ()
@classmethod
def mask(cls, width):
"""Creates a new BinInt with low ``width`` bits set."""
return cls((1 << width) - 1)
def __getitem__(self, idx):
"""Extracts a given bit or a range of bits, with python indexing
semantics. Use ``extract`` to extract by position and width.
Since BinInt is, conceptually, an infinite sequence of bits,
it is an error to use negative indices. However, it is fine
to omit the stop index, returning an infinite subsequence
of bits -- a BigInt is returned in this case. For finite
sequences, a BinWord is returned.
"""
if not isinstance(idx, slice):
return self.extract(idx, 1)
step = 1 if idx.step is None else operator.index(idx.step)
if step == 0:
raise ValueError('step cannot be 0')
if step < 0 and idx.start is None:
raise ValueError('start cannot be None for reverse slicing')
start = 0 if idx.start is None else operator.index(idx.start)
stop = None if idx.stop is None else operator.index(idx.stop)
if start < 0:
raise ValueError(
'indexing from the end doesn\'t make sense for a BinInt')
if stop is not None and stop < 0:
raise ValueError(
'indexing from the end doesn\'t make sense for a BinInt')
if stop is None and step > 0:
if step == 1:
return self >> start
bits = self.bit_length()
r = range(start, bits, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self >> ipos & 1) << opos
if self < 0:
val |= -1 << len(r)
return BinInt(val)
else:
if stop is None:
stop = -1
if step == 1:
if stop <= start:
return BinWord(0, 0)
return self.extract(start, stop - start)
r = range(start, stop, step)
val = 0
for opos, ipos in enumerate(r):
val |= (self >> ipos & 1) << opos
return BinWord(len(r), val)
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given
bit position.
"""
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0:
raise ValueError('extracting out of range')
return BinWord(width, self >> pos, trunc=True)
def __repr__(self):
return f'BinInt({self})'
def __add__(self, other):
return BinInt(super().__add__(other))
def __radd__(self, other):
return BinInt(super().__radd__(other))
def __sub__(self, other):
return BinInt(super().__sub__(other))
def __rsub__(self, other):
return BinInt(super().__rsub__(other))
def __mul__(self, other):
return BinInt(super().__mul__(other))
def __rmul__(self, other):
return BinInt(super().__rmul__(other))
def __floordiv__(self, other):
return BinInt(super().__floordiv__(other))
def __rfloordiv__(self, other):
return BinInt(super().__rfloordiv__(other))
def __mod__(self, other):
return BinInt(super().__mod__(other))
def __rmod__(self, other):
return BinInt(super().__rmod__(other))
def __and__(self, other):
return BinInt(super().__and__(other))
def __rand__(self, other):
return BinInt(super().__rand__(other))
def __or__(self, other):
return BinInt(super().__or__(other))
def __ror__(self, other):
return BinInt(super().__ror__(other))
def __xor__(self, other):
return BinInt(super().__xor__(other))
def __rxor__(self, other):
return BinInt(super().__rxor__(other))
def __lshift__(self, other):
return BinInt(super().__lshift__(other))
def __rshift__(self, other):
return BinInt(super().__rshift__(other))
def __neg__(self):
return BinInt(super().__neg__())
def __invert__(self):
return BinInt(super().__invert__())
def __abs__(self):
return BinInt(super().__abs__())
def __pos__(self):
return BinInt(super().__pos__())
def ceildiv(self, other):
"""Returns ceil(a / b)."""
return -(-self // other)
|
koriakin/binflakes | binflakes/sexpr/nodes.py | _unwrap | python | def _unwrap(value, location=None):
if isinstance(value, Node) and location is not None:
raise TypeError(
'explicit location should only be given for bare values')
if isinstance(value, AtomNode):
return value.value, value.location
if isinstance(value, ListNode):
return value.items, value.location
if isinstance(value, FormNode):
return value.to_list(), value.location
if value is None or isinstance(value, (
bool, BinInt, BinWord, BinArray, str, Symbol, tuple)):
return value, location
if isinstance(value, list):
return tuple(value), location
if isinstance(value, int):
return BinInt(value), location
raise TypeError(
f'{type(value).__name__} is not representable by S-expressions.') | A helper function for Node subclass constructors -- if ``value``
is a Node instance, extracts raw Python value and location from it,
and returns them as a tuple. Otherwise, ensures that ``value`` is
of a type representable by S-expressions and returns it along with
explicitly-passed location, if any. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/nodes.py#L19-L43 | null | from enum import Enum
from attr import attrs, attrib, validate, fields, NOTHING
from attr.validators import optional, instance_of
from binflakes.types import BinInt, BinWord, BinArray
from .location import TextLocationRange
from .string import escape_string
from .symbol import Symbol
class ConvertError(Exception):
"""Raised by Node subclass constructors when given value cannot
be represented as an instance of a given class.
"""
pass
@attrs(slots=True, init=False)
class Node:
"""Represents a parsed S-expression node. Abstract base class.
There are four immediately derived classes:
- ``AtomNode``: represents atomic value nodes (everything except lists).
- ``ListNode``: represents lists of values of uniform type.
- ``FormNode``: represents forms -- compound nodes represented in
S-expression files by a list starting from a preset symbol and followed
by pre-defined arguments of possibly non-uniform types.
- ``AlternativesNode``: a pseudo-class representing an alternative of
several disjoint node types. Cannot be instantiated -- when constructor
is called, the value is matched to one of the contained node type
and an instance of the found type is returned instead.
This module provides a base class for every supported atom type, as well
as a generic list type and alternatives type. These classes can be
used to represent any S-expression and are returned by the reader.
To create an S-expression based language, one can create a hierarchy
of custom node subclasses and call the top node constructor on the generic
tree returned by the reader -- it will be resursively converted to the
custom node set.
"""
location = attrib(validator=optional(instance_of(TextLocationRange)),
cmp=False)
def __init__(self, value, location=None):
"""Converts a value to an instance of this class, recursively
converting subnodes as necessary. The input value can be another
compatible Node instance, or a bare Python value of the corresponding
type.
Can be used to convert a bare Python value to a node tree, a generic
node tree to a specific node tree, or a specific node tree back to
a generic node tree.
"""
raise NotImplementedError
@attrs(slots=True, init=False)
class AtomNode(Node):
"""Represents a parsed atomic S-expression node (i.e. anything but a list).
Abstract base class. Subclasses need to define ``value_type`` class
attribute. No new direct subclasses should be defined by the user
(all types need direct support from the base machinery), but the derived
types can be arbitrarily subclassed further for extra methods.
"""
value = attrib()
def __init__(self, value, location=None):
self.value, self.location = _unwrap(value, location)
validate(self)
@value.validator
def _value_validate(self, attribute, value):
if not isinstance(value, self.value_type):
raise ConvertError(
f'{self.location}: expected {self.value_type.__name__}')
@attrs(slots=True, init=False)
class SymbolNode(AtomNode):
"""Represents a symbol S-expression."""
value_type = Symbol
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class NilNode(AtomNode):
"""Represents a nil S-expression."""
value_type = type(None)
def __init__(self, value=None, location=None):
super().__init__(value, location)
def __str__(self):
return '@nil'
@attrs(slots=True, init=False)
class BoolNode(AtomNode):
"""Represents a bool S-expression."""
value_type = bool
def __str__(self):
return '@true' if self.value else '@false'
@attrs(slots=True, init=False)
class IntNode(AtomNode):
"""Represents an int S-expression."""
value_type = BinInt
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class WordNode(AtomNode):
"""Represents a word S-expression."""
value_type = BinWord
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class ArrayNode(AtomNode):
"""Represents an array S-expression."""
value_type = BinArray
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class StringNode(AtomNode):
"""Represents a string S-expression."""
value_type = str
def __str__(self):
return escape_string(self.value)
ATOM_TYPES = [
SymbolNode,
NilNode,
BoolNode,
IntNode,
WordNode,
ArrayNode,
StringNode,
]
@attrs(slots=True, init=False)
class ListNode(Node):
"""Represents a uniform list S-expression. Abstract base class --
should be subclassed with ``item_type`` class attribute set to the type of
list items.
"""
items = attrib(validator=instance_of(tuple))
def __init__(self, value, location=None):
items, self.location = _unwrap(value, location)
if not isinstance(items, tuple):
raise ConvertError(f'{self.location}: expected a list')
self.items = tuple(
self.item_type(item)
for item in items
)
validate(self)
def __str__(self):
items = ' '.join(str(x) for x in self.items)
return f'({items})'
class _FormArgMode(Enum):
REQUIRED = 'required'
OPTIONAL = 'optional'
REST = 'rest'
def form_node(cls):
"""A class decorator to finalize fully derived FormNode subclasses."""
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
if 'arg_mode' in field.metadata:
if state is _FormArgMode.REST:
raise RuntimeError('rest argument must be last')
if field.metadata['arg_mode'] is _FormArgMode.REQUIRED:
if state is _FormArgMode.OPTIONAL:
raise RuntimeError('required arg after optional arg')
res._args.append(field)
res._required_args += 1
elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL:
state = _FormArgMode.OPTIONAL
res._args.append(field)
elif field.metadata['arg_mode'] is _FormArgMode.REST:
state = _FormArgMode.REST
res._rest_arg = field
else:
assert 0
return res
def form_arg(arg_type):
"""Defines a required form argument of a given node type."""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.REQUIRED,
})
def form_optional_arg(arg_type):
"""Defines an optional form argument of a given node type.
If not passed, it is set to None. All optional arguments
must come after all required arguments.
"""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.OPTIONAL,
})
def form_rest_arg(arg_type):
"""Defines a ``rest`` form argument. All form arguments not consumed
by required and optional arguments will be converted to the given node
type and gathered into a tuple. There can be at most one rest argument
and it must be the last defined form argument.
"""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.REST,
})
@attrs(slots=True, init=False)
class FormNode(Node):
"""An abstract base class for form nodes. Final subclasses need to
set a ``symbol`` class attribute, define zero or more form arguments,
and call the ``@form_node`` decorator on the class.
"""
symbol_location = attrib(
validator=optional(instance_of(TextLocationRange)), cmp=False)
def __init__(self, value=NOTHING, location=None, symbol_location=None,
**kwargs):
"""Constructs a FormNode instance from a value and location (where
value is a list node, or a plain list), or directly from argument
values::
AbcNode([Symbol('abc'), 123, 'def'], TextLocationRange(...))
AbcNode(my_arg=123, my_other_arg='def', location=...)
"""
if not hasattr(self, 'symbol'):
raise RuntimeError('constructing abstract FormNode')
if value is not NOTHING:
if kwargs:
raise TypeError(
'cannot construct FormNode from both a value and kwargs')
value, self.location = _unwrap(value, location)
if not isinstance(value, tuple):
raise ConvertError(f'{self.location}: expected a list')
if not value:
raise ConvertError(f'{self.location}: empty form')
symbol, self.symbol_location = _unwrap(value[0], symbol_location)
if not isinstance(symbol, Symbol):
raise ConvertError(
f'{location}: form must start with a symbol')
if symbol != self.symbol:
raise ConvertError(
f'{location}: expected form ({self.symbol})')
if len(value) - 1 < self._required_args:
raise ConvertError(
f'{location}: too few arguments to form {self.symbol}')
for arg, val in zip(self._args, value[1:]):
kwargs[arg.name] = val
extra = value[len(self._args) + 1:]
if self._rest_arg is not None:
kwargs[self._rest_arg.name] = extra
elif extra:
raise ConvertError(
f'{self.location}: too many arguments '
f'to form {self.symbol}')
else:
self.location = location
self.symbol_location = symbol_location
was_missing = False
for field in fields(type(self)):
if 'arg_type' in field.metadata:
arg_mode = field.metadata['arg_mode']
arg_type = field.metadata['arg_type']
if field.name in kwargs:
value = kwargs.pop(field.name)
if arg_mode is _FormArgMode.REQUIRED:
value = arg_type(value)
elif arg_mode is _FormArgMode.OPTIONAL:
if value is not None:
value = arg_type(value)
elif arg_mode is _FormArgMode.REST:
value = tuple(
arg_type(x)
for x in value
)
else:
assert 0
elif arg_mode is _FormArgMode.REQUIRED:
raise TypeError(
f'{location}: no value for {field.name}')
elif arg_mode is _FormArgMode.OPTIONAL:
value = None
elif arg_mode is _FormArgMode.REST:
value = ()
else:
assert 0
if value is None:
was_missing = True
elif was_missing and value != ():
raise TypeError(
'passing argument after a missing argument')
elif field.name in ('location', 'symbol_location'):
# already set before
continue
else:
assert 0
setattr(self, field.name, value)
if kwargs:
arg = kwargs.popitem()[0]
raise TypeError(f'unknown field {arg}')
validate(self)
def to_list(self):
"""Converts a parsed form back to a tuple of S-expressions it was
made from.
"""
res = [SymbolNode(self.symbol, self.symbol_location)]
for arg in self._args:
val = getattr(self, arg.name)
if val is not None:
res.append(val)
if self._rest_arg is not None:
res += getattr(self, self._rest_arg.name)
return tuple(res)
def __str__(self):
items = ' '.join(str(x) for x in self.to_list())
return f'({items})'
class _AlternativesMeta(type):
"""A simple metaclass for AlternativesNode to make isinstance work.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if hasattr(self, 'alternatives'):
self.set_alternatives(self.alternatives)
def __instancecheck__(self, instance):
for alt in getattr(self, '_alternatives', []):
if isinstance(instance, alt):
return True
return False
class AlternativesNode(metaclass=_AlternativesMeta):
"""A base for making node pseudo-classes that, when "created", match
the passed value to one of a given list of node subclasses and call
the constructor of the matching one, if any.
If all involved node types are already defined on subclass creation,
the list of supported node types can be set through the ``alternatives``
class attribute::
class MyAlternativesNode(AlternativesNode):
alternatives = [
MyNode,
AnotherNode,
]
If one of the node types isn't yet defined when a subclass is constructed,
the node types can be set later through the ``set_alternatives`` class
method::
class MyAlternativesNode(AlternativesNode):
pass
class MyNode(...):
...
MyAlternativesNode.set_alternatives([
MyNode,
AnotherNode,
])
The alternatives specified must be mutually exclusive, as follows:
- There must be at most one alternative for each atom type.
- There must be at most one of the following:
- A ListNode subtype.
- Any number of FormNode subtypes, with distinct symbols.
- If any AlternativeNode subclass is specified in alternatives, it's
as if all alternatives of that class were specified directly in its
place.
"""
def __new__(cls, value, location=None):
if not hasattr(cls, '_alternatives'):
raise RuntimeError('AlternativesNode subclass not initialized')
value, location = _unwrap(value, location)
for atom_type in ATOM_TYPES:
if isinstance(value, atom_type.value_type):
if atom_type in cls._atom_types:
return cls._atom_types[atom_type](value, location)
else:
raise ConvertError(
f'{location}: {atom_type.__name__} not allowed')
assert isinstance(value, tuple)
if cls._list_type is not None:
return cls._list_type(value, location)
if not value:
raise ConvertError(f'{location}: empty form')
symbol, symbol_location = _unwrap(value[0])
if not isinstance(symbol, Symbol):
raise ConvertError(
f'{location}: form must start with a symbol')
if symbol not in cls._form_types:
available = ', '.join(str(sym) for sym in cls._form_types)
raise ConvertError(f'{location}: unknown form {symbol}'
f' (available forms: {available})')
return cls._form_types[symbol](value, location)
@classmethod
def set_alternatives(cls, alternatives):
if hasattr(cls, '_alternatives'):
raise RuntimeError('AlternativesNode subclass initialized twice')
cls._atom_types = {}
cls._list_type = None
cls._form_types = {}
cls._alternatives = []
for alt in alternatives:
if isinstance(alt, _AlternativesMeta):
cls._alternatives += alt._alternatives
else:
cls._alternatives.append(alt)
for alt in cls._alternatives:
for atom_type in ATOM_TYPES:
if issubclass(alt, atom_type):
if atom_type in cls._atom_types:
raise RuntimeError(
f'Two alternatives for {atom_type.__name__}')
cls._atom_types[atom_type] = alt
break
else:
if issubclass(alt, ListNode):
if cls._list_type is not None:
raise RuntimeError('Two alternatives for list')
cls._list_type = alt
elif issubclass(alt, FormNode):
if alt.symbol in cls._form_types:
raise RuntimeError(
f'Two alternatives for form {alt.symbol}')
cls._form_types[alt.symbol] = alt
else:
raise RuntimeError(f'unknown alternative type {alt}')
if cls._list_type and cls._form_types:
raise RuntimeError('cannot have both FormNodes and a ListNode')
class GenericNode(AlternativesNode):
"""A node pseudo-type representing any of the generic node types."""
pass
@attrs(slots=True, init=False)
class GenericListNode(ListNode):
"""Represents a generic list S-expression -- items can be of any
generic node type.
"""
item_type = GenericNode
GenericNode.set_alternatives([
GenericListNode,
SymbolNode,
NilNode,
BoolNode,
IntNode,
WordNode,
ArrayNode,
StringNode,
])
|
koriakin/binflakes | binflakes/sexpr/nodes.py | form_node | python | def form_node(cls):
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
if 'arg_mode' in field.metadata:
if state is _FormArgMode.REST:
raise RuntimeError('rest argument must be last')
if field.metadata['arg_mode'] is _FormArgMode.REQUIRED:
if state is _FormArgMode.OPTIONAL:
raise RuntimeError('required arg after optional arg')
res._args.append(field)
res._required_args += 1
elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL:
state = _FormArgMode.OPTIONAL
res._args.append(field)
elif field.metadata['arg_mode'] is _FormArgMode.REST:
state = _FormArgMode.REST
res._rest_arg = field
else:
assert 0
return res | A class decorator to finalize fully derived FormNode subclasses. | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/nodes.py#L222-L247 | null | from enum import Enum
from attr import attrs, attrib, validate, fields, NOTHING
from attr.validators import optional, instance_of
from binflakes.types import BinInt, BinWord, BinArray
from .location import TextLocationRange
from .string import escape_string
from .symbol import Symbol
class ConvertError(Exception):
"""Raised by Node subclass constructors when given value cannot
be represented as an instance of a given class.
"""
pass
def _unwrap(value, location=None):
"""A helper function for Node subclass constructors -- if ``value``
is a Node instance, extracts raw Python value and location from it,
and returns them as a tuple. Otherwise, ensures that ``value`` is
of a type representable by S-expressions and returns it along with
explicitly-passed location, if any.
"""
if isinstance(value, Node) and location is not None:
raise TypeError(
'explicit location should only be given for bare values')
if isinstance(value, AtomNode):
return value.value, value.location
if isinstance(value, ListNode):
return value.items, value.location
if isinstance(value, FormNode):
return value.to_list(), value.location
if value is None or isinstance(value, (
bool, BinInt, BinWord, BinArray, str, Symbol, tuple)):
return value, location
if isinstance(value, list):
return tuple(value), location
if isinstance(value, int):
return BinInt(value), location
raise TypeError(
f'{type(value).__name__} is not representable by S-expressions.')
@attrs(slots=True, init=False)
class Node:
"""Represents a parsed S-expression node. Abstract base class.
There are four immediately derived classes:
- ``AtomNode``: represents atomic value nodes (everything except lists).
- ``ListNode``: represents lists of values of uniform type.
- ``FormNode``: represents forms -- compound nodes represented in
S-expression files by a list starting from a preset symbol and followed
by pre-defined arguments of possibly non-uniform types.
- ``AlternativesNode``: a pseudo-class representing an alternative of
several disjoint node types. Cannot be instantiated -- when constructor
is called, the value is matched to one of the contained node type
and an instance of the found type is returned instead.
This module provides a base class for every supported atom type, as well
as a generic list type and alternatives type. These classes can be
used to represent any S-expression and are returned by the reader.
To create an S-expression based language, one can create a hierarchy
of custom node subclasses and call the top node constructor on the generic
tree returned by the reader -- it will be resursively converted to the
custom node set.
"""
location = attrib(validator=optional(instance_of(TextLocationRange)),
cmp=False)
def __init__(self, value, location=None):
"""Converts a value to an instance of this class, recursively
converting subnodes as necessary. The input value can be another
compatible Node instance, or a bare Python value of the corresponding
type.
Can be used to convert a bare Python value to a node tree, a generic
node tree to a specific node tree, or a specific node tree back to
a generic node tree.
"""
raise NotImplementedError
@attrs(slots=True, init=False)
class AtomNode(Node):
"""Represents a parsed atomic S-expression node (i.e. anything but a list).
Abstract base class. Subclasses need to define ``value_type`` class
attribute. No new direct subclasses should be defined by the user
(all types need direct support from the base machinery), but the derived
types can be arbitrarily subclassed further for extra methods.
"""
value = attrib()
def __init__(self, value, location=None):
self.value, self.location = _unwrap(value, location)
validate(self)
@value.validator
def _value_validate(self, attribute, value):
if not isinstance(value, self.value_type):
raise ConvertError(
f'{self.location}: expected {self.value_type.__name__}')
@attrs(slots=True, init=False)
class SymbolNode(AtomNode):
"""Represents a symbol S-expression."""
value_type = Symbol
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class NilNode(AtomNode):
"""Represents a nil S-expression."""
value_type = type(None)
def __init__(self, value=None, location=None):
super().__init__(value, location)
def __str__(self):
return '@nil'
@attrs(slots=True, init=False)
class BoolNode(AtomNode):
"""Represents a bool S-expression."""
value_type = bool
def __str__(self):
return '@true' if self.value else '@false'
@attrs(slots=True, init=False)
class IntNode(AtomNode):
"""Represents an int S-expression."""
value_type = BinInt
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class WordNode(AtomNode):
"""Represents a word S-expression."""
value_type = BinWord
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class ArrayNode(AtomNode):
"""Represents an array S-expression."""
value_type = BinArray
def __str__(self):
return str(self.value)
@attrs(slots=True, init=False)
class StringNode(AtomNode):
"""Represents a string S-expression."""
value_type = str
def __str__(self):
return escape_string(self.value)
ATOM_TYPES = [
SymbolNode,
NilNode,
BoolNode,
IntNode,
WordNode,
ArrayNode,
StringNode,
]
@attrs(slots=True, init=False)
class ListNode(Node):
"""Represents a uniform list S-expression. Abstract base class --
should be subclassed with ``item_type`` class attribute set to the type of
list items.
"""
items = attrib(validator=instance_of(tuple))
def __init__(self, value, location=None):
items, self.location = _unwrap(value, location)
if not isinstance(items, tuple):
raise ConvertError(f'{self.location}: expected a list')
self.items = tuple(
self.item_type(item)
for item in items
)
validate(self)
def __str__(self):
items = ' '.join(str(x) for x in self.items)
return f'({items})'
class _FormArgMode(Enum):
REQUIRED = 'required'
OPTIONAL = 'optional'
REST = 'rest'
def form_arg(arg_type):
"""Defines a required form argument of a given node type."""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.REQUIRED,
})
def form_optional_arg(arg_type):
"""Defines an optional form argument of a given node type.
If not passed, it is set to None. All optional arguments
must come after all required arguments.
"""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.OPTIONAL,
})
def form_rest_arg(arg_type):
"""Defines a ``rest`` form argument. All form arguments not consumed
by required and optional arguments will be converted to the given node
type and gathered into a tuple. There can be at most one rest argument
and it must be the last defined form argument.
"""
return attrib(metadata={
'arg_type': arg_type,
'arg_mode': _FormArgMode.REST,
})
@attrs(slots=True, init=False)
class FormNode(Node):
"""An abstract base class for form nodes. Final subclasses need to
set a ``symbol`` class attribute, define zero or more form arguments,
and call the ``@form_node`` decorator on the class.
"""
symbol_location = attrib(
validator=optional(instance_of(TextLocationRange)), cmp=False)
def __init__(self, value=NOTHING, location=None, symbol_location=None,
**kwargs):
"""Constructs a FormNode instance from a value and location (where
value is a list node, or a plain list), or directly from argument
values::
AbcNode([Symbol('abc'), 123, 'def'], TextLocationRange(...))
AbcNode(my_arg=123, my_other_arg='def', location=...)
"""
if not hasattr(self, 'symbol'):
raise RuntimeError('constructing abstract FormNode')
if value is not NOTHING:
if kwargs:
raise TypeError(
'cannot construct FormNode from both a value and kwargs')
value, self.location = _unwrap(value, location)
if not isinstance(value, tuple):
raise ConvertError(f'{self.location}: expected a list')
if not value:
raise ConvertError(f'{self.location}: empty form')
symbol, self.symbol_location = _unwrap(value[0], symbol_location)
if not isinstance(symbol, Symbol):
raise ConvertError(
f'{location}: form must start with a symbol')
if symbol != self.symbol:
raise ConvertError(
f'{location}: expected form ({self.symbol})')
if len(value) - 1 < self._required_args:
raise ConvertError(
f'{location}: too few arguments to form {self.symbol}')
for arg, val in zip(self._args, value[1:]):
kwargs[arg.name] = val
extra = value[len(self._args) + 1:]
if self._rest_arg is not None:
kwargs[self._rest_arg.name] = extra
elif extra:
raise ConvertError(
f'{self.location}: too many arguments '
f'to form {self.symbol}')
else:
self.location = location
self.symbol_location = symbol_location
was_missing = False
for field in fields(type(self)):
if 'arg_type' in field.metadata:
arg_mode = field.metadata['arg_mode']
arg_type = field.metadata['arg_type']
if field.name in kwargs:
value = kwargs.pop(field.name)
if arg_mode is _FormArgMode.REQUIRED:
value = arg_type(value)
elif arg_mode is _FormArgMode.OPTIONAL:
if value is not None:
value = arg_type(value)
elif arg_mode is _FormArgMode.REST:
value = tuple(
arg_type(x)
for x in value
)
else:
assert 0
elif arg_mode is _FormArgMode.REQUIRED:
raise TypeError(
f'{location}: no value for {field.name}')
elif arg_mode is _FormArgMode.OPTIONAL:
value = None
elif arg_mode is _FormArgMode.REST:
value = ()
else:
assert 0
if value is None:
was_missing = True
elif was_missing and value != ():
raise TypeError(
'passing argument after a missing argument')
elif field.name in ('location', 'symbol_location'):
# already set before
continue
else:
assert 0
setattr(self, field.name, value)
if kwargs:
arg = kwargs.popitem()[0]
raise TypeError(f'unknown field {arg}')
validate(self)
def to_list(self):
"""Converts a parsed form back to a tuple of S-expressions it was
made from.
"""
res = [SymbolNode(self.symbol, self.symbol_location)]
for arg in self._args:
val = getattr(self, arg.name)
if val is not None:
res.append(val)
if self._rest_arg is not None:
res += getattr(self, self._rest_arg.name)
return tuple(res)
def __str__(self):
items = ' '.join(str(x) for x in self.to_list())
return f'({items})'
class _AlternativesMeta(type):
"""A simple metaclass for AlternativesNode to make isinstance work.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if hasattr(self, 'alternatives'):
self.set_alternatives(self.alternatives)
def __instancecheck__(self, instance):
for alt in getattr(self, '_alternatives', []):
if isinstance(instance, alt):
return True
return False
class AlternativesNode(metaclass=_AlternativesMeta):
"""A base for making node pseudo-classes that, when "created", match
the passed value to one of a given list of node subclasses and call
the constructor of the matching one, if any.
If all involved node types are already defined on subclass creation,
the list of supported node types can be set through the ``alternatives``
class attribute::
class MyAlternativesNode(AlternativesNode):
alternatives = [
MyNode,
AnotherNode,
]
If one of the node types isn't yet defined when a subclass is constructed,
the node types can be set later through the ``set_alternatives`` class
method::
class MyAlternativesNode(AlternativesNode):
pass
class MyNode(...):
...
MyAlternativesNode.set_alternatives([
MyNode,
AnotherNode,
])
The alternatives specified must be mutually exclusive, as follows:
- There must be at most one alternative for each atom type.
- There must be at most one of the following:
- A ListNode subtype.
- Any number of FormNode subtypes, with distinct symbols.
- If any AlternativeNode subclass is specified in alternatives, it's
as if all alternatives of that class were specified directly in its
place.
"""
def __new__(cls, value, location=None):
if not hasattr(cls, '_alternatives'):
raise RuntimeError('AlternativesNode subclass not initialized')
value, location = _unwrap(value, location)
for atom_type in ATOM_TYPES:
if isinstance(value, atom_type.value_type):
if atom_type in cls._atom_types:
return cls._atom_types[atom_type](value, location)
else:
raise ConvertError(
f'{location}: {atom_type.__name__} not allowed')
assert isinstance(value, tuple)
if cls._list_type is not None:
return cls._list_type(value, location)
if not value:
raise ConvertError(f'{location}: empty form')
symbol, symbol_location = _unwrap(value[0])
if not isinstance(symbol, Symbol):
raise ConvertError(
f'{location}: form must start with a symbol')
if symbol not in cls._form_types:
available = ', '.join(str(sym) for sym in cls._form_types)
raise ConvertError(f'{location}: unknown form {symbol}'
f' (available forms: {available})')
return cls._form_types[symbol](value, location)
@classmethod
def set_alternatives(cls, alternatives):
if hasattr(cls, '_alternatives'):
raise RuntimeError('AlternativesNode subclass initialized twice')
cls._atom_types = {}
cls._list_type = None
cls._form_types = {}
cls._alternatives = []
for alt in alternatives:
if isinstance(alt, _AlternativesMeta):
cls._alternatives += alt._alternatives
else:
cls._alternatives.append(alt)
for alt in cls._alternatives:
for atom_type in ATOM_TYPES:
if issubclass(alt, atom_type):
if atom_type in cls._atom_types:
raise RuntimeError(
f'Two alternatives for {atom_type.__name__}')
cls._atom_types[atom_type] = alt
break
else:
if issubclass(alt, ListNode):
if cls._list_type is not None:
raise RuntimeError('Two alternatives for list')
cls._list_type = alt
elif issubclass(alt, FormNode):
if alt.symbol in cls._form_types:
raise RuntimeError(
f'Two alternatives for form {alt.symbol}')
cls._form_types[alt.symbol] = alt
else:
raise RuntimeError(f'unknown alternative type {alt}')
if cls._list_type and cls._form_types:
raise RuntimeError('cannot have both FormNodes and a ListNode')
class GenericNode(AlternativesNode):
"""A node pseudo-type representing any of the generic node types."""
pass
@attrs(slots=True, init=False)
class GenericListNode(ListNode):
"""Represents a generic list S-expression -- items can be of any
generic node type.
"""
item_type = GenericNode
GenericNode.set_alternatives([
GenericListNode,
SymbolNode,
NilNode,
BoolNode,
IntNode,
WordNode,
ArrayNode,
StringNode,
])
|
Celeo/Pycord | pycord/__init__.py | WebSocketEvent.parse | python | def parse(cls, op):
for event in cls:
if event.value == int(op):
return event
return None | Gets the enum for the op code
Args:
op: value of the op code (will be casted to int)
Returns:
The enum that matches the op code | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L45-L57 | null | class WebSocketEvent(enum.Enum):
"""Enum for the different websocket events
Attributes:
name: name of the event
value: int value of the event
"""
DISPATCH = 0
HEARTBEAT = 1
IDENTIFY = 2
STATUS_UPDATE = 3
VOICE_STATE_UPDATE = 4
VOICE_SERVER_PING = 5
RESUME = 6
RECONNECT = 7
REQUEST_GUILD_MEMBERS = 8
INVALID_SESSION = 9
HELLO = 10
HEARTBEAT_ACK = 11
@classmethod
|
Celeo/Pycord | pycord/__init__.py | WebSocketKeepAlive.run | python | def run(self):
while self.should_run:
try:
self.logger.debug('Sending heartbeat, seq ' + last_sequence)
self.ws.send(json.dumps({
'op': 1,
'd': last_sequence
}))
except Exception as e:
self.logger.error(f'Got error in heartbeat: {str(e)}')
finally:
elapsed = 0.0
while elapsed < self.interval and self.should_run:
time.sleep(self.TICK_INTERVAL)
elapsed += self.TICK_INTERVAL | Runs the thread
This method handles sending the heartbeat to the Discord websocket server, so the connection
can remain open and the bot remain online for those commands that require it to be.
Args:
None | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L87-L109 | null | class WebSocketKeepAlive(threading.Thread):
"""Keep alive thread for sending websocket heartbeats
Attributes:
logger: a copy of the Pycord object's logger
ws: a copy of the Pycord object's websocket connection
interval: the set heartbeat interval
"""
TICK_INTERVAL = 0.25
def __init__(self, logger: logging.Logger, ws: websocket.WebSocketApp, interval: float) -> None:
super().__init__(name='Thread-ws_keep_alive')
self.logger = logger
self.ws = ws
self.interval = interval
self.should_run = True
def stop(self):
self.should_run = False
|
Celeo/Pycord | pycord/__init__.py | Pycord._setup_logger | python | def _setup_logger(self, logging_level: int, log_to_console: bool):
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler) | Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L181-L200 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord._query | python | def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None | Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L221-L252 | [
"def _build_headers(self) -> Dict[str, str]:\n \"\"\"Creates the headers required for HTTP requests\n\n Args:\n None\n\n Returns:\n Dictionary of header keys and values\n \"\"\"\n return {\n 'Authorization': f'Bot {self.token}',\n 'User-Agent': self.user_agent,\n 'C... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord._ws_on_message | python | def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data) | Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L269-L317 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord._ws_on_error | python | def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
self.logger.error(f'Got error from websocket connection: {str(error)}') | Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L319-L326 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord._ws_on_close | python | def _ws_on_close(self, ws: websocket.WebSocketApp):
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket() | Callback for closing the websocket connection
Args:
ws: websocket connection (now closed) | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L328-L336 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord._ws_on_open | python | def _ws_on_open(self, ws: websocket.WebSocketApp):
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True | Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L338-L364 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.connect_to_websocket | python | def connect_to_websocket(self):
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start() | Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L374-L399 | [
"def _get_websocket_address(self) -> str:\n \"\"\"Queries the Discord REST API for the websocket URL\n\n Args:\n None\n\n Returns:\n The URL of websocket connection\n \"\"\"\n return self._query('gateway', 'GET')['url']\n"
] | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.disconnect_from_websocket | python | def disconnect_from_websocket(self):
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection') | Disconnects from the websocket
Args:
None | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L424-L440 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.set_status | python | def set_status(self, name: str = None):
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data) | Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L442-L469 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_info | python | def get_guild_info(self, id: str) -> Dict[str, Any]:
return self._query(f'guilds/{id}', 'GET') | Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
} | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L549-L577 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_channels_in | python | def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
return self._query(f'guilds/{guild_id}/channels', 'GET') | Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L579-L628 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_channel_info | python | def get_channel_info(self, id: str) -> Dict[str, Any]:
return self._query(f'channels/{id}', 'GET') | Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
} | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L630-L651 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_members | python | def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
return self._query(f'guilds/{guild_id}/members', 'GET') | Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L653-L700 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_member_by_id | python | def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET') | Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
} | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L702-L735 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.get_all_guild_roles | python | def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
return self._query(f'guilds/{guild_id}/roles', 'GET') | Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L737-L780 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.set_member_roles | python | def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204) | Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L782-L799 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.add_member_roles | python | def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list) | Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L801-L821 | [
"def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:\n \"\"\"Get a guild member by their id\n\n Args:\n guild_id: snowflake id of the guild\n member_id: snowflake id of the member\n\n Returns:\n Dictionary data for the guild member.\n\n Example:\n ... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.remove_member_roles | python | def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list) | Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L823-L843 | [
"def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:\n \"\"\"Get a guild member by their id\n\n Args:\n guild_id: snowflake id of the guild\n member_id: snowflake id of the member\n\n Returns:\n Dictionary data for the guild member.\n\n Example:\n ... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.send_message | python | def send_message(self, id: str, message: str) -> Dict[str, Any]:
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message}) | Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L845-L860 | [
"def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \\\n -> Union[List[Dict[str, Any]], Dict[str, Any], None]:\n \"\"\"Make an HTTP request\n\n Args:\n path: the URI path (not including the base url, start with\n the first uri segment, like... | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.command | python | def command(self, name: str) -> Callable:
def inner(f: Callable):
self._commands.append((name, f))
return inner | Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L865-L915 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing
"""
self._commands.append((name, f))
|
Celeo/Pycord | pycord/__init__.py | Pycord.register_command | python | def register_command(self, name: str, f: Callable):
self._commands.append((name, f)) | Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to define methods in another file or wherever, import them,
and register them.
See the documentation for the ``@command`` decorator for more information
on what you method will receive.
Example:
def process_hello(data):
# do stuff
# later, somewhere else, etc.
pycord.register_command('hello', process_hello)
Args:
name: the command to trigger the callback (see ``@command`` documentation)
f: callable that will be triggered on command processing | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L917-L942 | null | class Pycord:
"""Main library class; handles connecting and accessing the Discord APIs
Attributes:
token: the user-supplied token used for authentication
user_agent: the user-supplied or defaulted HTTP user agent
connected: a bool value if the websocket connection is open
"""
url_base = 'https://discordapp.com/api/v6/'
def __init__(self, token: str, user_agent: str=None, logging_level: int=logging.DEBUG,
log_to_console: bool=True, command_prefix: str='!') -> None:
"""Class init method
Only sets up the class, does not start the websocket connection. For that, you'll need to
call ``connect_to_websocket`` on the resulting object.
Args:
token: the bot authentication token
user_agent: your selected user agent for HTTP requests see
https://discordapp.com/developers/docs/reference for more information
logging_level: the desired logging level for the internal logger
log_to_console: whether or not to log to the console as well as the file
command_prefix: the prefix to use when parsing commands (default is '!')
Attributes:
callbacks: a dictionary of callbacks to register. Keys should be ``PycordCallback``
enums, and values are a callable object that takes a single callabke parameter,
like command callback registrations. These callables will be called when the
corresponding event is sent to the server. Example:
cord.callbacks = {
PycordCallback.USER_FIRST_TIME_JOIN = my_method_name
}
"""
self.token = token
self.user_agent = user_agent or f'Pycord (github.com/Celeo/Pycord, {__version__})'
self._setup_logger(logging_level, log_to_console)
self.connected = False
self.command_prefix = command_prefix
self._commands = []
self.callbacks = {}
# =================================================
# Private methods
# =================================================
def _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger
Args:
logging_level: what logging level to use
log_to_console: whether or not to log to the console
"""
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging_level)
self.logger.addHandler(file_handler)
if log_to_console:
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)
self.logger.addHandler(stream_handler)
# =====================
# REST API
# =====================
def _build_headers(self) -> Dict[str, str]:
"""Creates the headers required for HTTP requests
Args:
None
Returns:
Dictionary of header keys and values
"""
return {
'Authorization': f'Bot {self.token}',
'User-Agent': self.user_agent,
'Content-Type': 'application/json'
}
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
-> Union[List[Dict[str, Any]], Dict[str, Any], None]:
"""Make an HTTP request
Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception
Returns:
Data from the endpoint's response
"""
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
r = requests.get(url, headers=self._build_headers())
elif method == 'PATCH':
r = requests.patch(url, headers=self._build_headers(), json=data)
else:
raise ValueError(f'Unknown HTTP method {method}')
self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
if r.status_code != expected_status:
raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
if expected_status == 200:
return r.json()
return None
def _get_websocket_address(self) -> str:
"""Queries the Discord REST API for the websocket URL
Args:
None
Returns:
The URL of websocket connection
"""
return self._query('gateway', 'GET')['url']
# =====================
# Websocket API
# =====================
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for maintaining
the connection, some of which are for notifying this client of user states, etc.
Only a few of the events are really worth listening to by "downstream" clients,
mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'),
and those can be accessed by clients using this library via the command registration,
which is handled by this method.
Args:
ws: websocket connection
raw: message received from the connection; either string or bytes, the latter
is a zlip-compressed string. Either way, the end result of formatting is JSON
"""
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logger.debug('Set last_sequence to ' + last_sequence)
event = WebSocketEvent.parse(data['op'])
self.logger.debug('Received event {} (op #{})'.format(
event.name,
data['op']
))
if event == WebSocketEvent.HELLO:
interval = float(data['d']['heartbeat_interval']) / 1000
self.logger.debug(f'Starting heartbeat thread at {interval} seconds')
self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval)
self._ws_keep_alive.start()
elif event == WebSocketEvent.DISPATCH:
self.logger.debug('Got dispatch ' + data['t'])
if data['t'] == PycordCallback.MESSAGE.value:
message_content = data['d']['content']
if message_content.startswith(self.command_prefix) and self._commands:
cmd_str = message_content[1:].split(' ')[0].lower()
self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"')
for command_obj in self._commands:
if command_obj[0].lower() == cmd_str:
self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback')
command_obj[1](data)
for key in self.callbacks:
if key.value == data['t']:
self.callbacks[key](data)
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
"""
self.logger.error(f'Got error from websocket connection: {str(error)}')
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket()
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
"""
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
'$referring_domain': ''
},
'compress': True,
'large_threshold': 250
}
}
self.logger.debug('Sending identify payload')
ws.send(json.dumps(payload))
self.connected = True
# =================================================
# Public methods
# =================================================
# =====================
# Websocket API
# =====================
def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block until your application is interrupted.
Args:
None
"""
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_address() + '?v=6&encoding=json',
on_message=self._ws_on_message,
on_error=self._ws_on_error,
on_close=self._ws_on_close
)
self._ws.on_open = self._ws_on_open
self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws)
self._ws_run_forever_wrapper.start()
def keep_running(self):
"""Call this method to block on the maintenance of the websocket connection.
Unless you interrupt this method, it will block continuously, as the websocket
connection is simply maintained with keep alives. This method should be called
at the end of your bot setup, as registered commands will be heard by the client
from Discord users and processed here.
Args:
None
"""
self._ws_run_forever_wrapper.join()
def _reconnect_websocket(self):
"""Reconnects to the Discord Gateway websocket
Args:
None
"""
self.logger.info('Running websocket reconnection proceedure')
self.disconnect_from_websocket()
self.connect_to_websocket()
def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
self._ws.close()
self.logger.info('Closed websocket connection')
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: the game's name, or None
"""
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.0
}
}
data = json.dumps(payload, indent=2)
self.logger.debug(f'Sending status update payload: {data}')
self._ws.send(data)
# =====================
# REST API
# =====================
def get_basic_bot_info(self) -> Dict[str, Any]:
"""Gets bot info (REST query)
Args:
None
Returns:
Dictionary of information about the bot. You're responsible for accessing
which attribute(s) you want.
Example:
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
"""
return self._query('users/@me', 'GET')
def get_connected_guilds(self) -> Dict[str, Any]:
"""Get connected guilds (REST query)
As your bot is added to guilds, it will need to know what's it's
connected to. Call this method to get a list of Guild objects.
Args:
None
Returns:
List of dictionary objects of guilds your bot is connected to.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query('users/@me/guilds', 'GET')
def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{id}', 'GET')
def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/docs/resources/channel#channel-object
Example:
[
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
},
{
"id": "155101607195836416",
"guild_id": "41771983423143937",
"name": "ROCKET CHEESE",
"type": 2,
"position": 5,
"permission_overwrites": [],
"bitrate": 64000,
"user_limit": 0
},
{
"last_message_id": "3343820033257021450",
"type": 1,
"id": "319674150115610528",
"recipients": [
{
"username": "test",
"discriminator": "9999",
"id": "82198898841029460",
"avatar": "33ecab261d4681afa4d85a04691c4a01"
}
]
}
]
"""
return self._query(f'guilds/{guild_id}/channels', 'GET')
def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
"name": "general",
"type": 0,
"position": 6,
"permission_overwrites": [],
"topic": "24/7 chat about how to gank Mike #2",
"last_message_id": "155117677105512449"
}
"""
return self._query(f'channels/{id}', 'GET')
def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
},
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
]
"""
return self._query(f'guilds/{guild_id}/members', 'GET')
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_id": "42072017402331136",
"afk_timeout": 300,
"embed_enabled": true,
"embed_channel_id": "41771983444115456",
"verification_level": 1,
"roles": [
"41771983423143936",
"41771983423143937",
"41771983423143938"
],
"emojis": [],
"features": ["INVITE_SPLASH"],
"unavailable": false
}
"""
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
"name": "WE DEM BOYZZ!!!!!!",
"color": 3447003,
"hoist": true,
"position": 1,
"permissions": 66321471,
"managed": false,
"mentionable": false
},
{
"hoist": false,
"name": "Admin",
"mentionable": false,
"color": 15158332,
"position": 2,
"id": "151107620239966208",
"managed": false,
"permissions": 66583679
},
{
"hoist": false,
"name": "@everyone",
"mentionable": false,
"color": 0,
"position": 0,
"id": "151106790233210882",
"managed": false,
"permissions": 37215297
}
]
"""
return self._query(f'guilds/{guild_id}/roles', 'GET')
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
for this user is complete, not just the roles that you want to add or remove.
For assistance in just adding or just removing roles, set the ``add_member_roles``
and ``remove_member_roles`` methods.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to set
"""
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contain duplicates, so you don't have
to filter role ids to this method (as long as they're still roles for this guild).
This method differs from ``set_member_roles`` in that this method ADDS roles
to the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to add
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
roles.extend(current_roles)
new_list = list(set(roles))
self.set_member_roles(guild_id, member_id, new_list)
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from the user that they have at the time of execution,
so you don't need to check that the user has the roles you're trying to remove
from them (as long as those roles are valid roles for this guild).
This method differs from ``set_member_roles`` in that this method REMOVES roles
from the user's current role list. ``set_member_roles`` is used by this method.
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
roles: list of snowflake ids of roles to remove
"""
current_roles = [role for role in self.get_guild_member_by_id(guild_id, member_id)['roles']]
new_list = [role for role in current_roles if role not in roles]
self.set_member_roles(guild_id, member_id, new_list)
def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the new message
"""
if not self.connected:
raise ValueError('Websocket not connected')
return self._query(f'channels/{id}/messages', 'POST', {'content': message})
# =====================
# Client command API
# =====================
def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.command('hello')
def command_hello(data):
# do stuff here
The ``data`` argument that your method will receive is the message object.
Example:
{
"t": "MESSAGE_CREATE",
"s": 4,
"op": 0,
"d": {
"type": 0,
"tts": false,
"timestamp": "2017-07-22T04:46:41.366000+00:00",
"pinned": false,
"nonce": "338180052904574976",
"mentions": [],
"mention_roles": [],
"mention_everyone": false,
"id": "338180026363150336",
"embeds": [],
"edited_timestamp": null,
"content": "!source",
"channel_id": "151106790233210882",
"author": {
"username": "Celeo",
"id": "110245175636312064",
"discriminator": "1453",
"avatar": "3118c26ea7e40350212196e1d9d7f5c9"
},
"attachments": []
}
}
Args:
name: command name
Returns:
Method decorator
"""
def inner(f: Callable):
self._commands.append((name, f))
return inner
|
elifesciences/elife-article | elifearticle/parse.py | build_contributors | python | def build_contributors(authors, contrib_type, competing_interests=None):
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors | Given a list of authors from the parser, instantiate contributors
objects and build them | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L16-L75 | [
"def set_attr_if_value(obj, attr_name, value):\n \"shorthand method to set object values if the value is not none\"\n if value is not None:\n setattr(obj, attr_name, value)\n",
"def text_from_affiliation_elements(department, institution, city, country):\n \"format an author affiliation from detail... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_funding | python | def build_funding(award_groups):
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards | Given a funding data, format it | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L78-L102 | null | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_datasets | python | def build_datasets(datasets_json):
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets | Given datasets in JSON format, build and return a list of dataset objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L105-L147 | [
"def set_attr_if_value(obj, attr_name, value):\n \"shorthand method to set object values if the value is not none\"\n if value is not None:\n setattr(obj, attr_name, value)\n",
"def author_name_from_json(author_json):\n \"concatenate an author name from json data\"\n author_name = None\n if ... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_data_availability | python | def build_data_availability(datasets_json):
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability | Given datasets in JSON format, get the data availability from it if present | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L150-L158 | null | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_ref_list | python | def build_ref_list(refs):
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list | Given parsed references build a list of ref objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L161-L252 | [
"def set_attr_if_value(obj, attr_name, value):\n \"shorthand method to set object values if the value is not none\"\n if value is not None:\n setattr(obj, attr_name, value)\n",
"def is_year_numeric(value):\n \"True if value is all digits\"\n if value and re.match(\"^[0-9]+$\", value):\n ... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | component_title | python | def component_title(component):
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title | Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc. | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L255-L280 | [
"def unicode_value(value):\n try:\n return unicode(value)\n except NameError: # pragma: no cover\n return str(value)\n"
] | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_components | python | def build_components(components):
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list | Given parsed components build a list of component objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L283-L332 | [
"def component_title(component):\n \"\"\"\n Label, title and caption\n Title is the label text plus the title text\n Title may contain italic tag, etc.\n \"\"\"\n\n title = u''\n\n label_text = u''\n title_text = u''\n if component.get('label'):\n label_text = component.get('label'... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_related_articles | python | def build_related_articles(related_articles):
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list | Given parsed data build a list of related article objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L335-L353 | null | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_pub_dates | python | def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance) | convert pub_dates into ArticleDate objects and add them to article | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L356-L373 | [
"def set_attr_if_value(obj, attr_name, value):\n \"shorthand method to set object values if the value is not none\"\n if value is not None:\n setattr(obj, attr_name, value)\n"
] | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_self_uri_list | python | def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list | parse the self-uri tags, build Uri objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L376-L384 | [
"def set_attr_if_value(obj, attr_name, value):\n \"shorthand method to set object values if the value is not none\"\n if value is not None:\n setattr(obj, attr_name, value)\n"
] | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | clean_abstract | python | def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract | Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L387-L395 | [
"def remove_tag(tag_name, string):\n \"\"\"\n Remove open and close tags - the tags themselves only - using\n a non-greedy angle bracket pattern match\n \"\"\"\n if not string:\n return string\n pattern = re.compile('</?' + tag_name + '.*?>')\n string = pattern.sub('', string)\n retur... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_article_from_xml | python | def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count | Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L408-L568 | [
"def build_contributors(authors, contrib_type, competing_interests=None):\n \"\"\"\n Given a list of authors from the parser, instantiate contributors\n objects and build them\n \"\"\"\n\n contributors = []\n\n for author in authors:\n contributor = None\n author_contrib_type = contr... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles
|
elifesciences/elife-article | elifearticle/parse.py | build_articles_from_article_xmls | python | def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles | Given a list of article XML filenames, convert to article objects | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L571-L586 | [
"def build_article_from_xml(article_xml_filename, detail=\"brief\",\n build_parts=None, remove_tags=None):\n \"\"\"\n Parse JATS XML with elifetools parser, and populate an\n eLifePOA article object\n Basic data crossref needs: article_id, doi, title, contributors with names se... | """
Build article objects by parsing article XML
"""
from __future__ import print_function
from collections import OrderedDict
from six import iteritems
from elifetools import parseJATS as parser
from elifetools import utils as eautils
from elifearticle import article as ea
from elifearticle import utils
from elifearticle.utils import unicode_value
def build_contributors(authors, contrib_type, competing_interests=None):
"""
Given a list of authors from the parser, instantiate contributors
objects and build them
"""
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors
def build_funding(award_groups):
"""
Given a funding data, format it
"""
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards
def build_datasets(datasets_json):
"""
Given datasets in JSON format, build and return a list of dataset objects
"""
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets
def build_data_availability(datasets_json):
"""
Given datasets in JSON format, get the data availability from it if present
"""
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability
def build_ref_list(refs):
"""
Given parsed references build a list of ref objects
"""
ref_list = []
for reference in refs:
ref = ea.Citation()
# Publcation Type
utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type'))
# id
utils.set_attr_if_value(ref, 'id', reference.get('id'))
# Article title
utils.set_attr_if_value(ref, 'article_title', reference.get('full_article_title'))
# Source
utils.set_attr_if_value(ref, 'source', reference.get('source'))
# Volume
utils.set_attr_if_value(ref, 'volume', reference.get('volume'))
# Issue
utils.set_attr_if_value(ref, 'issue', reference.get('issue'))
# First page
utils.set_attr_if_value(ref, 'fpage', reference.get('fpage'))
# Last page
utils.set_attr_if_value(ref, 'lpage', reference.get('lpage'))
# DOI
utils.set_attr_if_value(ref, 'doi', reference.get('doi'))
# Year
utils.set_attr_if_value(ref, 'year', reference.get('year'))
# Year date in iso 8601 format
utils.set_attr_if_value(ref, 'year_iso_8601_date', reference.get('year-iso-8601-date'))
# Can set the year_numeric now
if ref.year_iso_8601_date is not None:
# First preference take it from the iso 8601 date, if available
try:
ref.year_numeric = int(ref.year_iso_8601_date.split('-')[0])
except ValueError:
ref.year_numeric = None
if ref.year_numeric is None:
# Second preference, use the year value if it is entirely numeric
if utils.is_year_numeric(ref.year):
ref.year_numeric = ref.year
# date-in-citation
utils.set_attr_if_value(ref, 'date_in_citation', reference.get('date-in-citation'))
# elocation-id
utils.set_attr_if_value(ref, 'elocation_id', reference.get('elocation-id'))
# uri
utils.set_attr_if_value(ref, 'uri', reference.get('uri'))
if not ref.uri:
# take uri value from uri_text
utils.set_attr_if_value(ref, 'uri', reference.get('uri_text'))
# pmid
utils.set_attr_if_value(ref, 'pmid', reference.get('pmid'))
# isbn
utils.set_attr_if_value(ref, 'isbn', reference.get('isbn'))
# accession
utils.set_attr_if_value(ref, 'accession', reference.get('accession'))
# patent
utils.set_attr_if_value(ref, 'patent', reference.get('patent'))
# patent country
utils.set_attr_if_value(ref, 'country', reference.get('country'))
# publisher-loc
utils.set_attr_if_value(ref, 'publisher_loc', reference.get('publisher_loc'))
# publisher-name
utils.set_attr_if_value(ref, 'publisher_name', reference.get('publisher_name'))
# edition
utils.set_attr_if_value(ref, 'edition', reference.get('edition'))
# version
utils.set_attr_if_value(ref, 'version', reference.get('version'))
# chapter-title
utils.set_attr_if_value(ref, 'chapter_title', reference.get('chapter-title'))
# comment
utils.set_attr_if_value(ref, 'comment', reference.get('comment'))
# data-title
utils.set_attr_if_value(ref, 'data_title', reference.get('data-title'))
# conf-name
utils.set_attr_if_value(ref, 'conf_name', reference.get('conf-name'))
# Authors
if reference.get('authors'):
for author in reference.get('authors'):
ref_author = {}
eautils.set_if_value(ref_author, 'group-type', author.get('group-type'))
eautils.set_if_value(ref_author, 'surname', author.get('surname'))
eautils.set_if_value(ref_author, 'given-names', author.get('given-names'))
eautils.set_if_value(ref_author, 'collab', author.get('collab'))
if ref_author:
ref.add_author(ref_author)
# Try to populate the doi attribute if the uri is a doi
if not ref.doi and ref.uri:
if ref.uri != eautils.doi_uri_to_doi(ref.uri):
ref.doi = eautils.doi_uri_to_doi(ref.uri)
# Append the reference to the list
ref_list.append(ref)
return ref_list
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return title
def build_components(components):
"""
Given parsed components build a list of component objects
"""
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list
def build_related_articles(related_articles):
"""
Given parsed data build a list of related article objects
"""
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_instance)
def build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
"""
Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents
"""
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts)
def build_article_from_xml(article_xml_filename, detail="brief",
build_parts=None, remove_tags=None):
"""
Parse JATS XML with elifetools parser, and populate an
eLifePOA article object
Basic data crossref needs: article_id, doi, title, contributors with names set
detail="brief" is normally enough,
detail="full" will populate all the contributor affiliations that are linked by xref tags
"""
build_part = lambda part: build_part_check(part, build_parts)
error_count = 0
soup = parser.parse_document(article_xml_filename)
# Get DOI
doi = parser.doi(soup)
# Create the article object
article = ea.Article(doi, title=None)
# article version from the filename if possible
utils.set_attr_if_value(article, 'version',
utils.version_from_xml_filename(article_xml_filename))
# journal title
if build_part('basic'):
article.journal_title = parser.journal_title(soup)
# issn
if build_part('basic'):
article.journal_issn = parser.journal_issn(soup, "electronic")
if article.journal_issn is None:
article.journal_issn = parser.journal_issn(soup)
# Related articles
if build_part('related_articles'):
article.related_articles = build_related_articles(parser.related_article(soup))
# Get publisher_id pii
if build_part('basic'):
article.pii = parser.publisher_id(soup)
# set object manuscript value
if build_part('basic'):
manuscript = parser.publisher_id(soup)
if not manuscript and doi:
# try to get it from the DOI
manuscript = doi.split('.')[-1]
article.manuscript = manuscript
# Set the articleType
if build_part('basic'):
article_type = parser.article_type(soup)
if article_type:
article.article_type = article_type
# title
if build_part('basic'):
article.title = parser.full_title(soup)
#print article.title
# publisher_name
if build_part('basic'):
article.publisher_name = parser.publisher(soup)
# abstract
if build_part('abstract'):
article.abstract = clean_abstract(parser.full_abstract(soup), remove_tags)
# digest
if build_part('abstract'):
article.digest = clean_abstract(parser.full_digest(soup), remove_tags)
# elocation-id
if build_part('basic'):
article.elocation_id = parser.elocation_id(soup)
# issue
if build_part('basic'):
article.issue = parser.issue(soup)
# self-uri
if build_part('basic'):
article.self_uri_list = build_self_uri_list(parser.self_uri(soup))
# contributors
if build_part('contributors'):
# get the competing interests if available
competing_interests = parser.competing_interests(soup, None)
all_contributors = parser.contributors(soup, detail)
author_contributors = [con for con in all_contributors
if con.get('type') in ['author', 'on-behalf-of']]
contrib_type = "author"
contributors = build_contributors(author_contributors, contrib_type, competing_interests)
contrib_type = "author non-byline"
authors = parser.authors_non_byline(soup, detail)
contributors_non_byline = build_contributors(authors, contrib_type, competing_interests)
article.contributors = contributors + contributors_non_byline
# license href
if build_part('license'):
license_object = ea.License()
license_object.href = parser.license_url(soup)
license_object.copyright_statement = parser.copyright_statement(soup)
article.license = license_object
# article_category
if build_part('categories'):
article.article_categories = parser.category(soup)
# keywords
if build_part('keywords'):
article.author_keywords = parser.keywords(soup)
# research organisms
if build_part('research_organisms'):
article.research_organisms = parser.research_organism(soup)
# funding awards
if build_part('funding'):
article.funding_awards = build_funding(parser.full_award_groups(soup))
# datasets
if build_part('datasets'):
datasets_json = parser.datasets_json(soup)
article.datasets = build_datasets(datasets_json)
article.data_availability = build_data_availability(datasets_json)
# references or citations
if build_part('references'):
article.ref_list = build_ref_list(parser.refs(soup))
# components with component DOI
if build_part('components'):
article.component_list = build_components(parser.components(soup))
# History dates
if build_part('history'):
date_types = ["received", "accepted"]
for date_type in date_types:
history_date = parser.history_date(soup, date_type)
if history_date:
date_instance = ea.ArticleDate(date_type, history_date)
article.add_date(date_instance)
# Pub date
if build_part('pub_dates'):
build_pub_dates(article, parser.pub_dates(soup))
# Set the volume if present
if build_part('volume'):
volume = parser.volume(soup)
if volume:
article.volume = volume
if build_part('is_poa'):
article.is_poa = parser.is_poa(soup)
return article, error_count
|
elifesciences/elife-article | elifearticle/article.py | Article.get_self_uri | python | def get_self_uri(self, content_type):
"return the first self uri with the content_type"
try:
return [self_uri for self_uri in self.self_uri_list
if self_uri.content_type == content_type][0]
except IndexError:
return None | return the first self uri with the content_type | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/article.py#L145-L151 | null | class Article(BaseObject):
"""
We include some boiler plate in the init, namely article_type
"""
contributors = []
def __new__(cls, doi=None, title=None):
new_instance = object.__new__(cls)
new_instance.init(doi, title)
return new_instance
def init(self, doi=None, title=None):
self.article_type = "research-article"
self.display_channel = None
self.doi = doi
self.contributors = []
self.title = title
self.abstract = ""
self.research_organisms = []
self.manuscript = None
self.dates = {}
self.license = None
self.article_categories = []
self.conflict_default = None
self.ethics = []
self.author_keywords = []
self.funding_awards = []
self.ref_list = []
self.component_list = []
# For PubMed function a hook to specify if article was ever through PoA pipeline
self.was_ever_poa = None
self.is_poa = None
self.volume = None
self.elocation_id = None
self.pii = None
self.related_articles = []
self.version = None
self.datasets = []
self.data_availability = None
self.funding_awards = []
self.funding_note = None
self.journal_issn = None
self.journal_title = None
self.self_uri_list = []
self.version = None
self.publisher_name = None
self.issue = None
def add_contributor(self, contributor):
self.contributors.append(contributor)
def add_research_organism(self, research_organism):
self.research_organisms.append(research_organism)
def add_date(self, date):
self.dates[date.date_type] = date
def get_date(self, date_type):
"get date by date type"
try:
return self.dates[date_type]
except (KeyError, TypeError):
return None
def get_display_channel(self):
"display-channel string partly relates to the article_type"
return self.display_channel
def add_article_category(self, article_category):
self.article_categories.append(article_category)
def has_contributor_conflict(self):
# Return True if any contributors have a conflict
for contributor in self.contributors:
if contributor.conflict:
return True
return False
def add_ethic(self, ethic):
self.ethics.append(ethic)
def add_author_keyword(self, author_keyword):
self.author_keywords.append(author_keyword)
def add_dataset(self, dataset):
self.datasets.append(dataset)
def get_datasets(self, dataset_type=None):
if dataset_type:
return [d for d in self.datasets if d.dataset_type == dataset_type]
return self.datasets
def add_funding_award(self, funding_award):
self.funding_awards.append(funding_award)
def add_self_uri(self, uri):
self.self_uri_list.append(uri)
def pretty(self):
"sort values and format output for viewing and comparing in test scenarios"
pretty_obj = OrderedDict()
for key, value in sorted(iteritems(self.__dict__)):
if value is None:
pretty_obj[key] = None
elif is_str_or_unicode(value):
pretty_obj[key] = self.__dict__.get(key)
elif isinstance(value, list):
pretty_obj[key] = []
elif isinstance(value, dict):
pretty_obj[key] = {}
else:
pretty_obj[key] = unicode_value(value)
return pretty_obj
|
elifesciences/elife-article | elifearticle/article.py | Article.pretty | python | def pretty(self):
"sort values and format output for viewing and comparing in test scenarios"
pretty_obj = OrderedDict()
for key, value in sorted(iteritems(self.__dict__)):
if value is None:
pretty_obj[key] = None
elif is_str_or_unicode(value):
pretty_obj[key] = self.__dict__.get(key)
elif isinstance(value, list):
pretty_obj[key] = []
elif isinstance(value, dict):
pretty_obj[key] = {}
else:
pretty_obj[key] = unicode_value(value)
return pretty_obj | sort values and format output for viewing and comparing in test scenarios | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/article.py#L153-L167 | [
"def is_str_or_unicode(value):\n try:\n return isinstance(value, unicode)\n except NameError: # pragma: no cover\n return isinstance(value, str)\n"
] | class Article(BaseObject):
"""
We include some boiler plate in the init, namely article_type
"""
contributors = []
def __new__(cls, doi=None, title=None):
new_instance = object.__new__(cls)
new_instance.init(doi, title)
return new_instance
def init(self, doi=None, title=None):
self.article_type = "research-article"
self.display_channel = None
self.doi = doi
self.contributors = []
self.title = title
self.abstract = ""
self.research_organisms = []
self.manuscript = None
self.dates = {}
self.license = None
self.article_categories = []
self.conflict_default = None
self.ethics = []
self.author_keywords = []
self.funding_awards = []
self.ref_list = []
self.component_list = []
# For PubMed function a hook to specify if article was ever through PoA pipeline
self.was_ever_poa = None
self.is_poa = None
self.volume = None
self.elocation_id = None
self.pii = None
self.related_articles = []
self.version = None
self.datasets = []
self.data_availability = None
self.funding_awards = []
self.funding_note = None
self.journal_issn = None
self.journal_title = None
self.self_uri_list = []
self.version = None
self.publisher_name = None
self.issue = None
def add_contributor(self, contributor):
self.contributors.append(contributor)
def add_research_organism(self, research_organism):
self.research_organisms.append(research_organism)
def add_date(self, date):
self.dates[date.date_type] = date
def get_date(self, date_type):
"get date by date type"
try:
return self.dates[date_type]
except (KeyError, TypeError):
return None
def get_display_channel(self):
"display-channel string partly relates to the article_type"
return self.display_channel
def add_article_category(self, article_category):
self.article_categories.append(article_category)
def has_contributor_conflict(self):
# Return True if any contributors have a conflict
for contributor in self.contributors:
if contributor.conflict:
return True
return False
def add_ethic(self, ethic):
self.ethics.append(ethic)
def add_author_keyword(self, author_keyword):
self.author_keywords.append(author_keyword)
def add_dataset(self, dataset):
self.datasets.append(dataset)
def get_datasets(self, dataset_type=None):
if dataset_type:
return [d for d in self.datasets if d.dataset_type == dataset_type]
return self.datasets
def add_funding_award(self, funding_award):
self.funding_awards.append(funding_award)
def add_self_uri(self, uri):
self.self_uri_list.append(uri)
def get_self_uri(self, content_type):
"return the first self uri with the content_type"
try:
return [self_uri for self_uri in self.self_uri_list
if self_uri.content_type == content_type][0]
except IndexError:
return None
|
elifesciences/elife-article | elifearticle/utils.py | entity_to_unicode | python | def entity_to_unicode(string):
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string | Quick convert unicode HTML entities to unicode characters
using a regular expression replacement | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L37-L59 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | remove_tag | python | def remove_tag(tag_name, string):
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string | Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L61-L70 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | replace_tags | python | def replace_tags(string, from_tag='i', to_tag='italic'):
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string | Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L72-L80 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | version_from_xml_filename | python | def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None | extract the numeric version from the xml filename | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L93-L105 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | get_last_commit_to_master | python | def get_last_commit_to_master(repo_path="."):
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit) | returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient. | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L107-L125 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | calculate_journal_volume | python | def calculate_journal_volume(pub_date, year):
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume | volume value is based on the pub date year
pub_date is a python time object | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L127-L138 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | author_name_from_json | python | def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name | concatenate an author name from json data | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L140-L149 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
elifesciences/elife-article | elifearticle/utils.py | text_from_affiliation_elements | python | def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element) | format an author affiliation from details | train | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L151-L153 | null | """
Utility functions for converting content and some shared by other libraries
"""
import re
import os
from git import Repo, InvalidGitRepositoryError, NoSuchPathError
def is_str_or_unicode(value):
try:
return isinstance(value, unicode)
except NameError: # pragma: no cover
return isinstance(value, str)
def unicode_value(value):
try:
return unicode(value)
except NameError: # pragma: no cover
return str(value)
def uni_chr(chr_code):
try:
return unichr(chr_code)
except NameError: # pragma: no cover
return chr(chr_code)
def repl(match):
"Convert hex to int to unicode character"
chr_code = int(match.group(1), 16)
return uni_chr(chr_code)
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
def replace_tags(string, from_tag='i', to_tag='italic'):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
return string
def set_attr_if_value(obj, attr_name, value):
"shorthand method to set object values if the value is not none"
if value is not None:
setattr(obj, attr_name, value)
def is_year_numeric(value):
"True if value is all digits"
if value and re.match("^[0-9]+$", value):
return True
return False
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
|
DaveMcEwan/ndim | ndim_bezier.py | pt_on_bezier_curve | python | def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there is only one left, which is the point we want.
Q = P
while O > 0:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 1
return Q[0] | Return point at t on bezier curve defined by control points P. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L6-L29 | null | # Math functions for calculating bezier curves in N dimensions.
from ndim_base import *
def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there is only one left, which is the point we want.
Q = P
while O > 0:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 1
return Q[0]
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(n_seg, int)
assert n_seg >= 0
return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
n_seg = len(P) - 1
pts = pts_on_bezier_curve(P, n_seg)
return sum([distance_between_pts(pts[i], pts[i+1]) for i in range(n_seg)])
def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(P, list)
assert len(P) > 0
if not len(P) > 1:
return None # Points have no gradient.
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there are only two left, which is the points on the gradient we want.
Q = P
while O > 1:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 2
# Now that we have the two points in N dimensions, we can reduce to the
# gradients on N-1 planes.
q0 = Q[0]
q1 = Q[1]
return dir_between_pts(q0, q1)
|
DaveMcEwan/ndim | ndim_bezier.py | pts_on_bezier_curve | python | def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(n_seg, int)
assert n_seg >= 0
return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]] | Return list N+1 points representing N line segments on bezier curve
defined by control points P. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L32-L46 | null | # Math functions for calculating bezier curves in N dimensions.
from ndim_base import *
def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there is only one left, which is the point we want.
Q = P
while O > 0:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 1
return Q[0]
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(n_seg, int)
assert n_seg >= 0
return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
n_seg = len(P) - 1
pts = pts_on_bezier_curve(P, n_seg)
return sum([distance_between_pts(pts[i], pts[i+1]) for i in range(n_seg)])
def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(P, list)
assert len(P) > 0
if not len(P) > 1:
return None # Points have no gradient.
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there are only two left, which is the points on the gradient we want.
Q = P
while O > 1:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 2
# Now that we have the two points in N dimensions, we can reduce to the
# gradients on N-1 planes.
q0 = Q[0]
q1 = Q[1]
return dir_between_pts(q0, q1)
|
DaveMcEwan/ndim | ndim_bezier.py | bezier_curve_approx_len | python | def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
n_seg = len(P) - 1
pts = pts_on_bezier_curve(P, n_seg)
return sum([distance_between_pts(pts[i], pts[i+1]) for i in range(n_seg)]) | Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L49-L64 | [
"def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):\n '''Return list N+1 points representing N line segments on bezier curve\n defined by control points P.\n '''\n assert isinstance(P, list)\n assert len(P) > 0\n for p in P:\n assert isinstance(p, tuple)\n for i in p:\n asser... | # Math functions for calculating bezier curves in N dimensions.
from ndim_base import *
def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there is only one left, which is the point we want.
Q = P
while O > 0:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 1
return Q[0]
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(n_seg, int)
assert n_seg >= 0
return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
n_seg = len(P) - 1
pts = pts_on_bezier_curve(P, n_seg)
return sum([distance_between_pts(pts[i], pts[i+1]) for i in range(n_seg)])
def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(P, list)
assert len(P) > 0
if not len(P) > 1:
return None # Points have no gradient.
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there are only two left, which is the points on the gradient we want.
Q = P
while O > 1:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 2
# Now that we have the two points in N dimensions, we can reduce to the
# gradients on N-1 planes.
q0 = Q[0]
q1 = Q[1]
return dir_between_pts(q0, q1)
|
DaveMcEwan/ndim | ndim_bezier.py | dir_on_bezier_curve | python | def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(P, list)
assert len(P) > 0
if not len(P) > 1:
return None # Points have no gradient.
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there are only two left, which is the points on the gradient we want.
Q = P
while O > 1:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 2
# Now that we have the two points in N dimensions, we can reduce to the
# gradients on N-1 planes.
q0 = Q[0]
q1 = Q[1]
return dir_between_pts(q0, q1) | Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L67-L101 | [
"def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):\n '''Return direction between two points on N dimensions.\nList of vectors per pair of dimensions are returned in radians.\nE.g. Where X is \"right\", Y is \"up\", Z is \"in\" on a computer screen, and\n returned value is [pi/4, -pi/4], then the vector will be c... | # Math functions for calculating bezier curves in N dimensions.
from ndim_base import *
def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there is only one left, which is the point we want.
Q = P
while O > 0:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 1
return Q[0]
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(n_seg, int)
assert n_seg >= 0
return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
n_seg = len(P) - 1
pts = pts_on_bezier_curve(P, n_seg)
return sum([distance_between_pts(pts[i], pts[i+1]) for i in range(n_seg)])
def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(P, list)
assert len(P) > 0
if not len(P) > 1:
return None # Points have no gradient.
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
O = len(P) - 1 # Order of curve
# Recurse down the orders calculating the next set of control points until
# there are only two left, which is the points on the gradient we want.
Q = P
while O > 1:
Q = [pt_between_pts(Q[l], Q[l+1], t) for l in range(O)]
O -= 1
assert len(Q) == 2
# Now that we have the two points in N dimensions, we can reduce to the
# gradients on N-1 planes.
q0 = Q[0]
q1 = Q[1]
return dir_between_pts(q0, q1)
|
DaveMcEwan/ndim | ndim_base.py | vectors_between_pts | python | def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)] | Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L8-L26 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | dir_between_pts | python | def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)] | Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L29-L53 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_between_pts | python | def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ]) | Return the point between two points on N dimensions. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L56-L71 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | distance_between_pts | python | def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)])) | Return the distance between two points on N dimensions (Euclidean distance). | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L74-L87 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_change_axis | python | def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)]) | Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L90-L113 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_change_axis | python | def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts] | Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L116-L142 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_rotate | python | def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r) | Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L145-L180 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_rotate | python | def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts] | Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L183-L209 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_shift | python | def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)]) | Return given point shifted in N dimensions. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L212-L226 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_shift | python | def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts] | Return given points shifted in N dimensions. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L229-L249 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_relative | python | def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt) | Convenience shift+rotate combination. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L252-L272 | [
"def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):\n '''Return given point rotated around a center point in N dimensions.\nAngle is list of rotation in radians for each pair of axis.\n '''\n assert isinstance(pt, tuple)\n l_pt = len(pt)\n assert l_pt > 1\n for i in pt:\n assert ... | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_relative | python | def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts] | Convenience shift+rotate combination. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L275-L301 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_reflect | python | def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)]) | Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L304-L320 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_reflect | python | def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts] | Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L323-L345 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pt_scale | python | def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)]) | Return given point scaled by factor f from origin. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L348-L358 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | pts_scale | python | def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts] | Return given points scaled by factor f from origin. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L361-L377 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | angle_diff | python | def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff] | Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L380-L402 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)]
|
DaveMcEwan/ndim | ndim_base.py | gen_polygon_pts | python | def gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc.
'''
assert isinstance(n_pts, int) and n_pts > 0
assert isinstance(radius, list)
l_rad = len(radius)
assert l_rad > 0
for i in radius:
assert isinstance(i, float)
return [pt_rotate((radius[i % l_rad], 0.0), [i*2*pi/n_pts]) \
for i in range(n_pts)] | Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give complex shapes like stars, gear wheels, ratchet
wheels, etc. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_base.py#L405-L421 | null | # Base math functions for manipulating geometry.
# Intended to be used as from math_base import * as this gets all the python
# math functions too.
from math import *
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
for i in range(l_pts)]
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
# Difference used for calculating gradient, giving 2 quadrants of direction.
delta = [b[i] - a[i] for i in range(l_pt)]
# 180 degree offset to add, giving all 4 quadrants of this pair of
# dimensions.
semiturn = [pi * int(b[p] < a[p]) for p in range(l_pt-1)]
return [atan(delta[p+1] / delta[p]) + semiturn[p] for p in range(l_pt-1)]
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
assert isinstance(t, float)
assert 0 <= t <= 1
return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
def distance_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return the distance between two points on N dimensions (Euclidean distance).
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in b:
assert isinstance(i, float)
return sqrt(sum([(b[i] - a[i])**2 for i in range(l_pt)]))
def pt_change_axis(pt=(0.0, 0.0), flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
# Convert True/False to -1/1
flip_mul = [-2 * int(f) + 1 for f in flip]
return tuple([offset[i] + pt[i]*flip_mul[i] for i in range(l_pt)])
def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(flip, list)
l_fl = len(flip)
assert l_fl == l_pt
for i in flip:
assert isinstance(i, bool)
assert isinstance(offset, list)
l_of = len(offset)
assert l_of == l_pt
for i in offset:
assert isinstance(i, float)
return [pt_change_axis(pt, flip, offset) for pt in pts]
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
# Get vector from center to point and use to get relative polar coordinate.
v_cart = [pt[i] - center[i] for i in range(l_pt)]
# Length of vector needs to stay constant for new point.
v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)]
v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \
for i in range(l_angle)]
# Add rotation angle then convert back to cartesian vector.
n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)]
n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\
for i in range(l_angle)]
# Add in the centre offset to get original offset from c.
r = [n_cart[i] + center[i] for i in range(l_pt)]
return tuple(r)
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(center, tuple)
assert len(center) == l_pt
for i in center:
assert isinstance(i, float)
return [pt_rotate(pt, angle, center) for pt in pts]
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return tuple([pt[i] + shift[i] for i in range(l_pt)])
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
return [pt_shift(pt, shift) for pt in pts]
def pt_relative(pt=(0.0, 0.0), shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return pt_rotate(pt_shift(pt, shift), angle, pt)
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]):
'''Convenience shift+rotate combination.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for i in shift:
assert isinstance(i, float)
assert isinstance(angle, list)
l_angle = len(angle)
assert l_angle == l_pt-1
for i in angle:
assert isinstance(i, float)
assert abs(i) <= 2*pi
return [pt_relative(pt, shift, angle) for pt in pts]
def pt_reflect(pt=(0.0, 0.0), plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return tuple([pt[i] if plane[i] is None else (2*plane[i] - pt[i]) for i in range(l_pt)])
def pts_reflect(pts=[], plane=[None, None]):
'''Return given point reflected around planes in N dimensions.
There must be the same number of planes as dimensions, but the value of each
plane may be None to indicate no reflection.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(plane, list)
l_pl = len(plane)
assert l_pl == l_pt
for i in plane:
assert isinstance(i, float) or i is None
return [pt_reflect(pt, plane) for pt in pts]
def pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)])
def pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
if l_pt_prev is not None:
assert l_pt == l_pt_prev
l_pt_prev = l_pt
assert isinstance(f, float)
return [pt_scale(pt, f) for pt in pts]
def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
# Convert True/False to 1/-1
inv = 2 * int(direction) - 1
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(2*pi + d) if d < 0.0 else d for d in diff]
return [d*inv for d in diff]
|
DaveMcEwan/ndim | ndim_arc.py | arc_length | python | def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0):
'''Return Euclidean length of arc.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(radius, float)
# Allow negative radius
full = pi * radius*2
diff = angle_diff(start_a, end_a, True)
vec = [full * abs(d)/(2*pi) for d in diff]
return sqrt(sum([v**2 for v in vec])) | Return Euclidean length of arc. | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_arc.py#L41-L61 | [
"def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):\n '''Return difference in angle from start_a to end_a.\nDirection follows the right-hand-rule so positive is counter-clockwise.\n '''\n assert isinstance(start_a, list)\n assert isinstance(end_a, list)\n l_angle = len(start_a)\n assert l... | # Math functions for calculating attributes of circular arcs.
# arcinfo_* functions fill in the unknown attributes of an N-dimensional arc.
# Attributes to be filled in by arcinfo_*():
# radius: float
# center: (float, float)
# start_pt: (float, float, ...)
# end_pt: (float, float, ...)
# start_angle: [float, ...]; 0 <= x <= 2*pi
# end_angle: [float, ...]; 0 <= x <= 2*pi
# diff_angle: [float, ...]; -2*pi <= x <= 2*pi
# direction: bool; True=counter-clockwise, False=clockwise
# big: [bool, ...]
# length: float
# These are extrapolated to N
from ndim_base import *
def arc_is_big(start_a=[0.0], end_a=[0.0], direction=True):
'''Return True if arc is the long way round the center.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
for i in end_a:
assert isinstance(i, float)
assert abs(i) <= 2*pi
assert isinstance(direction, bool)
diff = [end_a[i] - start_a[i] for i in range(l_angle)]
diff = [(d < 0.0) != (abs(d) > pi) for d in diff]
return [d if direction else not d for d in diff]
def arcinfo_center_angles(center=(0.0, 0.0),
radius=0.0,
start_a=[0.0],
end_a=[0.0],
direction=True):
ret = dict()
ret['center'] = center
ret['radius'] = radius
ret['start_a'] = start_a
ret['end_a'] = end_a
ret['direction'] = direction
ret['start_pt'] = pt_relative(center, [radius, 0.0], start_a)
ret['end_pt'] = pt_relative(center, [radius, 0.0], end_a)
ret['diff_a'] = angle_diff(start_a, end_a, direction)
ret['big'] = arc_is_big(start_a, end_a, direction)
ret['length'] = arc_length(start_a, end_a, radius)
return ret
|
thisfred/val | val/_val.py | _build_type_validator | python | def _build_type_validator(value_type):
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator | Build a validator that only checks the type of a value. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L25-L35 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _build_static_validator | python | def _build_static_validator(exact_value):
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator | Build a validator that checks if the data is equal to an exact value. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L38-L48 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _build_callable_validator | python | def _build_callable_validator(function):
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator | Build a validator that checks the return value of function(data). | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L51-L65 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _build_iterable_validator | python | def _build_iterable_validator(iterable):
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator | Build a validator from an iterable. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L68-L90 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.