code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def execute_deployment_script(self, env_file, deploy_file): """Execute post-deployment script if present""" from snakemake.shell import shell if ON_WINDOWS: raise WorkflowError( "Post deploy script {} provided for conda env {} but unsupported on windows.".format( ...
Execute post-deployment script if present
execute_deployment_script
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def shellcmd_win(self, env_address, cmd): """Prepend the windows activate bat script.""" # get path to activate script activate = os.path.join(self.bin_path(), "activate.bat").replace("\\", "/") env_address = env_address.replace("\\", "/") return f'"{activate}" "{env_address}"&&...
Prepend the windows activate bat script.
shellcmd_win
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def shellcmd(self, cmd): """Return shell command with given modules loaded.""" return "module purge && module load {to_load}; {cmd}".format( to_load=" ".join(self.names), cmd=cmd )
Return shell command with given modules loaded.
shellcmd
python
snakemake/snakemake
src/snakemake/deployment/env_modules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/env_modules.py
MIT
def shellcmd( img_path, cmd, args="", quiet=False, envvars=None, shell_executable=None, container_workdir=None, is_python_script=False, ): """Execute shell command inside singularity container given optional args and environment variables to be passed.""" if envvars: ...
Execute shell command inside singularity container given optional args and environment variables to be passed.
shellcmd
python
snakemake/snakemake
src/snakemake/deployment/singularity.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/singularity.py
MIT
def save_files(bucket_name, source_path, destination_path): """given a directory path, save all files recursively to storage""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) # destination path should be stripped of path indicators too bucket_name = bucket_name.st...
given a directory path, save all files recursively to storage
save_files
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def get_source_files(source_path): """Given a directory, return a listing of files to upload""" filenames = [] if not os.path.exists(source_path): print("%s does not exist!" % source_path) sys.exit(0) for x in os.walk(source_path): for name in glob(os.path.join(x[0], "*")): ...
Given a directory, return a listing of files to upload
get_source_files
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def add_ending_slash(filename): """Since we want to replace based on having an ending slash, ensure it's there""" if not filename.endswith("/"): filename = "%s/" % filename return filename
Since we want to replace based on having an ending slash, ensure it's there
add_ending_slash
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def run_group_job(self, job: GroupJobExecutorInterface): """Run a pipe or service group job. This lets all items run simultaneously.""" # we only have to consider pipe or service groups because in local running mode, # these are the only groups that will occur service_futures =...
Run a pipe or service group job. This lets all items run simultaneously.
run_group_job
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def cached_or_run(self, job: SingleJobExecutorInterface, run_func, *args): """ Either retrieve result from cache, or run job with given function. """ cache_mode = self.workflow.get_cache_mode(job.rule) try: if cache_mode: async_run(self.workflow.output...
Either retrieve result from cache, or run job with given function.
cached_or_run
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def run_wrapper( job_rule, input, output, params, wildcards, threads, resources, log, benchmark, benchmark_repeats, benchmark_extended, conda_env, container_img, singularity_args, env_modules, use_singularity, linemaps, debug, cleanup_scripts, ...
Wrapper around the run method that handles exceptions and benchmarking. Arguments job_rule -- the ``job.rule`` member input -- a list of input files output -- a list of output files wildcards -- so far processed wildcards threads -- usable threads log -- a list of...
run_wrapper
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def change_working_directory(directory=None): """Change working directory in execution context if provided.""" if directory: try: saved_directory = os.getcwd() logger.info(f"Changing to shadow directory: {directory}") os.chdir(directory) yield fina...
Change working directory in execution context if provided.
change_working_directory
python
snakemake/snakemake
src/snakemake/executors/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/__init__.py
MIT
def _simple_copy(self): """Identical copy except dictionary keys are downcast to str.""" simplified = type(self)(self.max_wait_time) # Copy non-dictionary attributes the same. for name in ["remaining_wait_time", "active"]: old_attr = getattr(self, name) setattr(s...
Identical copy except dictionary keys are downcast to str.
_simple_copy
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def inventory(self): """Starting from the given file, try to cache as much existence and modification date information of this and other files as possible. """ assert self.rule is not None cache: IOCache = self.rule.workflow.iocache if cache.active: task...
Starting from the given file, try to cache as much existence and modification date information of this and other files as possible.
inventory
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def get_inventory_parent(self): """If eligible for inventory, get the parent of a given path. This code does not work on local Windows paths, but inventory is disabled on Windows. """ if self.is_storage: return self.storage_object.get_inventory_parent() else:...
If eligible for inventory, get the parent of a given path. This code does not work on local Windows paths, but inventory is disabled on Windows.
get_inventory_parent
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None): """Open this file. This can (and should) be used in a `with`-statement. If the file is a remote storage file, retrieve it first if necessary. """ if not os.path.exists(self): raise Inpu...
Open this file. This can (and should) be used in a `with`-statement. If the file is a remote storage file, retrieve it first if necessary.
open
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def protected(self): """Returns True if the file is protected. Always False for symlinks.""" # symlinks are never regarded as protected return ( await self.exists_local() and not os.access(self.file, os.W_OK) and not os.path.islink(self.file) )
Returns True if the file is protected. Always False for symlinks.
protected
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def mtime_uncached(self, skip_storage: bool = False): """Obtain mtime. Usually, this will be one stat call only. For symlinks and directories it will be two, for symlinked directories it will be three, for storage files it will additionally query the storage location. ...
Obtain mtime. Usually, this will be one stat call only. For symlinks and directories it will be two, for symlinked directories it will be three, for storage files it will additionally query the storage location.
mtime_uncached
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def check_broken_symlink(self): """Raise WorkflowError if file is a broken symlink.""" if not await self.exists_local(): try: if os.lstat(self.file): raise WorkflowError( f"File {self.file} seems to be a broken symlink." ...
Raise WorkflowError if file is a broken symlink.
check_broken_symlink
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def is_newer(self, time): """Returns true of the file (which is an input file) is newer than time, or if it is a symlink that points to a file newer than time.""" if self.is_ancient: return False return (await self.mtime()).local_or_storage(follow_symlinks=True) > time
Returns true of the file (which is an input file) is newer than time, or if it is a symlink that points to a file newer than time.
is_newer
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def touch(self, times=None): """times must be 2-tuple: (atime, mtime)""" try: if self.is_directory: file = os.path.join(self.file, ".snakemake_timestamp") # Create the flag file if it doesn't exist if not os.path.exists(file): ...
times must be 2-tuple: (atime, mtime)
touch
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def wait_for_files( files, latency_wait=3, wait_for_local=False, ignore_pipe_or_service=False, consider_local: Set[_IOFile] = _CONSIDER_LOCAL_DEFAULT, ): """Wait for given files to be present in the filesystem.""" from snakemake.io.fmt import fmt_iofile files = list(files) a...
Wait for given files to be present in the filesystem.
wait_for_files
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def directory(value): """ A flag to specify that output is a directory, rather than a file or named pipe. """ if is_flagged(value, "pipe"): raise SyntaxError("Pipe and directory flags are mutually exclusive.") if is_flagged(value, "storage_object"): raise SyntaxError("Storage and dir...
A flag to specify that output is a directory, rather than a file or named pipe.
directory
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def temp(value, group_jobs=False): """ A flag for an input or output file that shall be removed after usage. When set to true, the extra flag "group_jobs" causes the file to also be flagged as "nodelocal": A flag for an intermediate file that only lives on the compute node executing the group jobs and ...
A flag for an input or output file that shall be removed after usage. When set to true, the extra flag "group_jobs" causes the file to also be flagged as "nodelocal": A flag for an intermediate file that only lives on the compute node executing the group jobs and not accessible from the main snakemake job...
temp
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def protected(value): """A flag for a file that shall be write-protected after creation.""" if is_flagged(value, "temp"): raise SyntaxError("Protected and temporary flags are mutually exclusive.") if is_flagged(value, "storage_object"): raise SyntaxError("Storage and protected flags are mutu...
A flag for a file that shall be write-protected after creation.
protected
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def report( value, caption=None, category=None, subcategory=None, labels=None, patterns=[], htmlindex=None, ): """Flag output file or directory as to be included into reports. In the case of a directory, files to include can be specified via a glob pattern (default: *). Argumen...
Flag output file or directory as to be included into reports. In the case of a directory, files to include can be specified via a glob pattern (default: *). Arguments value -- File or directory. caption -- Path to a .rst file with a textual description of the result. category -- Name of the (optio...
report
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def local(value): """Mark a file as a local file. This disables the application of a default storage provider. """ if is_flagged(value, "storage_object"): raise SyntaxError("Storage and local flags are mutually exclusive.") return flag(value, "local")
Mark a file as a local file. This disables the application of a default storage provider.
local
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def expand(*args, **wildcard_values): """ Expand wildcards in given filepatterns. Arguments *args -- first arg: filepatterns as list or one single filepattern, second arg (optional): a function to combine wildcard values (itertools.product per default) **wildcard_values -- the wildc...
Expand wildcards in given filepatterns. Arguments *args -- first arg: filepatterns as list or one single filepattern, second arg (optional): a function to combine wildcard values (itertools.product per default) **wildcard_values -- the wildcards as keyword arguments with their ...
expand
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def multiext(prefix, *extensions, **named_extensions): """Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).""" if any( (r"/" in ext or r"\\" in ext) for ext in chain(extensions, named_extensions.values()) ): raise WorkflowError( r"Extensio...
Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).
multiext
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def glob_wildcards(pattern, files=None, followlinks=False): """ Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard. """ if is_flagged(pattern, "storage_object"): if files is not None: rai...
Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard.
glob_wildcards
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def update_wildcard_constraints( pattern, wildcard_constraints: Dict[str, str], global_wildcard_constraints: Dict[str, str], ): """Update wildcard constraints Args: pattern (str): pattern on which to update constraints wildcard_constraints (dict): dictionary of wildcard:constraint key-v...
Update wildcard constraints Args: pattern (str): pattern on which to update constraints wildcard_constraints (dict): dictionary of wildcard:constraint key-value pairs global_wildcard_constraints (dict): dictionary of wildcard:constraint key-value pairs
update_wildcard_constraints
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def strip_wildcard_constraints(pattern): """Return a string that does not contain any wildcard constraints.""" if is_callable(pattern): # do not apply on e.g. input functions return pattern def strip_constraint(match): return "{{{}}}".format(match.group("name")) return WILDCARD...
Return a string that does not contain any wildcard constraints.
strip_wildcard_constraints
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __call__(self, *args, **kwargs): """ Generic function that throws an `AttributeError`. Used as replacement for functions such as `index()` and `sort()`, which may be overridden by workflows, to signal to a user that these functions should not be used. """ rai...
Generic function that throws an `AttributeError`. Used as replacement for functions such as `index()` and `sort()`, which may be overridden by workflows, to signal to a user that these functions should not be used.
__call__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __init__( self, toclone=None, fromdict=None, plainstr=False, strip_constraints=False, custom_map=None, ): """ Create the object. Arguments toclone -- another Namedlist that shall be cloned fromdict -- a dict that shall be ...
Create the object. Arguments toclone -- another Namedlist that shall be cloned fromdict -- a dict that shall be converted to a Namedlist (keys become names)
__init__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _set_name(self, name, index, end=None): """ Set the name of an item. Arguments name -- a name index -- the item index """ if name not in self._allowed_overrides and hasattr(self.__class__, name): raise AttributeError( "invalid nam...
Set the name of an item. Arguments name -- a name index -- the item index
_set_name
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _get_names(self): """ Get the defined names as (name, index) pairs. """ for name, index in self._names.items(): yield name, index
Get the defined names as (name, index) pairs.
_get_names
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _take_names(self, names): """ Take over the given names. Arguments names -- the given names as (name, index) pairs """ for name, (i, j) in names: self._set_name(name, i, end=j)
Take over the given names. Arguments names -- the given names as (name, index) pairs
_take_names
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __init__(self, min_repeat=20, max_repeat=100): """ Args: max_repeat (int): The maximum length of the periodic substring. min_repeat (int): The minimum length of the periodic substring. """ self.min_repeat = min_repeat self.regex = re.compile( ...
Args: max_repeat (int): The maximum length of the periodic substring. min_repeat (int): The minimum length of the periodic substring.
__init__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def is_periodic(self, value): """Returns the periodic substring or None if not periodic.""" # short-circuit: need at least min_repeat characters if len(value) < self.min_repeat: return None # short-circuit: need at least min_repeat same characters last_letter = value...
Returns the periodic substring or None if not periodic.
is_periodic
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def branch( condition: Union[Callable, bool], then: Optional[Union[str, list[str], Callable]] = None, otherwise: Optional[Union[str, list[str], Callable]] = None, cases: Optional[Mapping] = None, ): """Branch based on a condition that is provided as a function pointer (i.e. a Callable) or a valu...
Branch based on a condition that is provided as a function pointer (i.e. a Callable) or a value. If then and optionally otherwise are specified, do the following: If the condition is (or evaluates to) True, return the value of the then parameter. Otherwise, return the value of the otherwise parameter. ...
branch
python
snakemake/snakemake
src/snakemake/ioutils/branch.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/branch.py
MIT
def evaluate(expr: str): """Evaluate a python expression while replacing any wildcards given as {wildcardname} with the wildcard value represented as a string.""" def inner(wildcards): formatted = expr.format(**{w: repr(v) for w, v in wildcards.items()}) try: return eval(formatt...
Evaluate a python expression while replacing any wildcards given as {wildcardname} with the wildcard value represented as a string.
evaluate
python
snakemake/snakemake
src/snakemake/ioutils/evaluate.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/evaluate.py
MIT
def exists(path): """Return True if the given file or directory exists. This function considers any storage arguments given to Snakemake. """ func_context = inspect.currentframe().f_back.f_locals func_context_global = inspect.currentframe().f_back.f_globals workflow = func_context.get("workflo...
Return True if the given file or directory exists. This function considers any storage arguments given to Snakemake.
exists
python
snakemake/snakemake
src/snakemake/ioutils/exists.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/exists.py
MIT
def flatten(list_of_lists: List) -> List: """Flatten an irregular list of lists recursively https://stackoverflow.com/a/53778278 :param list_of_lists: A list of lists :return result: A list that has been flattened from a list of lists """ result = list() for i in list_of_lists: if ...
Flatten an irregular list of lists recursively https://stackoverflow.com/a/53778278 :param list_of_lists: A list of lists :return result: A list that has been flattened from a list of lists
flatten
python
snakemake/snakemake
src/snakemake/ioutils/input.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/input.py
MIT
def lookup( dpath: Optional[str] = None, query: Optional[str] = None, cols: Optional[Union[List[str], str]] = None, is_nrows: Optional[int] = None, within=None, default=NODEFAULT, **namespace, ): """Lookup values in a pandas dataframe, series, or python mapping (e.g. dict). Required...
Lookup values in a pandas dataframe, series, or python mapping (e.g. dict). Required argument ``within`` should be a pandas dataframe or series (in which case use ``query``, and optionally ``cols`` and ``is_nrows``), or a Python mapping like a dict (in which case use the ``dpath`` argument is used). I...
lookup
python
snakemake/snakemake
src/snakemake/ioutils/lookup.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/lookup.py
MIT
def rule_item_factory(name: str): """Allows to access input, output etc. from statements inside a rule but outside of run/shell etc. blocks. Returns an object that defers evaluation to the DAG phase. """ if name == "threads": def inner(_wildcards, threads): return threads ...
Allows to access input, output etc. from statements inside a rule but outside of run/shell etc. blocks. Returns an object that defers evaluation to the DAG phase.
rule_item_factory
python
snakemake/snakemake
src/snakemake/ioutils/rule_items_proxy.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/rule_items_proxy.py
MIT
def subpath( path_or_func: Union[Callable, str, Path], strip_suffix: Optional[str] = None, basename: bool = False, parent: bool = False, ancestor: Optional[int] = None, ): """Return the subpath of a given path. Args: path_or_func: A string, pathlib.Path, or a function returning a st...
Return the subpath of a given path. Args: path_or_func: A string, pathlib.Path, or a function returning a string or pathlib.Path. strip_suffix: If given, strip the suffix from the path. basename: If True, return the basename of the path (cannot be used together with parent or ancestor). ...
subpath
python
snakemake/snakemake
src/snakemake/ioutils/subpath.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/subpath.py
MIT
def data_uri_from_file(file, defaultenc="utf8"): """Craft a base64 data URI from file with proper encoding and mimetype.""" if isinstance(file, Path): file = str(file) mime, encoding = mime_from_file(file) if encoding is None: encoding = defaultenc with open(file, "rb") as f: ...
Craft a base64 data URI from file with proper encoding and mimetype.
data_uri_from_file
python
snakemake/snakemake
src/snakemake/report/common.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/report/common.py
MIT
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options["uri"] = data_uri_from_file(reference) return result
Image.run() handles most of the
run
python
snakemake/snakemake
src/snakemake/report/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/report/__init__.py
MIT
def log_fmt_shell( self, stdout: bool = True, stderr: bool = True, append: bool = False ) -> str: """ Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers to support optional `log` files specified in the calling rule. If ...
Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers to support optional `log` files specified in the calling rule. If no `log` was specified, then an empty string "" is returned, regardless of the values of `stdout`, `stder...
log_fmt_shell
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _log_shell_redirect( log: Optional[PathLike], stdout: bool = True, stderr: bool = True, append: bool = False, ) -> str: """ Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers support optional `log` files specified in the calling...
Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers support optional `log` files specified in the calling rule. If no `log` was specified, then an empty string "" is returned, regardless of the values of `stdout`, `stderr`, and `append`. ...
_log_shell_redirect
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_list(cls, l): """Encode as vector if the type is homogeneous, otherwise use a list.""" is_homogeneous = False if len(l) == 0: # An empty list is always homogeneous is_homogeneous = True else: # Numbers of different type can be stored in the ...
Encode as vector if the type is homogeneous, otherwise use a list.
encode_list
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def __init__( self, namedlists: List[str] = None, dicts: List[str] = None, prefix: str = "snakemake", ): """namedlists is a list of strings indicating the snakemake object's member variables which are encoded as Namedlist. dicts is a list of strings indicating...
namedlists is a list of strings indicating the snakemake object's member variables which are encoded as Namedlist. dicts is a list of strings indicating the snakemake object's member variables that are encoded as dictionaries. Prefix is the prefix for the bash variable name(s) e.g., snak...
__init__
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_snakemake(self, smk: Snakemake) -> str: """Turn a snakemake object into a collection of bash associative arrays""" arrays = [] main_aa = dict() for var in vars(smk): val = getattr(smk, var) suffix = "params" if var == "_params_store" else var.strip("_")...
Turn a snakemake object into a collection of bash associative arrays
encode_snakemake
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def dict_to_aa(d: dict) -> str: """Converts a dictionary to a Bash associative array This produces the array component of the variable. e.g. ( [var1]=val1 [var2]=val2 ) to make it a correct bash associative array, you need to name it with name=<output of this method> """ ...
Converts a dictionary to a Bash associative array This produces the array component of the variable. e.g. ( [var1]=val1 [var2]=val2 ) to make it a correct bash associative array, you need to name it with name=<output of this method>
dict_to_aa
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_namedlist(cls, named_list: io_.Namedlist) -> str: """Convert a namedlist into a Bash associative array See the comments for dict_to_aa() """ nl_dict = dict() # Add the same items keyed by name and also by index for i, (name, val) in enumerate(named_list._allit...
Convert a namedlist into a Bash associative array See the comments for dict_to_aa()
encode_namedlist
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def combine_preamble_and_source(self, preamble: str) -> str: """The manifest info needs to be moved to before the preamble. Also, because rust-scipt relies on inner docs, there can't be an empty line between the manifest and preamble. """ manifest, src = RustScript.extract_manife...
The manifest info needs to be moved to before the preamble. Also, because rust-scipt relies on inner docs, there can't be an empty line between the manifest and preamble.
combine_preamble_and_source
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _strip_shebang(src: str) -> Tuple[str, str]: """From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L312-L320""" rgx = re.compile(r"^#![^\[].*?(\r\n|\n)") return strip_re(rgx, src)
From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L312-L320
_strip_shebang
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _strip_manifest(src: str) -> Tuple[str, str]: """From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L405-L411""" manifest, remainder = RustScript._strip_single_line_manifest(src) if not manifest: manifest, remainder = RustSc...
From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L405-L411
_strip_manifest
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _strip_single_line_manifest(src: str) -> Tuple[str, str]: """From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L618-L632""" rgx = re.compile(r"^\s*//\s*cargo-deps\s*:(.*?)(\r\n|\n)", flags=re.IGNORECASE) return strip_re(rgx, src)
From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L618-L632
_strip_single_line_manifest
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _strip_code_block_manifest(src: str) -> Tuple[str, str]: """From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L634-L664 We need to find the first `/*!` or `//!` that *isn't* preceded by something that would make it apply to anything ot...
From https://github.com/fornwall/rust-script/blob/ce508bad02a11d574657d2f1debf7e73fca2bf6e/src/manifest.rs#L634-L664 We need to find the first `/*!` or `//!` that *isn't* preceded by something that would make it apply to anything other than the create itself. Because we can't do this accurately,...
_strip_code_block_manifest
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def strip_re(regex: Pattern, s: str) -> Tuple[str, str]: """Strip a substring matching a regex from a string and return the stripped part and the remainder of the original string. Returns an empty string and the original string if the regex is not found """ rgx = re.compile(regex) match = rgx.se...
Strip a substring matching a regex from a string and return the stripped part and the remainder of the original string. Returns an empty string and the original string if the regex is not found
strip_re
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def get_batch(self, items: list): """Return the defined batch of the given items. Items are usually input files.""" # make sure that we always consider items in the same order if len(items) < self.batches: raise WorkflowError( "Batching rule {} has less input ...
Return the defined batch of the given items. Items are usually input files.
get_batch
python
snakemake/snakemake
src/snakemake/settings/types.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/settings/types.py
MIT
def generate(dag, path: Path, deploy=["conda", "singularity"], configfiles=None): """Generate unit tests from given dag at a given path.""" logger.info("Generating unit tests for each rule...") try: from jinja2 import Environment, PackageLoader except ImportError: raise WorkflowError( ...
Generate unit tests from given dag at a given path.
generate
python
snakemake/snakemake
src/snakemake/unit_tests/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/unit_tests/__init__.py
MIT
def get_expected_files(results_dir): """Recursively walk through the expected-results directory to enumerate all expected files.""" return [ os.path.relpath(f, results_dir) for f in glob.iglob(os.path.join(results_dir, "**/**"), recursive=True) if not os.path.isdir(f) ]
Recursively walk through the expected-results directory to enumerate all expected files.
get_expected_files
python
snakemake/snakemake
tests/common.py
https://github.com/snakemake/snakemake/blob/master/tests/common.py
MIT
def run( path, shouldfail=False, snakefile="Snakefile", subpath=None, no_tmpdir=False, check_md5=True, check_results=None, cores=3, nodes=None, set_pythonpath=True, cleanup=True, conda_frontend="conda", config=dict(), targets=set(), container_image=os.environ....
Test the Snakefile in the path. There must be a Snakefile in the path and a subdirectory named expected-results. If cleanup is False, we return the temporary directory to the calling test for inspection, and the test should clean it up.
run
python
snakemake/snakemake
tests/common.py
https://github.com/snakemake/snakemake/blob/master/tests/common.py
MIT
def reset_paths_between_tests(): """Ensure that changes to sys.path are reset between tests""" org_path = sys.path.copy() yield sys.path = org_path
Ensure that changes to sys.path are reset between tests
reset_paths_between_tests
python
snakemake/snakemake
tests/conftest.py
https://github.com/snakemake/snakemake/blob/master/tests/conftest.py
MIT
def test_github_issue_14(): """Add cleanup_scripts argument to allow the user to keep scripts""" # Return temporary directory for inspection - we should keep scripts here tmpdir = run(dpath("test_github_issue_14"), cleanup=False, cleanup_scripts=False) assert os.listdir(os.path.join(tmpdir, ".snakemake"...
Add cleanup_scripts argument to allow the user to keep scripts
test_github_issue_14
python
snakemake/snakemake
tests/tests.py
https://github.com/snakemake/snakemake/blob/master/tests/tests.py
MIT
def test_empty_pattern_matches_everything(mocker): """Test that empty patterns match any filename""" rule = mocker.Mock( products=lambda: [Mock(constant_prefix=lambda: "", constant_suffix=lambda: "")] ) output_index = OutputIndex([rule]) assert rule in output_index.match("") assert rule ...
Test that empty patterns match any filename
test_empty_pattern_matches_everything
python
snakemake/snakemake
tests/test_output_index.py
https://github.com/snakemake/snakemake/blob/master/tests/test_output_index.py
MIT
def test_empty_prefix_and_suffix(mocker): """Test with empty prefix and suffix""" rule = mocker.Mock( products=lambda: [Mock(constant_prefix=lambda: "", constant_suffix=lambda: "")] ) output_index = OutputIndex([rule]) matches = output_index.match("anything.txt") assert rule in matches
Test with empty prefix and suffix
test_empty_prefix_and_suffix
python
snakemake/snakemake
tests/test_output_index.py
https://github.com/snakemake/snakemake/blob/master/tests/test_output_index.py
MIT
def test_parametrized_matches(mocker, target, expected_match): """Parametrized test for various matching scenarios""" rule = mocker.Mock( products=lambda: [ Mock(constant_prefix=lambda: "test", constant_suffix=lambda: "txt") ] ) output_index = OutputIndex([rule]) matches ...
Parametrized test for various matching scenarios
test_parametrized_matches
python
snakemake/snakemake
tests/test_output_index.py
https://github.com/snakemake/snakemake/blob/master/tests/test_output_index.py
MIT
def test_prefix_matching_non_consecutive(): """Test that demonstrates why we need to keep checking even after seeing a longer prefix, when prefixes aren't consecutive (like 'ab' vs 'abbc').""" lookup = PrefixLookup([("a", 1), ("ab", 2), ("abbcc", 3), ("abbc", 4), ("abbd", 5)]) # Query "abbz" process: ...
Test that demonstrates why we need to keep checking even after seeing a longer prefix, when prefixes aren't consecutive (like 'ab' vs 'abbc').
test_prefix_matching_non_consecutive
python
snakemake/snakemake
tests/test_prefix_lookup.py
https://github.com/snakemake/snakemake/blob/master/tests/test_prefix_lookup.py
MIT
def test_named_list_one_named_one_str(self): """InputFiles is a subclass of snakemake.io.NamedInput ierate over input and store each with the integer index - i.e 0, 1, 2 then use input.items() to iterate over the named files and store them as named also check how this works with named th...
InputFiles is a subclass of snakemake.io.NamedInput ierate over input and store each with the integer index - i.e 0, 1, 2 then use input.items() to iterate over the named files and store them as named also check how this works with named things being lists
test_named_list_one_named_one_str
python
snakemake/snakemake
tests/test_script.py
https://github.com/snakemake/snakemake/blob/master/tests/test_script.py
MIT
def test_named_list_named_is_list(self): """Named lists that are lists of files become a space-separated string as you can't nest arrays in bash""" named_list = InputFiles(["test1.in", ["test2.in", "named.in"]]) named_list._set_name("named", 1) actual = BashEncoder.encode_namedl...
Named lists that are lists of files become a space-separated string as you can't nest arrays in bash
test_named_list_named_is_list
python
snakemake/snakemake
tests/test_script.py
https://github.com/snakemake/snakemake/blob/master/tests/test_script.py
MIT
def append( self: "ContentSequence", part_or_parts: Union[BasePart, List[BasePart]], add_end: bool = False, speaker: Union[str, int] | None = None, ): """ Append a part or list of parts to the sequence. Args: part_or_parts: A single part or list o...
Append a part or list of parts to the sequence. Args: part_or_parts: A single part or list of parts to add add_end: Whether to add the IM_END_TOKEN after these parts speaker: Optional speaker identifier (name or ID) to add before the parts
append
python
fishaudio/fish-speech
fish_speech/content_sequence.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/content_sequence.py
Apache-2.0
def encode( self: "ContentSequence", tokenizer: FishTokenizer, add_shift: bool = True, ignore_loss_tokens: list[str] = [], ) -> EncodedMessage: """ Encode the sequence parts into tokens for the model. Args: tokenizer: The tokenizer to use ...
Encode the sequence parts into tokens for the model. Args: tokenizer: The tokenizer to use add_shift: Whether to shift tokens for next-token prediction ignore_loss_tokens: List of token strings to ignore when calculating loss Returns: EncodedMes...
encode
python
fishaudio/fish-speech
fish_speech/content_sequence.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/content_sequence.py
Apache-2.0
def visualize( self: "ContentSequence", tokenizer: FishTokenizer, ignore_loss_tokens: list[str] = [], merge_semantic_tokens: bool = False, ): """ Visualize the encoded sequence with color-coded tokens. Blue/cyan tokens contribute to loss, green tokens do not. ...
Visualize the encoded sequence with color-coded tokens. Blue/cyan tokens contribute to loss, green tokens do not.
visualize
python
fishaudio/fish-speech
fish_speech/content_sequence.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/content_sequence.py
Apache-2.0
def __init__(self) -> None: """ Component of the TTSInferenceEngine class. Loads and manages the cache for the reference audio and text. """ self.ref_by_id: dict = {} self.ref_by_hash: dict = {} # Make Pylance happy (attribut/method not defined...) self.d...
Component of the TTSInferenceEngine class. Loads and manages the cache for the reference audio and text.
__init__
python
fishaudio/fish-speech
fish_speech/inference_engine/reference_loader.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/inference_engine/reference_loader.py
Apache-2.0
def load_audio(self, reference_audio, sr): """ Load the audio data from a file or bytes. """ if len(reference_audio) > 255 or not Path(reference_audio).exists(): audio_data = reference_audio reference_audio = io.BytesIO(audio_data) waveform, original_sr =...
Load the audio data from a file or bytes.
load_audio
python
fishaudio/fish-speech
fish_speech/inference_engine/reference_loader.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/inference_engine/reference_loader.py
Apache-2.0
def inference(self, req: ServeTTSRequest) -> Generator[InferenceResult, None, None]: """ Main inference function: - Loads the reference audio and text. - Calls the LLAMA model for inference. - Decodes the VQ tokens to audio. """ ref_id: str | None = req.reference...
Main inference function: - Loads the reference audio and text. - Calls the LLAMA model for inference. - Decodes the VQ tokens to audio.
inference
python
fishaudio/fish-speech
fish_speech/inference_engine/__init__.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/inference_engine/__init__.py
Apache-2.0
def send_Llama_request( self, req: ServeTTSRequest, prompt_tokens: list, prompt_texts: list ) -> queue.Queue: """ Send a request to the LLAMA model to generate the symbolic tokens. """ # Prepare the request request = dict( device=self.decoder_model.device...
Send a request to the LLAMA model to generate the symbolic tokens.
send_Llama_request
python
fishaudio/fish-speech
fish_speech/inference_engine/__init__.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/inference_engine/__init__.py
Apache-2.0
def get_audio_segment(self, result: GenerateResponse) -> np.ndarray: """ Decode the VQ tokens to audio. """ # Don't use autocast on MPS devices with autocast_exclude_mps( device_type=self.decoder_model.device.type, dtype=self.precision ): # Decode...
Decode the VQ tokens to audio.
get_audio_segment
python
fishaudio/fish-speech
fish_speech/inference_engine/__init__.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/inference_engine/__init__.py
Apache-2.0
def setup_caches(self, max_batch_size, max_seq_length): """ This method will only be called during inference when using KV cache. """ head_dim = self.config.dim // self.config.n_head max_seq_length = find_multiple(max_seq_length, 8) self.max_seq_length = max_seq_length ...
This method will only be called during inference when using KV cache.
setup_caches
python
fishaudio/fish-speech
fish_speech/models/dac/modded_dac.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/models/dac/modded_dac.py
Apache-2.0
def make_mask( self, max_length: int, x_lens: Optional[Tensor] = None, ) -> Tensor: """ Make ordinary mask if window size is not specified. """ if self.causal: mask = torch.tril(torch.ones(max_length, max_length)) else: mask = t...
Make ordinary mask if window size is not specified.
make_mask
python
fishaudio/fish-speech
fish_speech/models/dac/modded_dac.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/models/dac/modded_dac.py
Apache-2.0
def pad1d( x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = "zeros", value: float = 0.0, ): """Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen. """ length =...
Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen.
pad1d
python
fishaudio/fish-speech
fish_speech/models/dac/modded_dac.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/models/dac/modded_dac.py
Apache-2.0
def generate( *, model: BaseTransformer, prompt: torch.Tensor, max_new_tokens: int, audio_masks: torch.Tensor, audio_parts: torch.Tensor, decode_one_token=decode_one_token_ar, num_samples: int = 1, **sampling_kwargs, ): """ Takes a conditioning sequence (prompt) as input and ...
Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested.
generate
python
fishaudio/fish-speech
fish_speech/models/text2semantic/inference.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/models/text2semantic/inference.py
Apache-2.0
def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000) -> Tensor: """ Precomputes frequency tensors for complex exponentials (cis) Args: seq_len: Length of the sequence for which positional embeddings are needed. n_elem: Number of elements in the frequency tensor. ba...
Precomputes frequency tensors for complex exponentials (cis) Args: seq_len: Length of the sequence for which positional embeddings are needed. n_elem: Number of elements in the frequency tensor. base: Base value for the frequency scaling (default: 10000). Returns: A tensor...
precompute_freqs_cis
python
fishaudio/fish-speech
fish_speech/models/text2semantic/llama.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/models/text2semantic/llama.py
Apache-2.0
def list_files( path: Union[Path, str], extensions: set[str] = set(), recursive: bool = False, sort: bool = True, ) -> list[Path]: """List files in a directory. Args: path (Path): Path to the directory. extensions (set, optional): Extensions to filter. Defaults to None. ...
List files in a directory. Args: path (Path): Path to the directory. extensions (set, optional): Extensions to filter. Defaults to None. recursive (bool, optional): Whether to search recursively. Defaults to False. sort (bool, optional): Whether to sort the files. Defaults to True. ...
list_files
python
fishaudio/fish-speech
fish_speech/utils/file.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/file.py
Apache-2.0
def __init__( self, name: str = __name__, rank_zero_only: bool = True, extra: Optional[Mapping[str, object]] = None, ) -> None: """Initializes a multi-GPU-friendly python command line logger that logs on all processes with their rank prefixed in the log message. ...
Initializes a multi-GPU-friendly python command line logger that logs on all processes with their rank prefixed in the log message. :param name: The name of the logger. Default is ``__name__``. :param rank_zero_only: Whether to force all logs to only occur on the rank zero process. Default is `...
__init__
python
fishaudio/fish-speech
fish_speech/utils/logger.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/logger.py
Apache-2.0
def log( self, level: int, msg: str, rank: Optional[int] = None, *args, **kwargs ) -> None: """Delegate a log call to the underlying logger, after prefixing its message with the rank of the process it's being logged from. If `'rank'` is provided, then the log will only occur on that ...
Delegate a log call to the underlying logger, after prefixing its message with the rank of the process it's being logged from. If `'rank'` is provided, then the log will only occur on that rank/process. :param level: The level to log at. Look at `logging.__init__.py` for more information. ...
log
python
fishaudio/fish-speech
fish_speech/utils/logger.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/logger.py
Apache-2.0
def log_hyperparameters(object_dict: dict) -> None: """Controls which config parts are saved by lightning loggers. Additionally saves: - Number of model parameters """ hparams = {} cfg = object_dict["cfg"] model = object_dict["model"] trainer = object_dict["trainer"] if not train...
Controls which config parts are saved by lightning loggers. Additionally saves: - Number of model parameters
log_hyperparameters
python
fishaudio/fish-speech
fish_speech/utils/logging_utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/logging_utils.py
Apache-2.0
def print_config_tree( cfg: DictConfig, print_order: Sequence[str] = ( "data", "model", "callbacks", "logger", "trainer", "paths", "extras", ), resolve: bool = False, save_to_file: bool = False, ) -> None: """Prints content of DictConfig us...
Prints content of DictConfig using Rich library and its tree structure. Args: cfg (DictConfig): Configuration composed by Hydra. print_order (Sequence[str], optional): Determines in what order config components are printed. resolve (bool, optional): Whether to resolve reference fields of Di...
print_config_tree
python
fishaudio/fish-speech
fish_speech/utils/rich_utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/rich_utils.py
Apache-2.0
def enforce_tags(cfg: DictConfig, save_to_file: bool = False) -> None: """Prompts user to input tags from command line if no tags are provided in config.""" # noqa: E501 if not cfg.get("tags"): if "id" in HydraConfig().cfg.hydra.job: raise ValueError("Specify tags before launching a multir...
Prompts user to input tags from command line if no tags are provided in config.
enforce_tags
python
fishaudio/fish-speech
fish_speech/utils/rich_utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/rich_utils.py
Apache-2.0
def extras(cfg: DictConfig) -> None: """Applies optional utilities before the task is started. Utilities: - Ignoring python warnings - Setting tags from command line - Rich config printing """ # return if no `extras` config if not cfg.get("extras"): log.warning("Extras config n...
Applies optional utilities before the task is started. Utilities: - Ignoring python warnings - Setting tags from command line - Rich config printing
extras
python
fishaudio/fish-speech
fish_speech/utils/utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/utils.py
Apache-2.0
def task_wrapper(task_func: Callable) -> Callable: """Optional decorator that controls the failure behavior when executing the task function. This wrapper can be used to: - make sure loggers are closed even if the task function raises an exception (prevents multirun failure) - save the exception to a `...
Optional decorator that controls the failure behavior when executing the task function. This wrapper can be used to: - make sure loggers are closed even if the task function raises an exception (prevents multirun failure) - save the exception to a `.log` file - mark the run as failed with a dedicated f...
task_wrapper
python
fishaudio/fish-speech
fish_speech/utils/utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/utils.py
Apache-2.0
def get_metric_value(metric_dict: dict, metric_name: str) -> float: """Safely retrieves value of the metric logged in LightningModule.""" if not metric_name: log.info("Metric name is None! Skipping metric value retrieval...") return None if metric_name not in metric_dict: raise Exc...
Safely retrieves value of the metric logged in LightningModule.
get_metric_value
python
fishaudio/fish-speech
fish_speech/utils/utils.py
https://github.com/fishaudio/fish-speech/blob/master/fish_speech/utils/utils.py
Apache-2.0
def inference_wrapper(req: ServeTTSRequest, engine: TTSInferenceEngine): """ Wrapper for the inference function. Used in the API server. """ count = 0 for result in engine.inference(req): match result.code: case "header": if isinstance(result.audio, tuple): ...
Wrapper for the inference function. Used in the API server.
inference_wrapper
python
fishaudio/fish-speech
tools/server/inference.py
https://github.com/fishaudio/fish-speech/blob/master/tools/server/inference.py
Apache-2.0
def inference_wrapper( text, reference_id, reference_audio, reference_text, max_new_tokens, chunk_length, top_p, repetition_penalty, temperature, seed, use_memory_cache, engine, ): """ Wrapper for the inference function. Used in the Gradio interface. """ ...
Wrapper for the inference function. Used in the Gradio interface.
inference_wrapper
python
fishaudio/fish-speech
tools/webui/inference.py
https://github.com/fishaudio/fish-speech/blob/master/tools/webui/inference.py
Apache-2.0
def get_inference_wrapper(engine) -> Callable: """ Get the inference function with the immutable arguments. """ return partial( inference_wrapper, engine=engine, )
Get the inference function with the immutable arguments.
get_inference_wrapper
python
fishaudio/fish-speech
tools/webui/inference.py
https://github.com/fishaudio/fish-speech/blob/master/tools/webui/inference.py
Apache-2.0
def register_objects_from_init(directory: str): """ Traverse the specified directory for __init__.py files and register objects defined in __all__. """ for dirpath, _, filenames in os.walk(os.path.normpath(directory)): if '__init__.py' in filenames: module_path = dirpath.replace(...
Traverse the specified directory for __init__.py files and register objects defined in __all__.
register_objects_from_init
python
modelscope/data-juicer
service.py
https://github.com/modelscope/data-juicer/blob/master/service.py
Apache-2.0
def register_class(module, cls): """Register class and its methods as endpoints.""" def create_class_call(cls, method_name: str): async def class_call(request: Request): try: # wrap init method cls.__init__ = validate_call( cls.__init__, ...
Register class and its methods as endpoints.
register_class
python
modelscope/data-juicer
service.py
https://github.com/modelscope/data-juicer/blob/master/service.py
Apache-2.0
def analyze_modality_tag(code, op_prefix): """ Analyze the modality tag for the given code content string. Should be one of the "Modality Tags" in `tagging_mappings.json`. It makes the choice by finding the usages of attributes `{modality}_key` and the prefix of the OP name. If there are multiple mo...
Analyze the modality tag for the given code content string. Should be one of the "Modality Tags" in `tagging_mappings.json`. It makes the choice by finding the usages of attributes `{modality}_key` and the prefix of the OP name. If there are multiple modality keys are used, the 'multimodal' tag wil...
analyze_modality_tag
python
modelscope/data-juicer
.pre-commit-hooks/build_op_doc.py
https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py
Apache-2.0