docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Return a list of nets that used only by the vms in vms_to_stop Args: vms_to_stop (list of str): The names of the requested vms Returns list of virt.Network: net objects that used only by vms in vms_to_stop Raises: utils.LagoUserException: If a ...
def _get_unused_nets(self, vms_to_stop): vm_names = [vm.name() for vm in vms_to_stop] unused_nets = set() for vm in vms_to_stop: unused_nets = unused_nets.union(vm.nets()) for vm in self._vms.values(): if not vm.running() or vm.name() in vm_names: ...
559,409
Returns the vm objects associated with vm_names if vm_names is None, return all the vms in the prefix Args: vm_names (list of str): The names of the requested vms Returns dict: Which contains the requested vm objects indexed by name Raises: utils.LagoU...
def get_vms(self, vm_names=None): if not vm_names: return self._vms.copy() missing_vms = [] vms = {} for name in vm_names: try: vms[name] = self._vms[name] except KeyError: # TODO: add resolver by suffix ...
559,413
Get the list of snapshots for each domain Args: domanins(list of str): list of the domains to get the snapshots for, all will be returned if none or empty list passed Returns: dict of str -> list(str): with the domain names and the list of snapshots for ea...
def get_snapshots(self, domains=None): snapshots = {} for vm_name, vm in self.get_vms().items(): if domains and vm_name not in domains: continue snapshots[vm_name] = vm._spec['snapshots'] return snapshots
559,418
Initializes a workdir by adding a new prefix to the workdir. Args: prefix_name(str): Name of the new prefix to add *args: args to pass along to the prefix constructor *kwargs: kwargs to pass along to the prefix constructor Returns: The newly created pref...
def initialize(self, prefix_name='default', *args, **kwargs): if self.loaded: raise WorkdirError('Workdir %s already initialized' % self.path) if not os.path.exists(self.path): LOGGER.debug('Creating workdir %s', self.path) os.makedirs(self.path) se...
559,421
Change the current default prefix, for internal usage Args: new_current(str): Name of the new current prefix, it must already exist Returns: None Raises: PrefixNotFound: if the given prefix name does not exist in the workdir
def _set_current(self, new_current): new_cur_full_path = self.join(new_current) if not os.path.exists(new_cur_full_path): raise PrefixNotFound( 'Prefix "%s" does not exist in workdir %s' % (new_current, self.path) ) if os.path.lex...
559,424
Adds a new prefix to the workdir. Args: name(str): Name of the new prefix to add *args: args to pass along to the prefix constructor *kwargs: kwargs to pass along to the prefix constructor Returns: The newly created prefix Raises: La...
def add_prefix(self, name, *args, **kwargs): if os.path.exists(self.join(name)): raise LagoPrefixAlreadyExistsError(name, self.path) self.prefixes[name] = self.prefix_class( self.join(name), *args, **kwargs ) self.prefixes[name].initialize() if s...
559,425
Retrieve a prefix, resolving the current one if needed Args: name(str): name of the prefix to retrieve, or current to get the current one Returns: self.prefix_class: instance of the prefix with the given name
def get_prefix(self, name): if name == 'current': name = self.current try: return self.prefixes[name] except KeyError: raise KeyError( 'Unable to find prefix "%s" in workdir %s' % (name, self.path) )
559,426
Destroy all the given prefixes and remove any left files if no more prefixes are left Args: prefix_names(list of str): list of prefix names to destroy, if None passed (default) will destroy all of them
def destroy(self, prefix_names=None): if prefix_names is None: self.destroy(prefix_names=self.prefixes.keys()) return for prefix_name in prefix_names: if prefix_name == 'current' and self.current in prefix_names: continue elif pr...
559,427
Look for an existing workdir in the given path, in a path/.lago dir, or in a .lago dir under any of it's parent directories Args: start_path (str): path to start the search from, if None passed, it will use the current dir Returns: str: path to the found...
def resolve_workdir_path(cls, start_path=os.curdir): if start_path == 'auto': start_path = os.curdir cur_path = start_path LOGGER.debug( 'Checking if %s is a workdir', os.path.abspath(cur_path), ) if cls.is_workdir(cur_path): ...
559,428
A quick method to suggest if the path is a possible workdir. This does not guarantee that the workdir is not malformed, only that by simple heuristics it might be one. For a full check use :func:`is_workdir`. Args: path(str): Path Returns: bool: True if ...
def is_possible_workdir(path): res = False trails = ['initialized', 'uuid'] try: res = all( os.path.isfile(os.path.join(path, 'current', trail)) for trail in trails ) except: pass return res
559,429
Check if the given path is a workdir Args: path(str): Path to check Return: bool: True if the given path is a workdir
def is_workdir(cls, path): try: cls(path=path).load() except MalformedWorkdir: return False return True
559,430
Loads all the plugins for the given namespace Args: namespace(str): Namespace string, as in the setuptools entry_points instantiate(bool): If true, will instantiate the plugins too Returns: dict of str, object: Returns the list of loaded plugins
def _load_plugins(namespace, instantiate=True): mgr = ExtensionManager( namespace=namespace, on_load_failure_callback=( lambda _, ep, err: LOGGER. warning('Could not load plugin {}: {}'.format(ep.name, err)) ) ) if instantiate: plugins = dict( ...
559,434
Given a configuration specification, initializes all the net definitions in it so they can be used comfortably Args: conf (dict): Configuration specification Returns: dict: the adapted new conf
def _init_net_specs(conf): for net_name, net_spec in conf.get('nets', {}).items(): net_spec['name'] = net_name net_spec['mapping'] = {} net_spec.setdefault('type', 'nat') return conf
559,442
Allocate all the subnets needed by the given configuration spec Args: conf (dict): Configuration spec where to get the nets definitions from Returns: tuple(list, dict): allocated subnets and modified conf
def _allocate_subnets(self, conf): allocated_subnets = [] try: for net_spec in conf.get('nets', {}).itervalues(): if net_spec['type'] != 'nat': continue gateway = net_spec.get('gw') if gateway: ...
559,443
Select management networks. If no management network is found, it will mark the first network found by sorted the network lists. Also adding default DNS domain, if none is set. Args: conf(spec): spec
def _select_mgmt_networks(self, conf): nets = conf['nets'] mgmts = sorted( [ name for name, net in nets.iteritems() if net.get('management') is True ] ) if len(mgmts) == 0: mgmt_name = sorted((nets.keys()))[0]...
559,445
Add DNS records dict('dns_records') to ``conf`` for each management network. Add DNS forwarder IP('dns_forward') for each none management network. Args: conf(spec): spec mgmts(list): management networks names Returns: None
def _add_dns_records(self, conf, mgmts): nets = conf['nets'] dns_mgmt = mgmts[-1] LOGGER.debug('Using network %s as main DNS server', dns_mgmt) forward = conf['nets'][dns_mgmt].get('gw') dns_records = {} for net_name, net_spec in nets.iteritems(): dn...
559,446
Parse all the domains in the given conf and preallocate all their ips into the networks mappings, raising exception on duplicated ips or ips out of the allowed ranges See Also: :mod:`lago.subnet_lease` Args: conf (dict): Configuration spec to parse Retu...
def _register_preallocated_ips(self, conf): for dom_name, dom_spec in conf.get('domains', {}).items(): for idx, nic in enumerate(dom_spec.get('nics', [])): if 'ip' not in nic: continue net = conf['nets'][nic['net']] if sel...
559,447
For all the nics of all the domains in the conf that have dynamic ip, allocate one and addit to the network mapping Args: conf (dict): Configuration spec to extract the domains from Returns: None
def _allocate_ips_to_nics(self, conf): for dom_name, dom_spec in conf.get('domains', {}).items(): for idx, nic in enumerate(dom_spec.get('nics', [])): if 'ip' in nic: continue net = self._get_net(conf, dom_name, nic) if net...
559,449
For all the nics of all the domains in the conf that have MTU set, save the MTU on the NIC definition. Args: conf (dict): Configuration spec to extract the domains from Returns: None
def _set_mtu_to_nics(self, conf): for dom_name, dom_spec in conf.get('domains', {}).items(): for idx, nic in enumerate(dom_spec.get('nics', [])): net = self._get_net(conf, dom_name, nic) mtu = net.get('mtu', 1500) if mtu != 1500: ...
559,450
Initialize and populate all the network related elements, like reserving ips and populating network specs of the given confiiguration spec Args: conf (dict): Configuration spec to initalize Returns: None
def _config_net_topology(self, conf): conf = self._init_net_specs(conf) mgmts = self._select_mgmt_networks(conf) self._validate_netconfig(conf) allocated_subnets, conf = self._allocate_subnets(conf) try: self._add_mgmt_to_domains(conf, mgmts) self...
559,451
Add management network key('mgmt_net') to each domain. Note this assumes ``conf`` was validated. Args: conf(dict): spec mgmts(list): list of management networks names
def _add_mgmt_to_domains(self, conf, mgmts): for dom_name, dom_spec in conf['domains'].iteritems(): domain_mgmt = [ nic['net'] for nic in dom_spec['nics'] if nic['net'] in mgmts ].pop() dom_spec['mgmt_net'] = domain_mgmt
559,452
Validate network configuration Args: conf(dict): spec Returns: None Raises: :exc:`~lago.utils.LagoInitException`: If a VM has more than one management network configured, or a network which is not management has DNS attributes, or a...
def _validate_netconfig(self, conf): nets = conf.get('nets', {}) if len(nets) == 0: # TO-DO: add default networking if no network is configured raise LagoInitException('No networks configured.') no_mgmt_dns = [ name for name, net in nets.iteritems()...
559,453
Populates the given spec with the values of it's declared prototype Args: spec (dict): spec to update prototypes (dict): Configuration spec containing the prototypes Returns: dict: updated spec
def _use_prototype(self, spec, prototypes): prototype = spec['based-on'] del spec['based-on'] for attr in prototype: if attr not in spec: spec[attr] = copy.deepcopy(prototype[attr]) return spec
559,466
Retrieves the given url to the prefix Args: url(str): Url to retrieve Returns: str: path to the downloaded file
def fetch_url(self, url): url_path = urlparse.urlsplit(url).path dst_path = os.path.basename(url_path) dst_path = self.paths.prefixed(dst_path) with LogTask('Downloading %s' % url): urllib.urlretrieve(url=os.path.expandvars(url), filename=dst_path) return ds...
559,467
Initializes all the virt infrastructure of the prefix, creating the domains disks, doing any network leases and creating all the virt related files and dirs inside this prefix. Args: conf_fd (File): File like object to read the config from template_repo (TemplateReposito...
def virt_conf_from_stream( self, conf_fd, template_repo=None, template_store=None, do_bootstrap=True, do_build=True, ): virt_conf = utils.load_virt_stream(conf_fd) LOGGER.debug('Loaded virt config:\n%s', virt_conf) return self.virt_con...
559,468
Shutdown this prefix Args: vm_names(list of str): List of the vms to shutdown reboot(bool): If true, reboot the requested vms Returns: None
def shutdown(self, vm_names=None, reboot=False): self.virt_env.shutdown(vm_names, reboot)
559,476
Look for an existing prefix in the given path, in a path/.lago dir, or in a .lago dir under any of it's parent directories Args: start_path (str): path to start the search from, if None passed, it will use the current dir Returns: str: path to the found ...
def resolve_prefix_path(cls, start_path=None): if not start_path or start_path == 'auto': start_path = os.path.curdir cur_path = start_path LOGGER.debug('Checking if %s is a prefix', os.path.abspath(cur_path)) if cls.is_prefix(cur_path): return os.path.a...
559,479
Check if a path is a valid prefix Args: path(str): path to be checked Returns: bool: True if the given path is a prefix
def is_prefix(cls, path): lagofile = paths.Paths(path).prefix_lagofile() return os.path.isfile(lagofile)
559,480
Temporary method to retrieve the host scripts TODO: remove once the "ovirt-scripts" option gets deprecated Args: host_metadata(dict): host metadata to retrieve the scripts for Returns: list: deploy scripts for the host, empty if none found
def _get_scripts(self, host_metadata): deploy_scripts = host_metadata.get('deploy-scripts', []) if deploy_scripts: return deploy_scripts ovirt_scripts = host_metadata.get('ovirt-scripts', []) if ovirt_scripts: warnings.warn( 'Deprecated e...
559,482
Temporary method to set the host scripts TODO: remove once the "ovirt-scripts" option gets deprecated Args: host_metadata(dict): host metadata to set scripts in Returns: dict: the updated metadata
def _set_scripts(self, host_metadata, scripts): scripts_key = 'deploy-scripts' if 'ovirt-scritps' in host_metadata: scripts_key = 'ovirt-scripts' host_metadata[scripts_key] = scripts return host_metadata
559,483
Copy the deploy scripts for all the domains into the prefix scripts dir Args: domains(dict): spec with the domains info as when loaded from the initfile Returns: None
def _copy_deploy_scripts_for_hosts(self, domains): with LogTask('Copying any deploy scripts'): for host_name, host_spec in domains.iteritems(): host_metadata = host_spec.get('metadata', {}) deploy_scripts = self._get_scripts(host_metadata) new...
559,484
Copy the given deploy scripts to the scripts dir in the prefix Args: scripts(list of str): list of paths of the scripts to copy to the prefix Returns: list of str: list with the paths to the copied scripts, with a prefixed with $LAGO_PREFIX_PATH ...
def _copy_delpoy_scripts(self, scripts): if not os.path.exists(self.paths.scripts()): os.makedirs(self.paths.scripts()) new_scripts = [] for script in scripts: script = os.path.expandvars(script) if not os.path.exists(script): raise R...
559,485
__init__ Args: root_section (str): root section in the init defaults (dict): Default dictonary to load, can be empty.
def __init__(self, root_section='lago', defaults={}): self.root_section = root_section self._defaults = defaults self._config = defaultdict(dict) self._config.update(self.load()) self._parser = None
559,490
Update config dictionary with parsed args, as resolved by argparse. Only root positional arguments that already exist will overridden. Args: args (namespace): args parsed by argparse
def update_args(self, args): for arg in vars(args): if self.get(arg) and getattr(args, arg) is not None: self._config[self.root_section][arg] = getattr(args, arg)
559,492
Update config dictionary with declared arguments in an argparse.parser New variables will be created, and existing ones overridden. Args: parser (argparse.ArgumentParser): parser to read variables from
def update_parser(self, parser): self._parser = parser ini_str = argparse_to_ini(parser) configp = configparser.ConfigParser(allow_no_value=True) configp.read_dict(self._config) configp.read_string(ini_str) self._config.update( {s: dict(configp.items...
559,493
Return the config dictionary in INI format Args: incl_unset (bool): include variables with no defaults. Returns: str: string of the config file in INI format
def get_ini(self, incl_unset=False): configp = configparser.ConfigParser(allow_no_value=True) configp.read_dict(self._config) with StringIO() as config_ini: if self._parser: self._parser.set_defaults( **self.get_section(self.root_section)...
559,494
Wait until the given UTC timestamp. Args: utcTimeStamp (int): A UTC format timestamp. verbose (Optional[bool]): If False, all extra printouts will be suppressed. Defaults to True.
def _awaitReset(self, utcTimeStamp, verbose=True): resetTime = pytz.utc.localize(datetime.utcfromtimestamp(utcTimeStamp)) _vPrint(verbose, "--- Current Timestamp") _vPrint(verbose, " %s" % (time.strftime('%c'))) now = pytz.utc.localize(datetime.utcnow()) waitTime = ...
560,166
Makes a pretty countdown. Args: gitquery (str): The query or endpoint itself. Examples: query: 'query { viewer { login } }' endpoint: '/user' printString (Optional[str]): A counter message to display. Defaults to...
def _countdown(self, waitTime=0, printString="Waiting %*d seconds...", verbose=True): if waitTime <= 0: waitTime = self.__retryDelay for remaining in range(waitTime, 0, -1): _vPrint(verbose, "\r" + printString % (len(str(waitTime)), remaining), end="", flush=True) ...
560,167
Initialize the DataManager object. Args: filePath (Optional[str]): Relative or absolute path to a JSON data file. Defaults to None. loadData (Optional[bool]): Loads data from the given file path if True. Defaults to False.
def __init__(self, filePath=None, loadData=False): self.data = {} self.filePath = filePath if loadData: self.fileLoad(updatePath=False)
560,168
Load a JSON data file into the internal JSON data dictionary. Current internal data will be overwritten. If no file path is provided, the stored data file path will be used. Args: filePath (Optional[str]): A relative or absolute path to a '.json' file. Defaults to N...
def fileLoad(self, filePath=None, updatePath=True): if not filePath: filePath = self.filePath if not os.path.isfile(filePath): raise FileNotFoundError("Data file '%s' does not exist." % (filePath)) else: print("Importing existing data file '%s' ... " ...
560,170
Write the internal JSON data dictionary to a JSON data file. If no file path is provided, the stored data file path will be used. Args: filePath (Optional[str]): A relative or absolute path to a '.json' file. Defaults to None. updatePath (Optional[bool]): Specif...
def fileSave(self, filePath=None, updatePath=False): if not filePath: filePath = self.filePath if not os.path.isfile(filePath): print("Data file '%s' does not exist, will create new file." % (filePath)) if not os.path.exists(os.path.split(filePath)[0]): ...
560,171
Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the command for (default is all) Designed to be ran like: fab <role> dj.manage_async:"some_management_command --fo...
def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''): exclude_sites = exclude_sites.split(':') r = self.local_renderer for _site, site_data in self.iter_sites(site=site, no_secure=True): if _site in exclude_sites: ...
560,770
Initialize per-spider RabbitMQ queue. Parameters: server -- rabbitmq connection spider -- spider instance key -- key for this queue (e.g. "%(spider)s:queue")
def __init__(self, server, spider, key, exchange=None): self.server = server self.spider = spider self.key = key % {'spider': spider.name}
561,434
Select the image with the minimum distance Args: key: (see mapper) values: (see mapper) Yields: A tuple in the form of (key, value) key: Image name value: Image as jpeg byte data
def reduce(self, key, values): dist, key, value = min(values, key=lambda x: x[0]) print('MinDist[%f]' % dist) yield key, value
561,573
Return an identification string which uniquely names a manifest. This string is a combination of the manifest's processorArchitecture, name, publicKeyToken, version and language. Arguments: version (tuple or list of integers) - If version is given, use it ...
def getid(self, language=None, version=None): if not self.name: logger.warn("Assembly metadata incomplete") return "" id = [] if self.processorArchitecture: id.append(self.processorArchitecture) id.append(self.name) if self.publicKeyTo...
561,660
Builds the MD5 of a file block by block Args: fn: File path block_size: Size of the blocks to consider (default 1048576) Returns: File MD5
def _md5_file(fn, block_size=1048576): h = hashlib.md5() with open(fn) as fp: d = 1 while d: d = fp.read(block_size) h.update(d) return h.hexdigest()
561,997
Wraps pyinstaller and provides an easy to use interface Args: script_path: Absolute path to python script to be frozen. Returns: List of freeze commands ran Raises: subprocess.CalledProcessError: Freeze error. OSError: Freeze not found.
def freeze(script_path, target_dir='frozen', **kw): cmds = [] freeze_start_time = time.time() logging.debug('/\\%s%s Output%s/\\' % ('-' * 10, 'Pyinstaller', '-' * 10)) orig_dir = os.path.abspath('.') script_path = os.path.abspath(script_path) try: os.chdir(target_dir) cmds ...
562,000
Convert a ``Fact`` to its normalized tuple. This is where all type conversion for ``Fact`` attributes to strings as well as any normalization happens. Note: Because different writers may require different types, we need to do this individually. Args: ...
def _fact_to_tuple(self, fact): # Fields that may have ``None`` value will be represented by '' if fact.category: category = fact.category.name else: category = '' description = fact.description or '' return FactTuple( start=fact.sta...
562,842
Get the day end time given the day start. This assumes full 24h day. Args: config (dict): Configdict. Needed to extract ``day_start``. Note: This is merely a convinience funtion so we do not have to deduct this from ``day_start`` by hand all the time.
def get_day_end(config): day_start_datetime = datetime.datetime.combine(datetime.date.today(), config['day_start']) day_end_datetime = day_start_datetime - datetime.timedelta(seconds=1) return day_end_datetime.time()
562,852
Perform basic sanity checks on a timeframe. Args: range_tuple (tuple): ``(start, end)`` tuple as returned by ``complete_timeframe``. Raises: ValueError: If start > end. Returns: tuple: ``(start, end)`` tuple that passed validation. Note: ``timeframes`` may...
def validate_start_end_range(range_tuple): start, end = range_tuple if (start and end) and (start > end): raise ValueError(_("Start after end!")) return range_tuple
562,857
Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults ...
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): return os.path.join(appdirs.user_config_dir, file_name)
562,973
Write a ConfigParser instance to file at the correct location. Args: config_instance: Config instance to safe to file. appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config ...
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): path = get_config_path(appdirs, file_name) with open(path, 'w') as fobj: config_instance.write(fobj) return config_instance
562,974
Return a default config dictionary. Args: appdirs (HamsterAppDirs): ``HamsterAppDirs`` instance encapsulating the apps details. Returns: dict: Dictionary with a default configuration. Note: Those defaults are independent of the particular config-store.
def get_default_backend_config(appdirs): return { 'store': 'sqlalchemy', 'day_start': datetime.time(5, 30, 0), 'fact_min_delta': 1, 'tmpfile_path': os.path.join(appdirs.user_data_dir, '{}.tmp'.format(appdirs.appname)), 'db_engine': 'sqlite', 'db_path': os.path.jo...
562,976
Return a ConfigParser instance representing a given backend config dictionary. Args: config (dict): Dictionary of config key/value pairs. Returns: SafeConfigParser: SafeConfigParser instance representing config. Note: We do not provide *any* validation about mandatory values what ...
def backend_config_to_configparser(config): def get_store(): return config.get('store') def get_day_start(): day_start = config.get('day_start') if day_start: day_start = day_start.strftime('%H:%M:%S') return day_start def get_fact_min_delta(): retu...
562,977
Load an 'ongoing fact' from a given location. Args: filepath: Full path to the tmpfile location. Returns: hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False`` if no file was found. Raises: TypeError: If for some reason our stored instance is no...
def _load_tmp_fact(filepath): from hamster_lib import Fact try: with open(filepath, 'rb') as fobj: fact = pickle.load(fobj) except IOError: fact = False else: if not isinstance(fact, Fact): raise TypeError(_( "Something went wrong. It...
562,984
Extract semantically meaningful sub-components from a ``raw fact`` text. Args: raw_fact (text_type): ``raw fact`` text to be parsed. Returns: dict: dict with sub-components as values.
def parse_raw_fact(raw_fact): def at_split(string): result = string.split('@', 1) length = len(result) if length == 1: front, back = result[0].strip(), None else: front, back = result front, back = front.strip(), back.strip() ...
562,985
--- parameters: - name: spec in: query type: string - name: version in: query type: integer enum: [2,3]
def _handler_swagger_ui(self, request, spec, version): version = version or self._version_ui if self._spec_url: spec_url = self._spec_url else: spec_url = request.url.with_path(self['swagger:spec'].url()) proto = request.headers.get(hdrs.X_FORWARDED_P...
563,708
Get list of possible currencies for symbol; filter by country_code Look for all currencies that use the `symbol`. If there are currencies used in the country of `country_code`, return only those; otherwise return all found currencies. Parameters: symbol: unicode Currency symbo...
def by_symbol(symbol, country_code=None): res = _data()['symbol'].get(symbol) if res: tmp_res = [] for d in res: if country_code in d.countries: tmp_res += [d] if tmp_res: return tmp_res if country_code is None: return res
564,090
Load and return the corpus from the given path. Args: path (str): Path to the data set to load. Returns: Corpus: The loaded corpus Raises: IOError: When the data set is invalid, for example because required files (annotations, …) are missing.
def load(self, path): # Check for missing files missing_files = self._check_for_missing_files(path) if len(missing_files) > 0: raise IOError('Invalid data set of type {}: files {} not found at {}'.format( self.type(), ' '.join(missing_files), path)) ...
564,146
Reads a ctm file. Args: path (str): Path to the file Returns: (dict): Dictionary with entries. Example:: >>> read_file('/path/to/file.txt') { 'wave-ab': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ], ...
def read_file(path): gen = textfile.read_separated_lines_generator(path, max_columns=6, ignore_lines_starting_with=[';;']) utterances = collections.defaultdict(list) for record in gen: values = record[1:len(record)] for i in range(len...
564,153
Split a given integer into n parts according to len(proportions) so they sum up to count and match the given proportions. Args: proportions (dict): Dict of proportions, with a identifier as key. Returns: dict: Dictionary with absolute proportions and same identifiers as key. Example::...
def absolute_proportions(proportions, count): # first create absolute values by flooring non-integer portions relative_sum = sum(proportions.values()) absolute_proportions = {idx: int(count / relative_sum * prop_value) for idx, prop_value in proportions.items()} # Now ...
564,154
Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment. second_end (float): End of the second segment. Return: float: ...
def length_of_overlap(first_start, first_end, second_start, second_end): if first_end <= second_start or first_start >= second_end: return 0.0 if first_start < second_start: if first_end < second_end: return abs(first_end - second_start) else: return abs(sec...
564,167
Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation.
def remove_punctuation(text, exceptions=[]): all_but = [ r'\w', r'\s' ] all_but.extend(exceptions) pattern = '[^{}]'.format(''.join(all_but)) return re.sub(pattern, '', text)
564,180
Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes,...
def starts_with_prefix_in_list(text, prefixes): for prefix in prefixes: if text.startswith(prefix): return True return False
564,181
Load and filter the audio list. Args: path (str): Path to the audio list file. Returns: dict: Dictionary of filtered sentences (id : username, license, attribution-url)
def _load_audio_list(self, path): result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=4): for i in range(len(entry)): if entry[i] == '\\N': entry[i] = None if len(entry) < 4: ...
564,186
Load and filter the sentence list. Args: path (str): Path to the sentence list. Returns: dict: Dictionary of sentences (id : language, transcription)
def _load_sentence_list(self, path): result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3): if self.include_languages is None or entry[1] in self.include_languages: result[entry[0]] = entry[1:] return result
564,187
Writes data as json to file. Parameters: path (str): Path to write to data (dict, list): Data
def write_json_to_file(path, data): with open(path, 'w', encoding='utf-8') as f: json.dump(data, f)
564,227
Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list.
def read_json_file(path): with open(path, 'r', encoding='utf-8') as f: data = json.load(f) return data
564,228
Add a label to the end of the list. Args: label (Label): The label to add.
def add(self, label): label.label_list = self self.label_tree.addi(label.start, label.end, label)
564,240
Return a list of all tokens occurring in the label-list. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). Returns: :class:`set`: A set of distinct tokens.
def all_tokens(self, delimiter=' '): tokens = set() for label in self: tokens = tokens.union(set(label.tokenized(delimiter=delimiter))) return tokens
564,246
Open the container file. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``.
def open(self, mode=None): if mode is None: mode = self.mode elif mode not in ['r', 'w', 'a']: raise ValueError('Invalid mode! Modes: [\'a\', \'r\', \'w\']') if self._file is None: self._file = h5py.File(self.path, mode=mode)
564,262
Convenience context-manager for the use with ``with``. Opens the container if not already done. Only closes the container if it was opened within this context. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default:...
def open_if_needed(self, mode=None): was_open = self.is_open() if not was_open: self.open(mode=mode) try: yield self finally: if not was_open: self.close()
564,263
Read and return the data stored for the given key. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in ...
def get(self, key, mem_map=True): self.raise_error_if_not_open() if key in self._file: data = self._file[key] if not mem_map: data = data[()] return data else: return None
564,264
Set the given data to the container with the given key. Any existing data for the given key is discarded/overwritten. Args: key (str): A key to store the data for. data (numpy.ndarray): Array-like data. Note: The container has to be opened in advance.
def set(self, key, data): self.raise_error_if_not_open() if key in self._file: del self._file[key] self._file.create_dataset(key, data=data)
564,265
Remove the data stored for the given key. Args: key (str): Key of the data to remove. Note: The container has to be opened in advance.
def remove(self, key): self.raise_error_if_not_open() if key in self._file: del self._file[key]
564,267
Return the number of samples. Args: sr (int): Calculate the number of samples with the given sampling-rate. If None use the native sampling-rate. Returns: int: Number of samples
def num_samples(self, sr=None): native_sr = self.sampling_rate num_samples = units.seconds_to_sample(self.duration, native_sr) if sr is not None: ratio = float(sr) / native_sr num_samples = int(np.ceil(num_samples * ratio)) return num_samples
564,275
Set the given label-list for this utterance. If the label-list-idx is not set, ``default`` is used. If there is already a label-list with the given idx, it will be overriden. Args: label_list (LabelList, list): A single or multi. label-lists to add.
def set_label_list(self, label_lists): if isinstance(label_lists, annotations.LabelList): label_lists = [label_lists] for label_list in label_lists: if label_list.idx is None: label_list.idx = 'default' label_list.utterance = self ...
564,277
Return a set of all label-values occurring in this utterance. Args: label_list_ids (list): If not None, only label-values from label-lists with an id contained in this list are considered. Returns: :class:`s...
def all_label_values(self, label_list_ids=None): values = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: values = values.union(label_list.label_values()) return values
564,278
Return a dictionary containing the number of times, every label-value in this utterance is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered...
def label_count(self, label_list_ids=None): count = collections.defaultdict(int) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_count in label_list.label_count().items(): ...
564,279
Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels ...
def all_tokens(self, delimiter=' ', label_list_ids=None): tokens = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: tokens = tokens.union(label_list.all_tokens(delimiter=delimiter)) return tok...
564,280
Return a dictionary containing the number of seconds, every label-value is occurring in this utterance. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are consider...
def label_total_duration(self, label_list_ids=None): duration = collections.defaultdict(float) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_duration in label_list.label_total_durat...
564,281
Return a set of all label-values occurring in this corpus. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values.
def all_label_values(self, label_list_ids=None): values = set() for utterance in self.utterances.values(): values = values.union(utterance.all_label_values(label_list_ids=label_list_ids)) return values
564,296
Return a dictionary containing the number of times, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictio...
def label_count(self, label_list_ids=None): count = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_count(label_list_ids=label_list_ids).items(): count[label_value] += utt_count return co...
564,297
Return a dictionary containing the total duration, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A diction...
def label_durations(self, label_list_ids=None): duration = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_total_duration(label_list_ids=label_list_ids).items(): duration[label_value] += utt_count...
564,298
Return a list of all tokens occurring in one of the labels in the corpus. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-li...
def all_tokens(self, delimiter=' ', label_list_ids=None): tokens = set() for utterance in self.utterances.values(): tokens = tokens.union(utterance.all_tokens(delimiter=delimiter, label_list_ids=label_list_ids)) return tokens
564,299
Return the samples for the given key and the sampling-rate. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be o...
def get(self, key, mem_map=True): self.raise_error_if_not_open() if key in self._file: data = self._file[key] sampling_rate = data.attrs[SAMPLING_RATE_ATTR] if not mem_map: data = data[()] data = np.float32(data) / MAX_INT16_VAL...
564,318
Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of a...
def set(self, key, samples, sampling_rate): if not np.issubdtype(samples.dtype, np.floating): raise ValueError('Samples are required as np.float32!') if len(samples.shape) > 1: raise ValueError('Only single channel supported!') self.raise_error_if_not_open() ...
564,319
Find a unique name by adding an index to the name so it is unique within the given list. Parameters: name (str): Name name_list (iterable): List of names that the new name must differ from. suffix (str): The suffix to append after the index. prefix (str): The prefix to append in fro...
def index_name_if_in_list(name, name_list, suffix='', prefix=''): new_name = '{}'.format(name) index = 1 while new_name in name_list: new_name = '{}_{}{}{}'.format(name, prefix, index, suffix) index += 1 return new_name
564,332
Generates a random string of lowercase letters with the given length. Parameters: length (int): Length of the string to output. not_in (list): Only return a string not in the given iterator. Returns: str: A new name thats not in the given list.
def generate_name(length=15, not_in=None): value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) while (not_in is not None) and (value in not_in): value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) return value
564,333
Create an instance of the downloader with the given name. Args: type_name: The name of a downloader. Returns: An instance of the downloader with the given type.
def create_downloader_of_type(type_name): downloaders = available_downloaders() if type_name not in downloaders.keys(): raise UnknownDownloaderException('Unknown downloader: %s' % (type_name,)) return downloaders[type_name]()
564,335
Create an instance of the reader with the given name. Args: type_name: The name of a reader. Returns: An instance of the reader with the given type.
def create_reader_of_type(type_name): readers = available_readers() if type_name not in readers.keys(): raise UnknownReaderException('Unknown reader: %s' % (type_name,)) return readers[type_name]()
564,336
Create an instance of the writer with the given name. Args: type_name: The name of a writer. Returns: An instance of the writer with the given type.
def create_writer_of_type(type_name): writers = available_writers() if type_name not in writers.keys(): raise UnknownWriterException('Unknown writer: %s' % (type_name,)) return writers[type_name]()
564,337
Creates a subview from a string representation (created with ``self.serialize``). Args: representation (str): The representation. Returns: Subview: The created subview.
def parse(cls, representation, corpus=None): criteria_definitions = representation.split('\n') criteria = [] for i in range(0, len(criteria_definitions), 2): filter_name = criteria_definitions[i] filter_repr = criteria_definitions[i + 1] if filter_...
564,356
Perform validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate.
def validate(self, corpus): passed = True results = {} for validator in self.validators: sub_result = validator.validate(corpus) results[validator.name()] = sub_result if not sub_result.passed: passed = False return Combine...
564,365
Perform the validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. Returns: InvalidUtterancesResult: Validation result.
def validate(self, corpus): invalid_utterances = {} for utterance in corpus.utterances.values(): duration = utterance.duration ll = utterance.label_lists[self.label_list_idx] # We count the characters of all labels transcription = ' '.join([l.va...
564,370
Perform the validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. Returns: InvalidUtterancesResult: Validation result.
def validate(self, corpus): invalid_utterances = {} for utterance in corpus.utterances.values(): if self.label_list_idx in utterance.label_lists.keys(): ll = utterance.label_lists[self.label_list_idx] if len(ll) < self.min_number_of_labels: ...
564,372
Perform the validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. Returns: InvalidUtterancesResult: Validation result.
def validate(self, corpus): overflow_segments = {} for utterance in corpus.utterances.values(): utt_segments = self.validate_utterance(utterance) if len(utt_segments) > 0: overflow_segments[utterance.idx] = utt_segments passed = len(overflow_s...
564,378
Encode all utterances of the given corpus and store them in a :class:`audiomate.container.Container`. Args: corpus (Corpus): The corpus to process. output_path (str): The path to store the container with the encoded data. Returns: Container: The container with the e...
def encode_corpus(self, corpus, output_path): out_container = containers.Container(output_path) out_container.open() for utterance in corpus.utterances.values(): data = self.encode_utterance(utterance, corpus=corpus) out_container.set(utterance.idx, data) ...
564,395
Load and return the partition with the given index. Args: index (int): The index of partition, that refers to the index in ``self.partitions``. Returns: PartitionData: A PartitionData object containing the data for the partition with the given index.
def load_partition_data(self, index): info = self.partitions[index] data = PartitionData(info) for utt_id in info.utt_ids: utt_data = [c._file[utt_id][:] for c in self.containers] data.utt_data.append(utt_data) return data
564,399
Update the buffer at the given index. Args: data (np.ndarray): The frames. offset (int): The index of the first frame in `data` within the sequence. is_last (bool): Whether this is the last block of frames in the sequence. buffer_index (int): The index of the buf...
def update(self, data, offset, is_last, buffer_index=0): if buffer_index >= self.num_buffers: raise ValueError('Expected buffer index < {} but got index {}.'.format(self.num_buffers, buffer_index)) if self.buffers[buffer_index] is not None and self.buffers[buffer_index].shape[0] > ...
564,416