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 dh_dd_mh_md(g: int, m: int, l: int) -> Tuple[int, int, int, int]:
"""Split a global mesh dimension into four tiling components.
Args:
g: global mesh bounds dimension size
m: model-parallel submesh bounds dimension size
l: local submesh bounds dimens... | Split a global mesh dimension into four tiling components.
Args:
g: global mesh bounds dimension size
m: model-parallel submesh bounds dimension size
l: local submesh bounds dimension size
Returns:
The resulting tuple divides the dimensio... | dh_dd_mh_md | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_gpu_mesh(num_partitions: int) -> Mesh:
"""Mesh for GPUs that preferentially places 'model' on NVLink."""
nvlink_size = jax.local_device_count()
dcn_size = jax.process_count()
nvlink_mp = min(num_partitions, nvlink_size)
nvlink_dp, extra1 = divmod(nvlink_size, nvlink_mp)
dcn_mp, extra2 = ... | Mesh for GPUs that preferentially places 'model' on NVLink. | get_gpu_mesh | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def default_mesh(
num_partitions: int,
model_parallel_submesh: Optional[HardwareMesh] = None,
backend: Optional[str] = None,
) -> Mesh:
"""Attempt to return a default mesh for simple cases.
Args:
num_partitions: number of partitions to use, will be ignored if
model_parallel_submesh is... | Attempt to return a default mesh for simple cases.
Args:
num_partitions: number of partitions to use, will be ignored if
model_parallel_submesh is provided.
model_parallel_submesh: 4-tuple that specifies the x,y,z,c submesh to use as
the model-parallel device tile.
backend: get de... | default_mesh | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_local_chunk_info(
self, global_shape: Tuple[int, ...], mesh_axes: Sequence[Optional[str]]
) -> LocalChunkInfo:
"""Get the local chunk info for a given array shape and sharded axes.
Args:
global_shape: the global, unsharded shape of the array to chunk.
mesh_axes: ... | Get the local chunk info for a given array shape and sharded axes.
Args:
global_shape: the global, unsharded shape of the array to chunk.
mesh_axes: a sequence of names (or None) of equal rank to `global_shape`
that specifies which mesh dimensions the array is sharded along.
... | get_local_chunk_info | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def standard_logical_axis_rules(
activation_partitioning_dims: int = 1,
parameter_partitioning_dims: int = 1,
additional_rules: Optional[LogicalAxisRules] = None,
) -> LogicalAxisRules:
"""Default sharding rules for T5X model in terms of logical axis names.
Args:
activation_partitioning_dims:... | Default sharding rules for T5X model in terms of logical axis names.
Args:
activation_partitioning_dims: enables 2-D activation sharding when set to 2.
parameter_partitioning_dims: enables 2-D parameter sharding when set to 2.
additional_rules: additional rules (a sequence of tuples) that will be... | standard_logical_axis_rules | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def _id_fn(x, ix):
"""Identity function for copying parameters to the devices, sharded."""
# A pure identity such as `lambda x, *: x` can get optimized away, so we
# include a random.split as a cheap function that cannot be optimized away.
y = random.split(random.PRNGKey(jnp.array(ix, dtype=jnp.uint32))... | Identity function for copying parameters to the devices, sharded. | _id_fn | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def __init__(
self,
num_partitions: Optional[int] = None,
model_parallel_submesh: Optional[HardwareMesh] = None,
params_on_devices: bool = True,
backend: Optional[str] = None,
):
"""Configures the partitioner.
Args:
num_partitions: the number of par... | Configures the partitioner.
Args:
num_partitions: the number of partitions to use. Ignored if
`model_parallel_submesh` is provided.
model_parallel_submesh: 4-tuple that specifies the x,y,z,c submesh to use
as the model-parallel device tile. This submesh is used for t... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_data_layout(self, batch_size: Optional[int] = None, host_index: Optional[int] = None) -> DataLayout:
"""Returns filled `DataLayout` based on the partitioned model layout.
Args:
batch_size: if set, indicates the requested batch size. The exception will
be raised if this bat... | Returns filled `DataLayout` based on the partitioned model layout.
Args:
batch_size: if set, indicates the requested batch size. The exception will
be raised if this batch size is not compatible with the layout. If not
set, the batch size is inferred from the layout.
... | get_data_layout | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_local_chunk_info(
self, global_shape: Tuple[int, ...], mesh_axes: Sequence[Optional[str]]
) -> LocalChunkInfo:
"""Returns the local chunk info for a given array shape and sharded axes."""
return self._local_chunker.get_local_chunk_info(global_shape, mesh_axes) | Returns the local chunk info for a given array shape and sharded axes. | get_local_chunk_info | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def move_params_to_devices(self, train_state: TrainState, train_state_axes: TrainState) -> TrainState:
"""Moves the optimizer parameters to devices."""
p_id_fn = self.partition(
_id_fn,
in_axis_resources=(train_state_axes, None),
out_axis_resources=(train_state_axes, ... | Moves the optimizer parameters to devices. | move_params_to_devices | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_logical_axes(self, train_state: TrainState) -> TrainState:
"""Returns a copy of TrainState with Optional[AxisNames] as leaves."""
# By default, return None for the logical axes.
return train_state.restore_state(jax.tree_map(lambda x: None, train_state.state_dict())) | Returns a copy of TrainState with Optional[AxisNames] as leaves. | get_logical_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def partition(
self,
fn: Callable, # pylint: disable=g-bare-generic
in_axis_resources,
out_axis_resources,
static_argnums: Union[int, Sequence[int]] = (),
donate_argnums: Union[int, Sequence[int]] = (),
) -> PartitionedCallable:
"""Partitions the computation ... | Partitions the computation using partitioner-specific implementation.
Args:
fn: the function to partition.
in_axis_resources: Pytree of structure matching that of arguments to `fn`,
with all actual arguments replaced by resource assignment
specifications. It is also ... | partition | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def __init__(
self,
num_partitions: Optional[int] = None,
model_parallel_submesh: Optional[HardwareMesh] = None,
params_on_devices: bool = True,
backend: Optional[str] = None,
logical_axis_rules: Optional[LogicalAxisRules] = None,
use_cpu_pjit: Optional[bool] = Fa... | PjitPartitioner constructor.
See https://github.com/google-research/text-to-text-transfer-transformer/blob/main/README.mdx/usage/partitioning for details.
Args:
num_partitions: an integer that specifies the size of the model parallel
submesh to be automatically selected for the c... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def partition(
self,
fn: Callable, # pylint: disable=g-bare-generic
in_axis_resources,
out_axis_resources,
static_argnums: Union[int, Sequence[int]] = (),
donate_argnums: Union[int, Sequence[int]] = (),
) -> PjittedFnWithContext:
"""Partitions the function us... | Partitions the function using jax.pjit. | partition | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_mesh_axes(self, train_state: TrainState) -> TrainState:
"""Returns a copy of TrainState with Optional[PartitionSpecs] as leaves."""
logical_axes = self.get_logical_axes(train_state)
def _logical_to_mesh_axes(param_name, logical_axes):
if logical_axes is None:
... | Returns a copy of TrainState with Optional[PartitionSpecs] as leaves. | get_mesh_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
"""
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation
computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation
... |
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation
computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation
in transformers, and matches to within 1e-5 abs tolerance.
| _np_extract_fbank_features | python | huggingface/distil-whisper | training/flax/distil_whisper/pipeline.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/pipeline.py | MIT |
def __init__(
self,
checkpoint="openai/whisper-large-v2",
dtype=jnp.float32,
batch_size=None,
max_length=None,
**kwargs,
):
"""
Args
checkpoint (`str`, *optional*, defaults to `"openai/whisper-large-v2"):
The Whisper checkpo... |
Args
checkpoint (`str`, *optional*, defaults to `"openai/whisper-large-v2"):
The Whisper checkpoint to use with the pipeline. Must be an available checkpoint on the Hugging Face Hub
with Flax weights.
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/pipeline.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/pipeline.py | MIT |
def __call__(
self,
inputs,
chunk_length_s=30.0,
stride_length_s=None,
batch_size=None,
language=None,
task=None,
return_timestamps=None,
num_beams=1,
length_penalty=1.0,
do_sample=False,
top_k=50,
temperature=1.0,
... |
Transcribe an audio input sequence to a text transcription, optionally with timestamps.
Args:
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
The inputs is either:
- `str` that is the filename of the audio file, the file will be read at the correct ... | __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/pipeline.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/pipeline.py | MIT |
def _split_variables_and_axes(
variables_and_axes: FrozenVariableDict,
) -> Tuple[FrozenVariableDict, FrozenVariableDict]:
"""Splits `variables_and_axes` into two separate dicts with the same keys."""
# For each `key`, `key_axes` (if any) are its axes in `variables_and_axes`.
variables = {}
axes = {... | Splits `variables_and_axes` into two separate dicts with the same keys. | _split_variables_and_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/train_state.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/train_state.py | MIT |
def emailUser(profile, SUBJECT="", BODY=""):
"""
sends an email.
Arguments:
profile -- contains information related to the user (e.g., email
address)
SUBJECT -- subject line of the email
BODY -- body text of the email
"""
def generateSMSEmail(profile):
... |
sends an email.
Arguments:
profile -- contains information related to the user (e.g., email
address)
SUBJECT -- subject line of the email
BODY -- body text of the email
| emailUser | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def generateSMSEmail(profile):
"""
Generates an email from a user's phone number based on their carrier.
"""
if profile['carrier'] is None or not profile['phone_number']:
return None
return str(profile['phone_number']) + "@" + profile['carrier'] |
Generates an email from a user's phone number based on their carrier.
| generateSMSEmail | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def getTimezone(profile):
"""
Returns the pytz timezone for a given profile.
Arguments:
profile -- contains information related to the user (e.g., email
address)
"""
try:
return timezone(profile['timezone'])
except:
return None |
Returns the pytz timezone for a given profile.
Arguments:
profile -- contains information related to the user (e.g., email
address)
| getTimezone | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def generateTinyURL(URL):
"""
Generates a compressed URL.
Arguments:
URL -- the original URL to-be compressed
"""
target = "http://tinyurl.com/api-create.php?url=" + URL
response = urllib2.urlopen(target)
return response.read() |
Generates a compressed URL.
Arguments:
URL -- the original URL to-be compressed
| generateTinyURL | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def __init__(self, mic, profile):
"""
Instantiates a new Brain object, which cross-references user
input with a list of modules. Note that the order of brain.modules
matters, as the Brain will cease execution on the first module
that accepts a given input.
Arguments:
... |
Instantiates a new Brain object, which cross-references user
input with a list of modules. Note that the order of brain.modules
matters, as the Brain will cease execution on the first module
that accepts a given input.
Arguments:
mic -- used to interact with the user (f... | __init__ | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def get_modules(cls):
"""
Dynamically loads all the modules in the modules folder and sorts
them by the PRIORITY key. If no PRIORITY is defined for a given
module, a priority of 0 is assumed.
"""
logger = logging.getLogger(__name__)
locations = [jasperpath.PLUGIN... |
Dynamically loads all the modules in the modules folder and sorts
them by the PRIORITY key. If no PRIORITY is defined for a given
module, a priority of 0 is assumed.
| get_modules | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def query(self, texts):
"""
Passes user input to the appropriate module, testing it against
each candidate module's isValid function.
Arguments:
text -- user input, typically speech, to be parsed by a module
"""
for module in self.modules:
for text in... |
Passes user input to the appropriate module, testing it against
each candidate module's isValid function.
Arguments:
text -- user input, typically speech, to be parsed by a module
| query | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def handleForever(self):
"""
Delegates user input to the handling function when activated.
"""
self._logger.info("Starting to handle conversation with keyword '%s'.",
self.persona)
while True:
# Print notifications until empty
not... |
Delegates user input to the handling function when activated.
| handleForever | python | jasperproject/jasper-client | client/conversation.py | https://github.com/jasperproject/jasper-client/blob/master/client/conversation.py | MIT |
def check_network_connection(server="www.google.com"):
"""
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
... |
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
| check_network_connection | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def check_executable(executable):
"""
Checks if an executable exists in $PATH.
Arguments:
executable -- the name of the executable (e.g. "echo")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
execu... |
Checks if an executable exists in $PATH.
Arguments:
executable -- the name of the executable (e.g. "echo")
Returns:
True or False
| check_executable | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def check_python_import(package_or_module):
"""
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'.... |
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
| check_python_import | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def get_pip_requirements(fname=os.path.join(jasperpath.LIB_PATH,
'requirements.txt')):
"""
Gets the PIP requirements from a text file. If the files does not exists
or is not readable, it returns None
Arguments:
fname -- (optional) the requirement text... |
Gets the PIP requirements from a text file. If the files does not exists
or is not readable, it returns None
Arguments:
fname -- (optional) the requirement text file (Default:
"client/requirements.txt")
Returns:
A list of pip requirement objects or None
| get_pip_requirements | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def get_git_revision():
"""
Gets the current git revision hash as hex string. If the git executable is
missing or git is unable to get the revision, None is returned
Returns:
A hex string or None
"""
logger = logging.getLogger(__name__)
if not check_executable('git'):
logger... |
Gets the current git revision hash as hex string. If the git executable is
missing or git is unable to get the revision, None is returned
Returns:
A hex string or None
| get_git_revision | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def run():
"""
Performs a series of checks against the system and writes the results to
the logging system.
Returns:
The number of failed checks as integer
"""
logger = logging.getLogger(__name__)
# Set loglevel of this module least to info
loglvl = logger.getEffectiveLevel()
... |
Performs a series of checks against the system and writes the results to
the logging system.
Returns:
The number of failed checks as integer
| run | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def __init__(self, speaker, passive_stt_engine, active_stt_engine):
"""
Initiates the pocketsphinx instance.
Arguments:
speaker -- handles platform-independent audio output
passive_stt_engine -- performs STT while Jasper is in passive listen
mode
... |
Initiates the pocketsphinx instance.
Arguments:
speaker -- handles platform-independent audio output
passive_stt_engine -- performs STT while Jasper is in passive listen
mode
acive_stt_engine -- performs STT while Jasper is in active listen mode
... | __init__ | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def passiveListen(self, PERSONA):
"""
Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so
needs to be restarted.
"""
THRESHOLD_MULTIPLIER = 1.8
RATE = 16000
CHUNK = 1024
# number of seconds to allow to establish threshold
THRES... |
Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so
needs to be restarted.
| passiveListen | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def activeListen(self, THRESHOLD=None, LISTEN=True, MUSIC=False):
"""
Records until a second of silence or times out after 12 seconds
Returns the first matching string or None
"""
options = self.activeListenToAllOptions(THRESHOLD, LISTEN, MUSIC)
if options:
... |
Records until a second of silence or times out after 12 seconds
Returns the first matching string or None
| activeListen | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
MUSIC=False):
"""
Records until a second of silence or times out after 12 seconds
Returns a list of the matching options or None
"""
RATE = 16000
CHUNK = 1024
... |
Records until a second of silence or times out after 12 seconds
Returns a list of the matching options or None
| activeListenToAllOptions | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def handleEmailNotifications(self, lastDate):
"""Places new Gmail notifications in the Notifier's queue."""
emails = Gmail.fetchUnreadEmails(self.profile, since=lastDate)
if emails:
lastDate = Gmail.getMostRecentDate(emails)
def styleEmail(e):
return "New email f... | Places new Gmail notifications in the Notifier's queue. | handleEmailNotifications | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def getNotification(self):
"""Returns a notification. Note that this function is consuming."""
try:
notif = self.q.get(block=False)
return notif
except Queue.Empty:
return None | Returns a notification. Note that this function is consuming. | getNotification | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def getAllNotifications(self):
"""
Return a list of notifications in chronological order.
Note that this function is consuming, so consecutive calls
will yield different results.
"""
notifs = []
notif = self.getNotification()
while notif:
... |
Return a list of notifications in chronological order.
Note that this function is consuming, so consecutive calls
will yield different results.
| getAllNotifications | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def __init__(self, vocabulary, hmm_dir="/usr/local/share/" +
"pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k"):
"""
Initiates the pocketsphinx instance.
Arguments:
vocabulary -- a PocketsphinxVocabulary instance
hmm_dir -- the path of the Hidden Markov Mode... |
Initiates the pocketsphinx instance.
Arguments:
vocabulary -- a PocketsphinxVocabulary instance
hmm_dir -- the path of the Hidden Markov Model (HMM)
| __init__ | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def transcribe(self, fp):
"""
Performs STT, transcribing an audio file and returning the result.
Arguments:
fp -- a file object containing audio data
"""
fp.seek(44)
# FIXME: Can't use the Decoder.decode_raw() here, because
# pocketsphinx segfaults ... |
Performs STT, transcribing an audio file and returning the result.
Arguments:
fp -- a file object containing audio data
| transcribe | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def __init__(self, api_key=None, language='en-us'):
# FIXME: get init args from config
"""
Arguments:
api_key - the public api key which allows access to Google APIs
"""
self._logger = logging.getLogger(__name__)
self._request_url = None
self._language = N... |
Arguments:
api_key - the public api key which allows access to Google APIs
| __init__ | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def transcribe(self, fp):
"""
Performs STT via the Google Speech API, transcribing an audio file and
returning an English string.
Arguments:
audio_file_path -- the path to the .wav file to be transcribed
"""
if not self.api_key:
self._logger.critical... |
Performs STT via the Google Speech API, transcribing an audio file and
returning an English string.
Arguments:
audio_file_path -- the path to the .wav file to be transcribed
| transcribe | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def get_engine_by_slug(slug=None):
"""
Returns:
An STT Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
"""
if not slug or type(slug) is not str:
raise TypeError("Invalid slug '%s'", slug)
... |
Returns:
An STT Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
| get_engine_by_slug | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def get_engine_by_slug(slug=None):
"""
Returns:
A speaker implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
"""
if not slug or type(slug) is not str:
raise TypeError("Invalid slug '%s'", slug)
... |
Returns:
A speaker implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
| get_engine_by_slug | python | jasperproject/jasper-client | client/tts.py | https://github.com/jasperproject/jasper-client/blob/master/client/tts.py | MIT |
def phrases_to_revision(cls, phrases):
"""
Calculates a revision from phrases by using the SHA1 hash function.
Arguments:
phrases -- a list of phrases
Returns:
A revision string for given phrases.
"""
sorted_phrases = sorted(phrases)
join... |
Calculates a revision from phrases by using the SHA1 hash function.
Arguments:
phrases -- a list of phrases
Returns:
A revision string for given phrases.
| phrases_to_revision | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def __init__(self, name='default', path='.'):
"""
Initializes a new Vocabulary instance.
Optional Arguments:
name -- (optional) the name of the vocabulary (Default: 'default')
path -- (optional) the path in which the vocabulary exists or will
be creat... |
Initializes a new Vocabulary instance.
Optional Arguments:
name -- (optional) the name of the vocabulary (Default: 'default')
path -- (optional) the path in which the vocabulary exists or will
be created (Default: '.')
| __init__ | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def compiled_revision(self):
"""
Reads the compiled revision from the revision file.
Returns:
the revision of this vocabulary (i.e. the string
inside the revision file), or None if is_compiled
if False
"""
if not self.is_compiled:
... |
Reads the compiled revision from the revision file.
Returns:
the revision of this vocabulary (i.e. the string
inside the revision file), or None if is_compiled
if False
| compiled_revision | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def compile(self, phrases, force=False):
"""
Compiles this vocabulary. If the force argument is True, compilation
will be forced regardless of necessity (which means that the
preliminary check if the current revision already equals the
revision after compilation will be skipped).... |
Compiles this vocabulary. If the force argument is True, compilation
will be forced regardless of necessity (which means that the
preliminary check if the current revision already equals the
revision after compilation will be skipped).
This method is not meant to be overridden b... | compile | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def _compile_vocabulary(self, phrases):
"""
Abstract method that should be overridden in subclasses with custom
compilation code.
Arguments:
phrases -- a list of phrases that this vocabulary will contain
""" |
Abstract method that should be overridden in subclasses with custom
compilation code.
Arguments:
phrases -- a list of phrases that this vocabulary will contain
| _compile_vocabulary | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def is_compiled(self):
"""
Checks if the vocabulary is compiled by checking if the revision,
languagemodel and dictionary files are readable.
Returns:
True if this vocabulary has been compiled, else False
"""
return (super(self.__class__, self).is_compiled an... |
Checks if the vocabulary is compiled by checking if the revision,
languagemodel and dictionary files are readable.
Returns:
True if this vocabulary has been compiled, else False
| is_compiled | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def _compile_vocabulary(self, phrases):
"""
Compiles the vocabulary to the Pocketsphinx format by creating a
languagemodel and a dictionary.
Arguments:
phrases -- a list of phrases that this vocabulary will contain
"""
text = " ".join([("<s> %s </s>" % phrase... |
Compiles the vocabulary to the Pocketsphinx format by creating a
languagemodel and a dictionary.
Arguments:
phrases -- a list of phrases that this vocabulary will contain
| _compile_vocabulary | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def _compile_languagemodel(self, text, output_file):
"""
Compiles the languagemodel from a text.
Arguments:
text -- the text the languagemodel will be generated from
output_file -- the path of the file this languagemodel will
be written to
... |
Compiles the languagemodel from a text.
Arguments:
text -- the text the languagemodel will be generated from
output_file -- the path of the file this languagemodel will
be written to
Returns:
A list of all unique words this vocabu... | _compile_languagemodel | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def _compile_dictionary(self, words, output_file):
"""
Compiles the dictionary from a list of words.
Arguments:
words -- a list of all unique words this vocabulary contains
output_file -- the path of the file this dictionary will
be written to
... |
Compiles the dictionary from a list of words.
Arguments:
words -- a list of all unique words this vocabulary contains
output_file -- the path of the file this dictionary will
be written to
| _compile_dictionary | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def get_keyword_phrases():
"""
Gets the keyword phrases from the keywords file in the jasper data dir.
Returns:
A list of keyword phrases.
"""
phrases = []
with open(jasperpath.data('keyword_phrases'), mode="r") as f:
for line in f:
phrase = line.strip()
... |
Gets the keyword phrases from the keywords file in the jasper data dir.
Returns:
A list of keyword phrases.
| get_keyword_phrases | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def get_all_phrases():
"""
Gets phrases from all modules.
Returns:
A list of phrases in all modules plus additional phrases passed to this
function.
"""
phrases = []
modules = brain.Brain.get_modules()
for module in modules:
phrases.extend(get_phrases_from_module(mo... |
Gets phrases from all modules.
Returns:
A list of phrases in all modules plus additional phrases passed to this
function.
| get_all_phrases | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, by listing the user's
Facebook friends with birthdays today.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
... |
Responds to user-input, typically speech text, by listing the user's
Facebook friends with birthdays today.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information rela... | handle | python | jasperproject/jasper-client | client/modules/Birthday.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Birthday.py | MIT |
def getSender(email):
"""
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
"""
sender = email['From']
m = re.match(r'(.*)\s<.*>', sender)
if m:
return m.group(1)
return... |
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
| getSender | python | jasperproject/jasper-client | client/modules/Gmail.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Gmail.py | MIT |
def getMostRecentDate(emails):
"""
Returns the most recent date of any email in the list provided.
Arguments:
emails -- a list of emails to check
Returns:
Date of the most recent email.
"""
dates = [getDate(e) for e in emails]
dates.sort(reverse=True)
if dat... |
Returns the most recent date of any email in the list provided.
Arguments:
emails -- a list of emails to check
Returns:
Date of the most recent email.
| getMostRecentDate | python | jasperproject/jasper-client | client/modules/Gmail.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Gmail.py | MIT |
def fetchUnreadEmails(profile, since=None, markRead=False, limit=None):
"""
Fetches a list of unread email objects from a user's Gmail inbox.
Arguments:
profile -- contains information related to the user (e.g., Gmail
address)
since -- if provided, no emails befor... |
Fetches a list of unread email objects from a user's Gmail inbox.
Arguments:
profile -- contains information related to the user (e.g., Gmail
address)
since -- if provided, no emails before this date will be returned
markRead -- if True, marks all returned em... | fetchUnreadEmails | python | jasperproject/jasper-client | client/modules/Gmail.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Gmail.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, with a summary of
the user's Gmail inbox, reporting on the number of unread emails
in the inbox, as well as their senders.
Arguments:
text -- user-input, typically transcribed speech
m... |
Responds to user-input, typically speech text, with a summary of
the user's Gmail inbox, reporting on the number of unread emails
in the inbox, as well as their senders.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (f... | handle | python | jasperproject/jasper-client | client/modules/Gmail.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Gmail.py | MIT |
def getTopStories(maxResults=None):
"""
Returns the top headlines from Hacker News.
Arguments:
maxResults -- if provided, returns a random sample of size maxResults
"""
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(URL, headers=hdr)
page = urllib2.urlopen(req).re... |
Returns the top headlines from Hacker News.
Arguments:
maxResults -- if provided, returns a random sample of size maxResults
| getTopStories | python | jasperproject/jasper-client | client/modules/HN.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/HN.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, with a sample of
Hacker News's top headlines, sending them to the user over email
if desired.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with t... |
Responds to user-input, typically speech text, with a sample of
Hacker News's top headlines, sending them to the user over email
if desired.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
... | handle | python | jasperproject/jasper-client | client/modules/HN.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/HN.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, by telling a joke.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the ... |
Responds to user-input, typically speech text, by telling a joke.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., phone
nu... | handle | python | jasperproject/jasper-client | client/modules/Joke.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Joke.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, by relaying the
meaning of life.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains infor... |
Responds to user-input, typically speech text, by relaying the
meaning of life.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., phone... | handle | python | jasperproject/jasper-client | client/modules/Life.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Life.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, by telling a joke.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.... |
Responds to user-input, typically speech text, by telling a joke.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., phone
number)
... | handle | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def __init__(self, server="localhost", port=6600):
"""
Prepare the client and music variables
"""
self.server = server
self.port = port
# prepare client
self.client = mpd.MPDClient()
self.client.timeout = None
self.client.idletimeout = None
... |
Prepare the client and music variables
| __init__ | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def play(self, songs=False, playlist_name=False):
"""
Plays the current song or accepts a song to play.
Arguments:
songs -- a list of song objects
playlist_name -- user-defined, something like "Love Song Playlist"
"""
if songs:
self.cl... |
Plays the current song or accepts a song to play.
Arguments:
songs -- a list of song objects
playlist_name -- user-defined, something like "Love Song Playlist"
| play | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def get_soup(self):
"""
Returns the list of unique words that comprise song and artist titles
"""
soup = []
for song in self.songs:
song_words = song.title.split(" ")
artist_words = song.artist.split(" ")
soup.extend(song_words)
s... |
Returns the list of unique words that comprise song and artist titles
| get_soup | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def get_soup_playlist(self):
"""
Returns the list of unique words that comprise playlist names
"""
soup = []
for name in self.playlists:
soup.extend(name.split(" "))
title_trans = ''.join(chr(c) if chr(c).isupper() or chr(c).islower()
... |
Returns the list of unique words that comprise playlist names
| get_soup_playlist | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def get_soup_separated(self):
"""
Returns the list of PHRASES that comprise song and artist titles
"""
title_soup = [song.title for song in self.songs]
artist_soup = [song.artist for song in self.songs]
soup = list(set(title_soup + artist_soup))
title_trans = '... |
Returns the list of PHRASES that comprise song and artist titles
| get_soup_separated | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def fuzzy_songs(self, query):
"""
Returns songs matching a query best as possible on either artist
field, etc
"""
query = query.upper()
matched_song_titles = difflib.get_close_matches(query,
self.song_titles)
... |
Returns songs matching a query best as possible on either artist
field, etc
| fuzzy_songs | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def fuzzy_playlists(self, query):
"""
returns playlist names that match query best as possible
"""
query = query.upper()
lookup = {n.upper(): n for n in self.playlists}
results = [lookup[r] for r in difflib.get_close_matches(query, lookup)]
return results |
returns playlist names that match query best as possible
| fuzzy_playlists | python | jasperproject/jasper-client | client/modules/MPDControl.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/MPDControl.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, with a summary of
the day's top news headlines, sending them to the user over email
if desired.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with... |
Responds to user-input, typically speech text, with a summary of
the day's top news headlines, sending them to the user over email
if desired.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
... | handle | python | jasperproject/jasper-client | client/modules/News.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/News.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, with a summary of
the user's Facebook notifications, including a count and details
related to each individual notification.
Arguments:
text -- user-input, typically transcribed speech
... |
Responds to user-input, typically speech text, with a summary of
the user's Facebook notifications, including a count and details
related to each individual notification.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (... | handle | python | jasperproject/jasper-client | client/modules/Notifications.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Notifications.py | MIT |
def handle(text, mic, profile):
"""
Reports the current time based on the user's timezone.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g.,... |
Reports the current time based on the user's timezone.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., phone
number)
| handle | python | jasperproject/jasper-client | client/modules/Time.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Time.py | MIT |
def handle(text, mic, profile):
"""
Reports that the user has unclear or unusable input.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., p... |
Reports that the user has unclear or unusable input.
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the user (for both input and output)
profile -- contains information related to the user (e.g., phone
number)
| handle | python | jasperproject/jasper-client | client/modules/Unclear.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Unclear.py | MIT |
def replaceAcronyms(text):
"""
Replaces some commonly-used acronyms for an improved verbal weather report.
"""
def parseDirections(text):
words = {
'N': 'north',
'S': 'south',
'E': 'east',
'W': 'west',
}
output = [words[w] for w in... |
Replaces some commonly-used acronyms for an improved verbal weather report.
| replaceAcronyms | python | jasperproject/jasper-client | client/modules/Weather.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Weather.py | MIT |
def handle(text, mic, profile):
"""
Responds to user-input, typically speech text, with a summary of
the relevant weather for the requested date (typically, weather
information will not be available for days beyond tomorrow).
Arguments:
text -- user-input, typically transcribed speech
... |
Responds to user-input, typically speech text, with a summary of
the relevant weather for the requested date (typically, weather
information will not be available for days beyond tomorrow).
Arguments:
text -- user-input, typically transcribed speech
mic -- used to interact with the use... | handle | python | jasperproject/jasper-client | client/modules/Weather.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Weather.py | MIT |
def isValid(text):
"""
Returns True if the text is related to the weather.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'\b(weathers?|temperature|forecast|outside|hot|' +
r'cold|jacket|coat|rain)\b', text, re.IGNORE... |
Returns True if the text is related to the weather.
Arguments:
text -- user-input, typically transcribed speech
| isValid | python | jasperproject/jasper-client | client/modules/Weather.py | https://github.com/jasperproject/jasper-client/blob/master/client/modules/Weather.py | MIT |
def testLog(self):
"""Does Brain correctly log errors when raised by modules?"""
my_brain = TestBrain._emptyBrain()
unclear = my_brain.modules[-1]
with mock.patch.object(unclear, 'handle') as mocked_handle:
with mock.patch.object(my_brain._logger, 'error') as mocked_log:
... | Does Brain correctly log errors when raised by modules? | testLog | python | jasperproject/jasper-client | tests/test_brain.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_brain.py | MIT |
def testSortByPriority(self):
"""Does Brain sort modules by priority?"""
my_brain = TestBrain._emptyBrain()
priorities = filter(lambda m: hasattr(m, 'PRIORITY'), my_brain.modules)
target = sorted(priorities, key=lambda m: m.PRIORITY, reverse=True)
self.assertEqual(target, priorit... | Does Brain sort modules by priority? | testSortByPriority | python | jasperproject/jasper-client | tests/test_brain.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_brain.py | MIT |
def testPriority(self):
"""Does Brain correctly send query to higher-priority module?"""
my_brain = TestBrain._emptyBrain()
hn_module = 'HN'
hn = filter(lambda m: m.__name__ == hn_module, my_brain.modules)[0]
with mock.patch.object(hn, 'handle') as mocked_handle:
my_... | Does Brain correctly send query to higher-priority module? | testPriority | python | jasperproject/jasper-client | tests/test_brain.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_brain.py | MIT |
def runConversation(self, query, inputs, module):
"""Generic method for spoofing conversation.
Arguments:
query -- The initial input to the server.
inputs -- Additional input, if conversation is extended.
Returns:
The server's responses, in a list.
"""
s... | Generic method for spoofing conversation.
Arguments:
query -- The initial input to the server.
inputs -- Additional input, if conversation is extended.
Returns:
The server's responses, in a list.
| runConversation | python | jasperproject/jasper-client | tests/test_modules.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_modules.py | MIT |
def testTranscribeJasper(self):
"""
Does Jasper recognize his name (i.e., passive listen)?
"""
with open(self.jasper_clip, mode="rb") as f:
transcription = self.passive_stt_engine.transcribe(f)
self.assertIn("JASPER", transcription) |
Does Jasper recognize his name (i.e., passive listen)?
| testTranscribeJasper | python | jasperproject/jasper-client | tests/test_stt.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_stt.py | MIT |
def testTranscribe(self):
"""
Does Jasper recognize 'time' (i.e., active listen)?
"""
with open(self.time_clip, mode="rb") as f:
transcription = self.active_stt_engine.transcribe(f)
self.assertIn("TIME", transcription) |
Does Jasper recognize 'time' (i.e., active listen)?
| testTranscribe | python | jasperproject/jasper-client | tests/test_stt.py | https://github.com/jasperproject/jasper-client/blob/master/tests/test_stt.py | MIT |
def prepare_latents(
self,
batch_size: int, # Number of videos to generate in parallel
num_channels_latents: int, # Number of channels in the latents
width: int, # Width of the video frame
height: int, ... |
Prepares the initial latents for video generation.
Args:
batch_size (int): Number of videos to generate in parallel.
num_channels_latents (int): Number of channels in the latents.
width (int): Width of the video frame.
height (int): Height of the video f... | prepare_latents | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate.py | MIT |
def decode_latents(self, latents):
"""
Decode the latents to produce a video.
Parameters:
latents (torch.Tensor): The latents to be decoded.
Returns:
video (torch.Tensor): The decoded video.
video_length (int): The length of the video in frames.
"""
... |
Decode the latents to produce a video.
Parameters:
latents (torch.Tensor): The latents to be decoded.
Returns:
video (torch.Tensor): The decoded video.
video_length (int): The length of the video in frames.
| decode_latents | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate.py | MIT |
def enable_sequential_cpu_offload(self, gpu_id=0):
"""
Offloads selected models to the GPU for increased performance.
Args:
gpu_id (int, optional): The ID of the GPU to offload models to. Defaults to 0.
"""
device = torch.device(f"cuda:{gpu_id}")
for cpu_off... |
Offloads selected models to the GPU for increased performance.
Args:
gpu_id (int, optional): The ID of the GPU to offload models to. Defaults to 0.
| enable_sequential_cpu_offload | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate_static.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate_static.py | MIT |
def decode_latents(self, latents):
"""
Decode the given latents to video frames.
Parameters:
latents (torch.Tensor): The latents to be decoded. Shape: (batch_size, num_channels_latents, video_length, height, width).
Returns:
video (torch.Tensor): The decoded video frame... |
Decode the given latents to video frames.
Parameters:
latents (torch.Tensor): The latents to be decoded. Shape: (batch_size, num_channels_latents, video_length, height, width).
Returns:
video (torch.Tensor): The decoded video frames. Shape: (batch_size, num_channels_latents, v... | decode_latents | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate_static.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate_static.py | MIT |
def prepare_latents(
self,
batch_size,
num_channels_latents,
width,
height,
dtype,
device,
generator,
latents=None,
):
"""
Prepares the initial latents for the diffusion pipeline.
Args:
batch_size (int): The... |
Prepares the initial latents for the diffusion pipeline.
Args:
batch_size (int): The number of images to generate in one forward pass.
num_channels_latents (int): The number of channels in the latents tensor.
width (int): The width of the latents tensor.
... | prepare_latents | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate_static.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate_static.py | MIT |
def prepare_condition(
self,
cond_image,
width,
height,
device,
dtype,
do_classififer_free_guidance=False,
):
"""
Prepares the condition for the face animation pipeline.
Args:
cond_image (torch.Tensor): The conditional imag... |
Prepares the condition for the face animation pipeline.
Args:
cond_image (torch.Tensor): The conditional image tensor.
width (int): The width of the output image.
height (int): The height of the output image.
device (torch.device): The device to run the ... | prepare_condition | python | jdh-algo/JoyHallo | joyhallo/animate/face_animate_static.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/animate/face_animate_static.py | MIT |
def preprocess(self, wav_file: str, clip_length: int=-1):
"""
Preprocess a WAV audio file by separating the vocals from the background and resampling it to a 16 kHz sample rate.
The separated vocal track is then converted into wav2vec2 for further processing or analysis.
Args:
... |
Preprocess a WAV audio file by separating the vocals from the background and resampling it to a 16 kHz sample rate.
The separated vocal track is then converted into wav2vec2 for further processing or analysis.
Args:
wav_file (str): The path to the WAV file to be processed. This fil... | preprocess | python | jdh-algo/JoyHallo | joyhallo/datasets/audio_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/audio_processor.py | MIT |
def get_embedding(self, wav_file: str):
"""preprocess wav audio file convert to embeddings
Args:
wav_file (str): The path to the WAV file to be processed. This file should be accessible and in WAV format.
Returns:
torch.tensor: Returns an audio embedding as a torch.tens... | preprocess wav audio file convert to embeddings
Args:
wav_file (str): The path to the WAV file to be processed. This file should be accessible and in WAV format.
Returns:
torch.tensor: Returns an audio embedding as a torch.tensor
| get_embedding | python | jdh-algo/JoyHallo | joyhallo/datasets/audio_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/audio_processor.py | MIT |
def preprocess(self, source_image_path: str, cache_dir: str, face_region_ratio: float):
"""
Apply preprocessing to the source image to prepare for face analysis.
Parameters:
source_image_path (str): The path to the source image.
cache_dir (str): The directory to cache in... |
Apply preprocessing to the source image to prepare for face analysis.
Parameters:
source_image_path (str): The path to the source image.
cache_dir (str): The directory to cache intermediate results.
Returns:
None
| preprocess | python | jdh-algo/JoyHallo | joyhallo/datasets/image_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/image_processor.py | MIT |
def close(self):
"""
Closes the ImageProcessor and releases any resources held by the FaceAnalysis instance.
Args:
self: The ImageProcessor instance.
Returns:
None.
"""
for _, model in self.face_analysis.models.items():
if hasattr(mod... |
Closes the ImageProcessor and releases any resources held by the FaceAnalysis instance.
Args:
self: The ImageProcessor instance.
Returns:
None.
| close | python | jdh-algo/JoyHallo | joyhallo/datasets/image_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/image_processor.py | MIT |
def preprocess(self, source_image_path: str):
"""
Apply preprocessing to the source image to prepare for face analysis.
Parameters:
source_image_path (str): The path to the source image.
cache_dir (str): The directory to cache intermediate results.
Returns:
... |
Apply preprocessing to the source image to prepare for face analysis.
Parameters:
source_image_path (str): The path to the source image.
cache_dir (str): The directory to cache intermediate results.
Returns:
None
| preprocess | python | jdh-algo/JoyHallo | joyhallo/datasets/image_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/image_processor.py | MIT |
def close(self):
"""
Closes the ImageProcessor and releases any resources held by the FaceAnalysis instance.
Args:
self: The ImageProcessor instance.
Returns:
None.
"""
for _, model in self.face_analysis.models.items():
if hasattr(mod... |
Closes the ImageProcessor and releases any resources held by the FaceAnalysis instance.
Args:
self: The ImageProcessor instance.
Returns:
None.
| close | python | jdh-algo/JoyHallo | joyhallo/datasets/image_processor.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/image_processor.py | MIT |
def augmentation(self, image, transform, state=None):
"""
Apply data augmentation to the input image.
Args:
image (PIL.Image): The input image.
transform (torchvision.transforms.Compose): The data augmentation transforms.
state (dict, optional): The random st... |
Apply data augmentation to the input image.
Args:
image (PIL.Image): The input image.
transform (torchvision.transforms.Compose): The data augmentation transforms.
state (dict, optional): The random state for reproducibility. Defaults to None.
Returns:
... | augmentation | python | jdh-algo/JoyHallo | joyhallo/datasets/mask_image.py | https://github.com/jdh-algo/JoyHallo/blob/master/joyhallo/datasets/mask_image.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.