desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'A boolean indicating whether image comparison is available'
def _can_compare(self):
return ((self.method[0] == IMAGEMAGICK) and (self.method[1] > (6, 8, 7)))
'Return a tuple indicating an available method and its version.'
@staticmethod def _check_method():
version = get_im_version() if version: return (IMAGEMAGICK, version) version = get_pil_version() if version: return (PIL, version) return (WEBPROXY, 0)
'Evaluate the symbol in the environment, returning a Unicode string.'
def evaluate(self, env):
if (self.ident in env.values): return env.values[self.ident] else: return self.original
'Compile the variable lookup.'
def translate(self):
if six.PY2: ident = self.ident.encode('utf-8') else: ident = self.ident expr = ex_rvalue((VARIABLE_PREFIX + ident)) return ([expr], set([ident]), set())
'Evaluate the function call in the environment, returning a Unicode string.'
def evaluate(self, env):
if (self.ident in env.functions): arg_vals = [expr.evaluate(env) for expr in self.args] try: out = env.functions[self.ident](*arg_vals) except Exception as exc: return (u'<%s>' % six.text_type(exc)) return six.text_type(out) else: return self.origi...
'Compile the function call.'
def translate(self):
varnames = set() if six.PY2: ident = self.ident.encode('utf-8') else: ident = self.ident funcnames = set([ident]) arg_exprs = [] for arg in self.args: (subexprs, subvars, subfuncs) = arg.translate() varnames.update(subvars) funcnames.update(subfuncs) ...
'Evaluate the entire expression in the environment, returning a Unicode string.'
def evaluate(self, env):
out = [] for part in self.parts: if isinstance(part, six.string_types): out.append(part) else: out.append(part.evaluate(env)) return u''.join(map(six.text_type, out))
'Compile the expression to a list of Python AST expressions, a set of variable names used, and a set of function names.'
def translate(self):
expressions = [] varnames = set() funcnames = set() for part in self.parts: if isinstance(part, six.string_types): expressions.append(ex_literal(part)) else: (e, v, f) = part.translate() expressions.extend(e) varnames.update(v) ...
'Create a new parser. :param in_arguments: boolean that indicates the parser is to be used for parsing function arguments, ie. considering commas (`ARG_SEP`) a special character'
def __init__(self, string, in_argument=False):
self.string = string self.in_argument = in_argument self.pos = 0 self.parts = []
'Parse a template expression starting at ``pos``. Resulting components (Unicode strings, Symbols, and Calls) are added to the ``parts`` field, a list. The ``pos`` field is updated to be the next character after the expression.'
def parse_expression(self):
extra_special_chars = () special_char_re = self.special_char_re if self.in_argument: extra_special_chars = (ARG_SEP,) special_char_re = re.compile(('[%s]|$' % u''.join((re.escape(c) for c in (self.special_chars + extra_special_chars))))) text_parts = [] while (self.pos < len(self.str...
'Parse a variable reference (like ``$foo`` or ``${foo}``) starting at ``pos``. Possibly appends a Symbol object (or, failing that, text) to the ``parts`` field and updates ``pos``. The character at ``pos`` must, as a precondition, be ``$``.'
def parse_symbol(self):
assert (self.pos < len(self.string)) assert (self.string[self.pos] == SYMBOL_DELIM) if (self.pos == (len(self.string) - 1)): self.parts.append(SYMBOL_DELIM) self.pos += 1 return next_char = self.string[(self.pos + 1)] start_pos = self.pos self.pos += 1 if (next_char =...
'Parse a function call (like ``%foo{bar,baz}``) starting at ``pos``. Possibly appends a Call object to ``parts`` and update ``pos``. The character at ``pos`` must be ``%``.'
def parse_call(self):
assert (self.pos < len(self.string)) assert (self.string[self.pos] == FUNC_DELIM) start_pos = self.pos self.pos += 1 ident = self._parse_ident() if (not ident): self.parts.append(FUNC_DELIM) return if (self.pos >= len(self.string)): self.parts.append(self.string[start...
'Parse a list of arguments starting at ``pos``, returning a list of Expression objects. Does not modify ``parts``. Should leave ``pos`` pointing to a } character or the end of the string.'
def parse_argument_list(self):
expressions = [] while (self.pos < len(self.string)): subparser = Parser(self.string[self.pos:], in_argument=True) subparser.parse_expression() expressions.append(Expression(subparser.parts)) self.pos += subparser.pos if ((self.pos >= len(self.string)) or (self.string[sel...
'Parse an identifier and return it (possibly an empty string). Updates ``pos``.'
def _parse_ident(self):
remainder = self.string[self.pos:] ident = re.match('\\w*', remainder).group(0) self.pos += len(ident) return ident
'Like `substitute`, but forces the interpreter (rather than the compiled version) to be used. The interpreter includes exception-handling code for missing variables and buggy template functions but is much slower.'
def interpret(self, values={}, functions={}):
return self.expr.evaluate(Environment(values, functions))
'Evaluate the template given the values and functions.'
def substitute(self, values={}, functions={}):
try: res = self.compiled(values, functions) except: res = self.interpret(values, functions) return res
'Compile the template to a Python function.'
def translate(self):
(expressions, varnames, funcnames) = self.expr.translate() argnames = [] for varname in varnames: argnames.append((VARIABLE_PREFIX + varname)) for funcname in funcnames: argnames.append((FUNCTION_PREFIX + funcname)) func = compile_func(argnames, [ast.Return(ast.List(expressions, ast....
'Create a basic storage strategy. Parameters: - `key`: The key on the Mutagen file object used to access the field\'s data. - `as_type`: The Python type that the value is stored as internally (`unicode`, `int`, `bool`, or `bytes`). - `suffix`: When `as_type` is a string type, append this before storing the value. - `fl...
def __init__(self, key, as_type=six.text_type, suffix=None, float_places=2):
self.key = key self.as_type = as_type self.suffix = suffix self.float_places = float_places if (self.suffix and (self.as_type is six.text_type) and (not isinstance(self.suffix, six.text_type))): self.suffix = self.suffix.decode('utf-8')
'Get the value for the field using this style.'
def get(self, mutagen_file):
return self.deserialize(self.fetch(mutagen_file))
'Retrieve the raw value of for this tag from the Mutagen file object.'
def fetch(self, mutagen_file):
try: return mutagen_file[self.key][0] except (KeyError, IndexError): return None
'Given a raw value stored on a Mutagen object, decode and return the represented value.'
def deserialize(self, mutagen_value):
if (self.suffix and isinstance(mutagen_value, six.text_type) and mutagen_value.endswith(self.suffix)): return mutagen_value[:(- len(self.suffix))] else: return mutagen_value
'Assign the value for the field using this style.'
def set(self, mutagen_file, value):
self.store(mutagen_file, self.serialize(value))
'Store a serialized value in the Mutagen file object.'
def store(self, mutagen_file, value):
mutagen_file[self.key] = [value]
'Convert the external Python value to a type that is suitable for storing in a Mutagen file object.'
def serialize(self, value):
if (isinstance(value, float) and (self.as_type is six.text_type)): value = u'{0:.{1}f}'.format(value, self.float_places) value = self.as_type(value) elif (self.as_type is six.text_type): if isinstance(value, bool): value = six.text_type(int(bool(value))) elif isinstan...
'Remove the tag from the file.'
def delete(self, mutagen_file):
if (self.key in mutagen_file): del mutagen_file[self.key]
'Get the first value in the field\'s value list.'
def get(self, mutagen_file):
try: return self.get_list(mutagen_file)[0] except IndexError: return None
'Get a list of all values for the field using this style.'
def get_list(self, mutagen_file):
return [self.deserialize(item) for item in self.fetch(mutagen_file)]
'Get the list of raw (serialized) values.'
def fetch(self, mutagen_file):
try: return mutagen_file[self.key] except KeyError: return []
'Set an individual value as the only value for the field using this style.'
def set(self, mutagen_file, value):
self.set_list(mutagen_file, [value])
'Set all values for the field using this style. `values` should be an iterable.'
def set_list(self, mutagen_file, values):
self.store(mutagen_file, [self.serialize(value) for value in values])
'Set the list of all raw (serialized) values for this field.'
def store(self, mutagen_file, values):
mutagen_file[self.key] = values
'Create a new ID3 storage style. `id3_lang` is the value for the language field of newly created frames.'
def __init__(self, key, id3_lang=None, **kwargs):
self.id3_lang = id3_lang super(MP3StorageStyle, self).__init__(key, **kwargs)
'Convert APIC frame into Image.'
def deserialize(self, apic_frame):
return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
'Return an APIC frame populated with data from ``image``.'
def serialize(self, image):
assert isinstance(image, Image) frame = mutagen.id3.Frames[self.key]() frame.data = image.data frame.mime = image.mime_type frame.desc = (image.desc or u'') try: frame.desc.encode('latin-1') except UnicodeEncodeError: frame.encoding = mutagen.id3.Encoding.UTF16 else: ...
'Turn a Image into a base64 encoded FLAC picture block.'
def serialize(self, image):
pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = (image.desc or u'') return base64.b64encode(pic.write()).decode('ascii')
'``pictures`` is a list of mutagen.flac.Picture instances.'
def store(self, mutagen_file, pictures):
mutagen_file.clear_pictures() for pic in pictures: mutagen_file.add_picture(pic)
'Turn a Image into a mutagen.flac.Picture.'
def serialize(self, image):
pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = (image.desc or u'') return pic
'Remove all images from the file.'
def delete(self, mutagen_file):
mutagen_file.clear_pictures()
'Remove all images from the file.'
def delete(self, mutagen_file):
for cover_tag in self.TAG_NAMES.values(): try: del mutagen_file[cover_tag] except KeyError: pass
'Creates a new MediaField. :param styles: `StorageStyle` instances that describe the strategy for reading and writing the field in particular formats. There must be at least one style for each possible file format. :param out_type: the type of the value that should be returned when getting this property.'
def __init__(self, *styles, **kwargs):
self.out_type = kwargs.get('out_type', six.text_type) self._styles = styles
'Yields the list of storage styles of this field that can handle the MediaFile\'s format.'
def styles(self, mutagen_file):
for style in self._styles: if (mutagen_file.__class__.__name__ in style.formats): (yield style)
'Get an appropriate "null" value for this field\'s type. This is used internally when setting the field to None.'
def _none_value(self):
if (self.out_type == int): return 0 elif (self.out_type == float): return 0.0 elif (self.out_type == bool): return False elif (self.out_type == six.text_type): return u''
'Returns a ``MediaField`` descriptor that gets and sets the first item.'
def single_field(self):
options = {'out_type': self.out_type} return MediaField(*self._styles, **options)
'``date_styles`` is a list of ``StorageStyle``s to store and retrieve the whole date from. The ``year`` option is an additional list of fallback styles for the year. The year is always set on this style, but is only retrieved if the main storage styles do not return a value.'
def __init__(self, *date_styles, **kwargs):
super(DateField, self).__init__(*date_styles) year_style = kwargs.get('year', None) if year_style: self._year_field = MediaField(*year_style)
'Get a 3-item sequence representing the date consisting of a year, month, and day number. Each number is either an integer or None.'
def _get_date_tuple(self, mediafile):
datestring = super(DateField, self).__get__(mediafile, None) if isinstance(datestring, six.string_types): datestring = re.sub('[Tt ].*$', '', six.text_type(datestring)) items = re.split('[-/]', six.text_type(datestring)) else: items = [] items = items[:3] if (len(items) < ...
'Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component.'
def _set_date_tuple(self, mediafile, year, month=None, day=None):
if (year is None): self.__delete__(mediafile) return date = [u'{0:04d}'.format(int(year))] if month: date.append(u'{0:02d}'.format(int(month))) if (month and day): date.append(u'{0:02d}'.format(int(day))) date = map(six.text_type, date) super(DateField, self).__se...
'Constructs a new `MediaFile` reflecting the file at path. May throw `UnreadableFileError`. By default, MP3 files are saved with ID3v2.4 tags. You can use the older ID3v2.3 standard by specifying the `id3v23` option.'
def __init__(self, path, id3v23=False):
self.path = path self.mgfile = mutagen_call('open', path, mutagen.File, path) if (self.mgfile is None): raise FileTypeError(path) elif ((type(self.mgfile).__name__ == 'M4A') or (type(self.mgfile).__name__ == 'MP4')): info = self.mgfile.info if (info.codec and info.codec.startswit...
'Write the object\'s tags back to the file. May throw `UnreadableFileError`.'
def save(self):
kwargs = {} if self.id3v23: id3 = self.mgfile if hasattr(id3, 'tags'): id3 = id3.tags id3.update_to_v23() kwargs['v2_version'] = 3 mutagen_call('save', self.path, self.mgfile.save, **kwargs)
'Remove the current metadata tag from the file. May throw `UnreadableFileError`.'
def delete(self):
mutagen_call('delete', self.path, self.mgfile.delete)
'Get the names of all writable properties that reflect metadata tags (i.e., those that are instances of :class:`MediaField`).'
@classmethod def fields(cls):
for (property, descriptor) in cls.__dict__.items(): if isinstance(descriptor, MediaField): if isinstance(property, bytes): (yield property.decode('utf8', 'ignore')) else: (yield property)
'Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `date1`, and `date2`, respectively, to make them appear in that order.'
@classmethod def _field_sort_name(cls, name):
if isinstance(cls.__dict__[name], DateItemField): name = re.sub('year', 'date0', name) name = re.sub('month', 'date1', name) name = re.sub('day', 'date2', name) return name
'Get the names of all writable metadata fields, sorted in the order that they should be written. This is a lexicographic order, except for instances of :class:`DateItemField`, which are sorted in year-month-day order.'
@classmethod def sorted_fields(cls):
for property in sorted(cls.fields(), key=cls._field_sort_name): (yield property)
'Get all metadata fields: the writable ones from :meth:`fields` and also other audio properties.'
@classmethod def readable_fields(cls):
for property in cls.fields(): (yield property) for property in ('length', 'samplerate', 'bitdepth', 'bitrate', 'channels', 'format'): (yield property)
'Add a field to store custom tags. :param name: the name of the property the field is accessed through. It must not already exist on this class. :param descriptor: an instance of :class:`MediaField`.'
@classmethod def add_field(cls, name, descriptor):
if (not isinstance(descriptor, MediaField)): raise ValueError(u'{0} must be an instance of MediaField'.format(descriptor)) if (name in cls.__dict__): raise ValueError(u'property "{0}" already exists on MediaField'.format(name)) setattr(cls, name, descriptor)
'Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted from the `MediaFile`.'
def update(self, dict):
for field in self.sorted_fields(): if (field in dict): if (dict[field] is None): delattr(self, field) else: setattr(self, field, dict[field])
'The duration of the audio in seconds (a float).'
@property def length(self):
return self.mgfile.info.length
'The audio\'s sample rate (an int).'
@property def samplerate(self):
if hasattr(self.mgfile.info, 'sample_rate'): return self.mgfile.info.sample_rate elif (self.type == 'opus'): return 48000 return 0
'The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable).'
@property def bitdepth(self):
if hasattr(self.mgfile.info, 'bits_per_sample'): return self.mgfile.info.bits_per_sample return 0
'The number of channels in the audio (an int).'
@property def channels(self):
if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0
'The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecision is possible because the file header is incorporated in the ...
@property def bitrate(self):
if (hasattr(self.mgfile.info, 'bitrate') and self.mgfile.info.bitrate): return self.mgfile.info.bitrate else: if (not self.length): return 0 size = os.path.getsize(self.path) return int(((size * 8) / self.length))
'A string describing the file format/codec.'
@property def format(self):
return TYPES[self.type]
'Convert a representation node to a Python object.'
def from_yaml(cls, loader, node):
return loader.construct_yaml_object(node, cls)
'Convert a Python object to a representation node.'
def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)
'Initialize the scanner.'
def __init__(self):
self.done = False self.flow_level = 0 self.tokens = [] self.fetch_stream_start() self.tokens_taken = 0 self.indent = (-1) self.indents = [] self.allow_simple_key = True self.possible_simple_keys = {}
'Write tag data into the Speex comment packet/page.'
def _inject(self, fileobj, padding_func):
fileobj.seek(0) page = OggPage(fileobj) while (not page.packets[0].startswith('Speex ')): page = OggPage(fileobj) serial = page.serial page = OggPage(fileobj) while (page.serial != serial): page = OggPage(fileobj) old_pages = [page] while (not (old_pages[(-1)]....
'Parse a Vorbis comment from a file-like object. Arguments: errors (str): \'strict\', \'replace\', or \'ignore\'. This affects Unicode decoding and how other malformed content is interpreted. framing (bool): if true, fail if a framing bit is not present Framing bits are required by the Vorbis comment specification, but...
def load(self, fileobj, errors='replace', framing=True):
try: vendor_length = cdata.uint_le(fileobj.read(4)) self.vendor = fileobj.read(vendor_length).decode('utf-8', errors) count = cdata.uint_le(fileobj.read(4)) for i in xrange(count): length = cdata.uint_le(fileobj.read(4)) try: string = fileobj.r...
'Validate keys and values. Check to make sure every key used is a valid Vorbis key, and that every value used is a valid Unicode or UTF-8 string. If any invalid keys or values are found, a ValueError is raised. In Python 3 all keys and values have to be a string.'
def validate(self):
if (not isinstance(self.vendor, text_type)): if PY3: raise ValueError('vendor needs to be str') try: self.vendor.decode('utf-8') except UnicodeDecodeError: raise ValueError for (key, value) in self: try: if (not is_valid...
'Clear all keys from the comment.'
def clear(self):
for i in list(self): self.remove(i)
'Return a string representation of the data. Validation is always performed, so calling this function on invalid data may raise a ValueError. Arguments: framing (bool): if true, append a framing bit (see load)'
def write(self, framing=True):
self.validate() def _encode(value): if (not isinstance(value, bytes)): return value.encode('utf-8') return value f = BytesIO() vendor = _encode(self.vendor) f.write(cdata.to_uint_le(len(vendor))) f.write(vendor) f.write(cdata.to_uint_le(len(self))) for (tag, v...
'A list of values for the key. This is a copy, so comment[\'title\'].append(\'a title\') will not work.'
def __getitem__(self, key):
if isinstance(key, slice): return VComment.__getitem__(self, key) if (not is_valid_key(key)): raise ValueError key = key.lower() values = [value for (k, value) in self if (k.lower() == key)] if (not values): raise KeyError(key) else: return values
'Delete all values associated with the key.'
def __delitem__(self, key):
if isinstance(key, slice): return VComment.__delitem__(self, key) if (not is_valid_key(key)): raise ValueError key = key.lower() to_delete = [x for x in self if (x[0].lower() == key)] if (not to_delete): raise KeyError(key) else: for item in to_delete: ...
'Return true if the key has any values.'
def __contains__(self, key):
if (not is_valid_key(key)): raise ValueError key = key.lower() for (k, value) in self: if (k.lower() == key): return True else: return False
'Set a key\'s value or values. Setting a value overwrites all old ones. The value may be a list of Unicode or UTF-8 strings, or a single Unicode or UTF-8 string.'
def __setitem__(self, key, values):
if isinstance(key, slice): return VComment.__setitem__(self, key, values) if (not is_valid_key(key)): raise ValueError if (not isinstance(values, list)): values = [values] try: del self[key] except KeyError: pass if PY2: key = key.encode('ascii') ...
'Return all keys in the comment.'
def keys(self):
return list(set([k.lower() for (k, v) in self]))
'Return a copy of the comment data in a real dict.'
def as_dict(self):
return dict([(key, self[key]) for key in self.keys()])
'Returns a possibly valid _ADTSStream or None. Args: max_bytes (int): maximum bytes to read'
@classmethod def find_stream(cls, fileobj, max_bytes):
r = BitReader(fileobj) stream = cls(r) if stream.sync(max_bytes): stream.offset = ((r.get_position() - 12) // 8) return stream
'Find the next sync. Returns True if found.'
def sync(self, max_bytes):
max_bytes = max(max_bytes, 2) r = self._r r.align() while (max_bytes > 0): try: b = r.bytes(1) if (b == '\xff'): if (r.bits(4) == 15): return True r.align() max_bytes -= 2 else: ...
'Use _ADTSStream.find_stream to create a stream'
def __init__(self, r):
self._fixed_header_key = None self._r = r self.offset = (-1) self.parsed_frames = 0 self._samples = 0 self._payload = 0 self._start = (r.get_position() / 8) self._last = self._start
'Bitrate of the raw aac blocks, excluding framing/crc'
@property def bitrate(self):
assert self.parsed_frames, 'no frame parsed yet' if (self._samples == 0): return 0 return (((8 * self._payload) * self.frequency) // self._samples)
'samples so far'
@property def samples(self):
assert self.parsed_frames, 'no frame parsed yet' return self._samples
'bytes read in the stream so far (including framing)'
@property def size(self):
assert self.parsed_frames, 'no frame parsed yet' return (self._last - self._start)
'0 means unknown'
@property def channels(self):
assert self.parsed_frames, 'no frame parsed yet' b_index = self._fixed_header_key[6] if (b_index == 7): return 8 elif (b_index > 7): return 0 else: return b_index
'0 means unknown'
@property def frequency(self):
assert self.parsed_frames, 'no frame parsed yet' f_index = self._fixed_header_key[4] try: return _FREQS[f_index] except IndexError: return 0
'True if parsing was successful. Fails either because the frame wasn\'t valid or the stream ended.'
def parse_frame(self):
try: return self._parse_frame() except BitReaderError: return False
'Reads the program_config_element() Raises BitReaderError'
def __init__(self, r):
self.element_instance_tag = r.bits(4) self.object_type = r.bits(2) self.sampling_frequency_index = r.bits(4) num_front_channel_elements = r.bits(4) num_side_channel_elements = r.bits(4) num_back_channel_elements = r.bits(4) num_lfe_channel_elements = r.bits(2) num_assoc_data_elements = r...
'Raises AACError'
@convert_error(IOError, AACError) def __init__(self, fileobj):
start_offset = 0 header = fileobj.read(10) if header.startswith('ID3'): size = BitPaddedInt(header[6:]) start_offset = (size + 10) fileobj.seek(start_offset) adif = fileobj.read(4) if (adif == 'ADIF'): self._parse_adif(fileobj) self._type = 'ADIF' else: ...
'Write tag data into the FLAC Vorbis comment packet/page.'
def _inject(self, fileobj, padding_func):
fileobj.seek(0) page = OggPage(fileobj) while (not page.packets[0].startswith('\x7fFLAC')): page = OggPage(fileobj) first_page = page while (not ((page.sequence == 1) and (page.serial == first_page.serial))): page = OggPage(fileobj) old_pages = [page] while (not (old_pages[(-...
'Reads `count` bits and returns an uint, MSB read first. May raise BitReaderError if not enough data could be read or IOError by the underlying file object.'
def bits(self, count):
if (count < 0): raise ValueError if (count > self._bits): n_bytes = (((count - self._bits) + 7) // 8) data = self._fileobj.read(n_bytes) if (len(data) != n_bytes): raise BitReaderError('not enough data') for b in bytearray(data): self._buffer...
'Returns a bytearray of length `count`. Works unaligned.'
def bytes(self, count):
if (count < 0): raise ValueError if (self._bits == 0): data = self._fileobj.read(count) if (len(data) != count): raise BitReaderError('not enough data') return data return bytes(bytearray((self.bits(8) for _ in xrange(count))))
'Skip `count` bits. Might raise BitReaderError if there wasn\'t enough data to skip, but might also fail on the next bits() instead.'
def skip(self, count):
if (count < 0): raise ValueError if (count <= self._bits): self.bits(count) else: count -= self.align() n_bytes = (count // 8) self._fileobj.seek(n_bytes, 1) count -= (n_bytes * 8) self.bits(count)
'Returns the amount of bits read or skipped so far'
def get_position(self):
return (((self._fileobj.tell() - self._pos) * 8) - self._bits)
'Align to the next byte, returns the amount of bits skipped'
def align(self):
bits = self._bits self._buffer = 0 self._bits = 0 return bits
'If we are currently aligned to bytes and nothing is buffered'
def is_aligned(self):
return (self._bits == 0)
'Raises SMFError'
def __init__(self, fileobj):
self.length = _read_midi_length(fileobj)
'Register a new key mapping. A key mapping is four functions, a getter, setter, deleter, and lister. The key may be either a string or a glob pattern. The getter, deleted, and lister receive an ID3 instance and the requested key name. The setter also receives the desired value, which will be a list of strings. The gett...
@classmethod def RegisterKey(cls, key, getter=None, setter=None, deleter=None, lister=None):
key = key.lower() if (getter is not None): cls.Get[key] = getter if (setter is not None): cls.Set[key] = setter if (deleter is not None): cls.Delete[key] = deleter if (lister is not None): cls.List[key] = lister
'Register a text key. If the key you need to register is a simple one-to-one mapping of ID3 frame name to EasyID3 key, then you can use this function:: EasyID3.RegisterTextKey("title", "TIT2")'
@classmethod def RegisterTextKey(cls, key, frameid):
def getter(id3, key): return list(id3[frameid]) def setter(id3, key, value): try: frame = id3[frameid] except KeyError: id3.add(mutagen.id3.Frames[frameid](encoding=3, text=value)) else: frame.encoding = 3 frame.text = value def...
'Register a user-defined text frame key. Some ID3 tags are stored in TXXX frames, which allow a freeform \'description\' which acts as a subkey, e.g. TXXX:BARCODE.:: EasyID3.RegisterTXXXKey(\'barcode\', \'BARCODE\').'
@classmethod def RegisterTXXXKey(cls, key, desc):
frameid = ('TXXX:' + desc) def getter(id3, key): return list(id3[frameid]) def setter(id3, key, value): enc = 0 for v in value: if (v and (max(v) > u'\x7f')): enc = 3 break id3.add(mutagen.id3.TXXX(encoding=enc, text=value, desc=des...
'save(filething=None, v1=1, v2_version=4, v23_sep=\'/\', padding=None) Save changes to a file. See :meth:`mutagen.id3.ID3.save` for more info.'
@loadfile(writable=True, create=True) def save(self, filething, v1=1, v2_version=4, v23_sep='/', padding=None):
if (v2_version == 3): backup = self.__id3._copy() try: self.__id3.update_to_v23() self.__id3.save(filething, v1=v1, v2_version=v2_version, v23_sep=v23_sep, padding=padding) finally: self.__id3._restore(backup) else: self.__id3.save(filething, v...
'Print tag key=value pairs.'
def pprint(self):
strings = [] for key in sorted(self.keys()): values = self[key] for value in values: strings.append(('%s=%s' % (key, value))) return '\n'.join(strings)
'The default implementation which tries to select a reasonable amount of padding and which might change in future versions. Returns: int: Amount of padding after saving'
def get_default_padding(self):
high = ((1024 * 10) + (self.size // 100)) low = (1024 + (self.size // 1000)) if (self.padding >= 0): if (self.padding > high): return low return self.padding else: return low