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 test_tts_convert_with_voice_settings() -> None: """Test TTS with custom voice settings.""" client = ElevenLabs() audio_generator = client.text_to_speech.convert( text=DEFAULT_TEXT, voice_id=DEFAULT_VOICE, model_id=DEFAULT_MODEL, voice_settings=VoiceSettings(stability=0.71...
Test TTS with custom voice settings.
test_tts_convert_with_voice_settings
python
elevenlabs/elevenlabs-python
tests/test_tts.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_tts.py
MIT
def test_voice_preview_generation(): """Test generating voice previews from description.""" client = ElevenLabs() # Test parameters description = "A warm and friendly female voice with a slight British accent, speaking clearly and professionally" sample_text = "This is a test message that needs to ...
Test generating voice previews from description.
test_voice_preview_generation
python
elevenlabs/elevenlabs-python
tests/test_ttv.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_ttv.py
MIT
def test_construct_event_valid_signature(): """Test webhook event construction with valid signature.""" # Setup client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} # Create a valid signature body = json.dumps(payload) timesta...
Test webhook event construction with valid signature.
test_construct_event_valid_signature
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_missing_signature(): """Test webhook event construction with missing signature header.""" client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} with pytest.raises(BadRequestError) as excinfo: client.webhook...
Test webhook event construction with missing signature header.
test_construct_event_missing_signature
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_invalid_signature_format(): """Test webhook event construction with invalid signature format.""" client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} body = json.dumps(payload) sig_header = "invalid_format" ...
Test webhook event construction with invalid signature format.
test_construct_event_invalid_signature_format
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_expired_timestamp(): """Test webhook event construction with expired timestamp.""" client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} # Create an expired timestamp (31 minutes old) expired_time = int(time.ti...
Test webhook event construction with expired timestamp.
test_construct_event_expired_timestamp
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_invalid_signature(): """Test webhook event construction with invalid signature.""" client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} body = json.dumps(payload) timestamp = str(int(time.time())) sig_head...
Test webhook event construction with invalid signature.
test_construct_event_invalid_signature
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_missing_secret(): """Test webhook event construction with missing secret.""" client = ElevenLabs() payload = {"event_type": "speech.completed", "id": "123456"} body = json.dumps(payload) timestamp = str(int(time.time())) sig_header = f"t={timestamp},v0=some_signature" ...
Test webhook event construction with missing secret.
test_construct_event_missing_secret
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def test_construct_event_mocked_time(mock_time): """Test webhook event construction with mocked time.""" mock_time.return_value = 1600000000 client = ElevenLabs() webhook_secret = "test_secret" payload = {"event_type": "speech.completed", "id": "123456"} # Create a valid signature with fixed t...
Test webhook event construction with mocked time.
test_construct_event_mocked_time
python
elevenlabs/elevenlabs-python
tests/test_webhooks.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/test_webhooks.py
MIT
def as_local_files(urls: Sequence[str]) -> Generator[str, None, None]: """Util to download files from urls and return local file paths""" temp_files = [] for url in urls: response = httpx.get(url) temp_file = tempfile.NamedTemporaryFile() temp_file.write(response.content) te...
Util to download files from urls and return local file paths
as_local_files
python
elevenlabs/elevenlabs-python
tests/utils.py
https://github.com/elevenlabs/elevenlabs-python/blob/master/tests/utils.py
MIT
def create_oss_artifact( path, bucket=None, accesskey_id=None, accesskey_secret=None, key=None, endpoint=None, is_global=False, ): """ Configure the object as OssArtifact OSS configuration can be found (https://www.alibabacloud.com/help/doc-detail/32027.htm) :param path: ...
Configure the object as OssArtifact OSS configuration can be found (https://www.alibabacloud.com/help/doc-detail/32027.htm) :param path: the local path of container :param bucket: oss bucket :param accesskey_id: oss user id :param accesskey_secret: oss user ky :param key: key of oss obj...
create_oss_artifact
python
couler-proj/couler
couler/argo.py
https://github.com/couler-proj/couler/blob/master/couler/argo.py
Apache-2.0
def create_s3_artifact( path, bucket=None, accesskey_id=None, accesskey_secret=None, key=None, endpoint=None, is_global=False, insecure=False, ): """ Configure the object as S3Artifact :param path: the local path of container :param bucket: s3 bucket :param accesskey_...
Configure the object as S3Artifact :param path: the local path of container :param bucket: s3 bucket :param accesskey_id: s3 user id :param accesskey_secret: s3 user key :param key: key of s3 object :param endpoint: end point of s3 :param insecure: use HTTP instead of HTTPS when True ...
create_s3_artifact
python
couler-proj/couler
couler/argo.py
https://github.com/couler-proj/couler/blob/master/couler/argo.py
Apache-2.0
def obtain_secret(secret_keys, namespace="default", name=None, dry_run=False): """Get the key from secret in k8s, and return the secret name.""" secret_data = {} for x in secret_keys: secret_data[x] = "" return create_secret( secret_data, namespace=namespace, name=name, ...
Get the key from secret in k8s, and return the secret name.
obtain_secret
python
couler-proj/couler
couler/argo.py
https://github.com/couler-proj/couler/blob/master/couler/argo.py
Apache-2.0
def create_secret( secret_data, namespace="default", name=None, dry_run=False, use_existing=False, artifact_secret=False, ): """Store the input dict as a secret in k8s, and return the secret name.""" secret = Secret( namespace=namespace, data=secret_data, name=nam...
Store the input dict as a secret in k8s, and return the secret name.
create_secret
python
couler-proj/couler
couler/argo.py
https://github.com/couler-proj/couler/blob/master/couler/argo.py
Apache-2.0
def check_name(name): """Check the name is valid or not""" if len(name) > WorkflowCRD.NAME_MAX_LENGTH: raise ValueError( "Name is too long. Max length: {}, now: {}" "".format(WorkflowCRD.NAME_MAX_LENGTH, len(name)) ) if "." in name: ...
Check the name is valid or not
check_name
python
couler-proj/couler
couler/argo_submitter.py
https://github.com/couler-proj/couler/blob/master/couler/argo_submitter.py
Apache-2.0
def config_defaults(name_salter=None, service_account: str = None): """ Config couler defaults. :param name_salter: function to salt workflow names. :param service_account: name of the default Kubernetes ServiceAccount with which to run workflows :return: """ if name_salter is not No...
Config couler defaults. :param name_salter: function to salt workflow names. :param service_account: name of the default Kubernetes ServiceAccount with which to run workflows :return:
config_defaults
python
couler-proj/couler
couler/core/config.py
https://github.com/couler-proj/couler/blob/master/couler/core/config.py
Apache-2.0
def config_workflow( name=None, user_id=None, timeout=None, time_to_clean=None, cluster_config_file=None, cron_config=None, service_account=None, ): """ Config some workflow-level information. :param name: name of the workflow. :param user_id: user information. :param tim...
Config some workflow-level information. :param name: name of the workflow. :param user_id: user information. :param timeout: maximum running time(seconds). :param time_to_clean: time to keep the workflow after completed(seconds). :param cluster_config_file: cluster specific config :param cr...
config_workflow
python
couler-proj/couler
couler/core/config.py
https://github.com/couler-proj/couler/blob/master/couler/core/config.py
Apache-2.0
def _config_cron_workflow( schedule, concurrency_policy='"Allow"', successful_jobs_history_limit=3, # Default 3 failed_jobs_history_limit=1, # Default 1 starting_deadline_seconds=10, suspend="false", timezone="Asia/Shanghai", ): """ Config the CronWorkflow, see example https://...
Config the CronWorkflow, see example https://github.com/argoproj/argo/blob/master/docs/cron-workflows.md
_config_cron_workflow
python
couler-proj/couler
couler/core/config.py
https://github.com/couler-proj/couler/blob/master/couler/core/config.py
Apache-2.0
def run_script( image, command=None, source=None, args=None, output=None, input=None, env=None, secret=None, resources=None, timeout=None, retry=None, step_name=None, image_pull_policy=None, pool=None, enable_ulogfs=True, daemon=False, volume_mounts=No...
Generate an Argo script template. For example, https://github.com/argoproj/argo/tree/master/examples#scripts--results. :param image: Docker image name :param command: entrypoint array :param source: reference to function name that contains code to be executed :param args: arguments to the step...
run_script
python
couler-proj/couler
couler/core/run_templates.py
https://github.com/couler-proj/couler/blob/master/couler/core/run_templates.py
Apache-2.0
def run_container( image, command=None, args=None, output=None, input=None, env=None, env_from=None, secret=None, resources=None, timeout=None, retry=None, step_name=None, image_pull_policy=None, pool=None, enable_ulogfs=True, daemon=False, volume_moun...
Generate an Argo container template. For example, the template whalesay in https://github.com/argoproj/argo/tree/master/examples#hello-world. :param image: Docker image name :param command: entrypoint array :param args: arguments to the step or task :param output: output artifact for container...
run_container
python
couler-proj/couler
couler/core/run_templates.py
https://github.com/couler-proj/couler/blob/master/couler/core/run_templates.py
Apache-2.0
def _cleanup(): """Cleanup the cached fields, just used for unit test. """ global _secrets, _update_steps_lock, _dag_caller_line, _upstream_dag_task, _upstream_dag_depends_logic, workflow, _steps_outputs # noqa: E501 global _exit_handler_enable, _when_prefix, _when_task, _while_steps, _concurrent_func_...
Cleanup the cached fields, just used for unit test.
_cleanup
python
couler-proj/couler
couler/core/states.py
https://github.com/couler-proj/couler/blob/master/couler/core/states.py
Apache-2.0
def _update_dag_tasks( function_name, caller_line, dependencies, depends_logic, args=None, template_name=None, step_name=None, ): """ A task in DAG of Argo YAML contains name, related template and parameters. Here we insert a single task into the global tasks. """ if step...
A task in DAG of Argo YAML contains name, related template and parameters. Here we insert a single task into the global tasks.
_update_dag_tasks
python
couler-proj/couler
couler/core/step_update_utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/step_update_utils.py
Apache-2.0
def _update_steps(function_name, caller_line, args=None, template_name=None): """ A step in Argo YAML contains name, related template and parameters. Here we insert a single step into the global steps. """ function_id = utils.invocation_name(function_name, caller_line) # Update `steps` only if ...
A step in Argo YAML contains name, related template and parameters. Here we insert a single step into the global steps.
_update_steps
python
couler-proj/couler
couler/core/step_update_utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/step_update_utils.py
Apache-2.0
def argo_safe_name(name): """Some names are to be used in the Argo YAML file. For example, the generateName and template name in https://github.com/argoproj/argo/blob/master/examples/hello-world.yaml. As Argo is to use the YAML as part of Kubernetes job description YAML, these names must follow Kube...
Some names are to be used in the Argo YAML file. For example, the generateName and template name in https://github.com/argoproj/argo/blob/master/examples/hello-world.yaml. As Argo is to use the YAML as part of Kubernetes job description YAML, these names must follow Kubernetes's convention -- no per...
argo_safe_name
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def invocation_location(): """If a function A in file B calls function C, which in turn calls invocation_location(), the call returns information about the invocation, in particular, the caller's name "A" and the line number where A calls C. Return (B + line_number) as function_name if A doesn't exist, ...
If a function A in file B calls function C, which in turn calls invocation_location(), the call returns information about the invocation, in particular, the caller's name "A" and the line number where A calls C. Return (B + line_number) as function_name if A doesn't exist, where users directly calls C i...
invocation_location
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def body(func_obj): """If a function A calls body(), the call returns the Python source code of the function definition body (not including the signature) of A. """ if func_obj is None: return None code = inspect.getsource(func_obj) # Remove function signature code = code[code.find("...
If a function A calls body(), the call returns the Python source code of the function definition body (not including the signature) of A.
body
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def workflow_filename(): """Return the Python file that defines the workflow. """ stacks = inspect.stack() frame = inspect.stack()[len(stacks) - 1] full_path = frame[0].f_code.co_filename filename, _ = os.path.splitext(os.path.basename(full_path)) filename = argo_safe_name(filename) retu...
Return the Python file that defines the workflow.
workflow_filename
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def load_cluster_config(): """Load user provided cluster specification file. """ module_file = os.getenv("couler_cluster_config") if module_file is None: return None spec = util.spec_from_file_location(module_file, module_file) module = util.module_from_spec(spec) spec.loader.exec_m...
Load user provided cluster specification file.
load_cluster_config
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def encode_base64(s): """ Encode a string using base64 and return a binary string. This function is used in Secret creation. For example, the secrets for Argo YAML: https://github.com/argoproj/argo/blob/master/examples/README.md#secrets """ bencode = base64.b64encode(s.encode("utf-8")) r...
Encode a string using base64 and return a binary string. This function is used in Secret creation. For example, the secrets for Argo YAML: https://github.com/argoproj/argo/blob/master/examples/README.md#secrets
encode_base64
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def generate_parameters_run_job(env): """ Generate the inputs parameter for running kubernetes resource """ envs = [] para_index = 0 parameters = [] args = [] if env is not None: if isinstance(env, dict): for key in env: value = env[key] ...
Generate the inputs parameter for running kubernetes resource
generate_parameters_run_job
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def convert_dict_to_env_list(d): """This is to convert a Python dictionary to a list, where each list item is a dict with `name` and `value` keys. """ if not isinstance(d, dict): raise TypeError("The input parameter `d` is not a dict.") env_list = [] for k, v in d.items(): if is...
This is to convert a Python dictionary to a list, where each list item is a dict with `name` and `value` keys.
convert_dict_to_env_list
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def gpu_requested(resources): """ Check whether the requested resources contains GPU. Here resources is a dict like {"cpu": 1, "memory": 2,...}. """ if resources is None: return False if not isinstance(resources, dict): raise TypeError("Parameter resources is required to be a dic...
Check whether the requested resources contains GPU. Here resources is a dict like {"cpu": 1, "memory": 2,...}.
gpu_requested
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def bool_to_str(bool_val): """convert boolean to strings for YAML configuration""" if not isinstance(bool_val, bool): raise TypeError("The bool_val is required to be boolean type") return "true" if bool_val else "false"
convert boolean to strings for YAML configuration
bool_to_str
python
couler-proj/couler
couler/core/utils.py
https://github.com/couler-proj/couler/blob/master/couler/core/utils.py
Apache-2.0
def concurrent(function_list, subtasks=False): """ Start different jobs at the same time subtasks: each function F of function_list contains multiple steps. Then, for each F, we create a sub-steps template. """ if not isinstance(function_list, list): raise SyntaxError("require input func...
Start different jobs at the same time subtasks: each function F of function_list contains multiple steps. Then, for each F, we create a sub-steps template.
concurrent
python
couler-proj/couler
couler/core/syntax/concurrent.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/concurrent.py
Apache-2.0
def when(condition, function): """Generates an Argo conditional step. For example, the coinflip example in https://github.com/argoproj/argo/blob/master/examples/coinflip.yaml. """ pre = condition["pre"] post = condition["post"] if pre is None or post is None: raise SyntaxError("Outpu...
Generates an Argo conditional step. For example, the coinflip example in https://github.com/argoproj/argo/blob/master/examples/coinflip.yaml.
when
python
couler-proj/couler
couler/core/syntax/conditional.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/conditional.py
Apache-2.0
def dag(dependency_graph): """ Generate a DAG of Argo YAML Note: couler.set_dependencies() is more preferable. https://github.com/argoproj/argo/blob/master/examples/dag-coinflip.yaml """ if not isinstance(dependency_graph, list): raise SyntaxError("require input as list") states.wor...
Generate a DAG of Argo YAML Note: couler.set_dependencies() is more preferable. https://github.com/argoproj/argo/blob/master/examples/dag-coinflip.yaml
dag
python
couler-proj/couler
couler/core/syntax/dag.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/dag.py
Apache-2.0
def set_dependencies(step_function, dependencies=None): """ :param step_function: step to run :param dependencies: the list of dependencies of this step. This can be in either of the following forms: 1. a list of step names; 2. a string representing the enhanced depends logic that sp...
:param step_function: step to run :param dependencies: the list of dependencies of this step. This can be in either of the following forms: 1. a list of step names; 2. a string representing the enhanced depends logic that specifies dependencies based on their statuses. See the l...
set_dependencies
python
couler-proj/couler
couler/core/syntax/dag.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/dag.py
Apache-2.0
def set_exit_handler(status, exit_handler): """ Configure the workflow handler Status would be: Succeeded, Failed, or Error. Each status invokes one exit_handler function. https://github.com/argoproj/argo/blob/master/examples/exit-handlers.yaml """ if not callable(exit_handler): rais...
Configure the workflow handler Status would be: Succeeded, Failed, or Error. Each status invokes one exit_handler function. https://github.com/argoproj/argo/blob/master/examples/exit-handlers.yaml
set_exit_handler
python
couler-proj/couler
couler/core/syntax/exit_handler.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/exit_handler.py
Apache-2.0
def exec_while(condition, inner_while): """ Generate the Argo recursive logic. For example https://github.com/argoproj/argo/blob/master/examples/README.md#recursion. """ # _while_lock means 'exec_while' operation begins to work # _while_steps stores logic steps inside the recursion logic sta...
Generate the Argo recursive logic. For example https://github.com/argoproj/argo/blob/master/examples/README.md#recursion.
exec_while
python
couler-proj/couler
couler/core/syntax/recursion.py
https://github.com/couler-proj/couler/blob/master/couler/core/syntax/recursion.py
Apache-2.0
def _container_output(step_name, template_name, output): """Generate output name from an Argo container template. For example, "{{steps.generate-parameter.outputs.parameters.hello-param}}" used in https://github.com/argoproj/argo/tree/master/examples#output-parameters. Each element of return for run_co...
Generate output name from an Argo container template. For example, "{{steps.generate-parameter.outputs.parameters.hello-param}}" used in https://github.com/argoproj/argo/tree/master/examples#output-parameters. Each element of return for run_container is contacted by: couler.step_name.template_name.outp...
_container_output
python
couler-proj/couler
couler/core/templates/output.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/output.py
Apache-2.0
def _script_output(step_name, template_name, output): """Generate output name from an Argo script template. For example, "{{steps.generate.outputs.result}}" in https://github.com/argoproj/argo/tree/master/examples#scripts--results Return of run_script is contacted by: couler.step_name.template_name...
Generate output name from an Argo script template. For example, "{{steps.generate.outputs.result}}" in https://github.com/argoproj/argo/tree/master/examples#scripts--results Return of run_script is contacted by: couler.step_name.template_name.outputs.result
_script_output
python
couler-proj/couler
couler/core/templates/output.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/output.py
Apache-2.0
def _job_output(step_name, template_name): """ :param step_name: :param template_name: https://github.com/argoproj/argo/blob/master/examples/k8s-jobs.yaml#L44 Return the job name and job id for running a job """ job_name = "couler.%s.%s.outputs.parameters.job-name" % ( step_name, ...
:param step_name: :param template_name: https://github.com/argoproj/argo/blob/master/examples/k8s-jobs.yaml#L44 Return the job name and job id for running a job
_job_output
python
couler-proj/couler
couler/core/templates/output.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/output.py
Apache-2.0
def extract_step_return(step_output): """Extract information for run container or script output. step_output is a list with multiple outputs """ ret = {} if isinstance(step_output, list): # The first element of outputs is used for control flow operation step_output = step_output[0] ...
Extract information for run container or script output. step_output is a list with multiple outputs
extract_step_return
python
couler-proj/couler
couler/core/templates/output.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/output.py
Apache-2.0
def to_yaml(self): """Covert the secret to a secret CRD specification.""" d = OrderedDict( { "apiVersion": "v1", "kind": "Secret", "metadata": {"name": self.name, "namespace": self.namespace} if self.namespace != "default" else {"name": self.na...
Covert the secret to a secret CRD specification.
to_yaml
python
couler-proj/couler
couler/core/templates/secret.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/secret.py
Apache-2.0
def to_env_list(self): """ Convert the secret to an environment list, and can be attached to containers. """ secret_envs = [] for key, _ in self.data.items(): secret_env = { "name": key, "valueFrom": {"secretKeyRef": {"name": se...
Convert the secret to an environment list, and can be attached to containers.
to_env_list
python
couler-proj/couler
couler/core/templates/secret.py
https://github.com/couler-proj/couler/blob/master/couler/core/templates/secret.py
Apache-2.0
def run( raw_template, tuning_params, objective, success_condition=None, failure_condition=None, algorithm="random", parallel_trial_count=3, max_trial_count=12, max_failed_trial_count=3, ): """ Args: tuning_params: A dictionary of hyperparameters to be tuned. ...
Args: tuning_params: A dictionary of hyperparameters to be tuned. objective: The dictionary of objective for model training. success_condition: The condition to indicate when a Katib experiment succeeds. failure_condition: The condition to indicate when a Katib ...
run
python
couler-proj/couler
couler/steps/katib.py
https://github.com/couler-proj/couler/blob/master/couler/steps/katib.py
Apache-2.0
def test_workflow_security_context(self): """ The securityContext configuration mostly taken from https://kubernetes.io/docs/tasks/configure-pod-container/security-context/ """ self.assertIsNone(couler.workflow.security_context) flip_coin() self.assertNotIn("secur...
The securityContext configuration mostly taken from https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
test_workflow_security_context
python
couler-proj/couler
couler/tests/workflow_basic_test.py
https://github.com/couler-proj/couler/blob/master/couler/tests/workflow_basic_test.py
Apache-2.0
def random_code() -> None: """ Randomly generate a 'success' or 'fail' to let sys.exit emulate a task final state """ import random task = ['success', 'fail'] res = random.randint(0, 1) res = task[res] print(f'{res}') if res == 'fail': sys.exit(2)
Randomly generate a 'success' or 'fail' to let sys.exit emulate a task final state
random_code
python
couler-proj/couler
examples/depends.py
https://github.com/couler-proj/couler/blob/master/examples/depends.py
Apache-2.0
def __init__( self, data_url, text_features=None, label_column=None, data_dir="", citation="", url="", label_classes=None, process_label=lambda x: x, **kwargs, ): """BuilderConfig for CLUE. Args: text_features:...
BuilderConfig for CLUE. Args: text_features: `dict[string, string]`, map from the name of the feature dict for each text field to the name of the column in the tsv file label_column: `string`, name of the column in the tsv file corresponding to the label dat...
__init__
python
JunnYu/RoFormer_pytorch
examples/clue/classification/clue_10.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/examples/clue/classification/clue_10.py
Apache-2.0
def __init__( self, data_url, text_features=None, label_column=None, data_dir="", citation="", url="", label_classes=None, process_label=lambda x: x, **kwargs, ): """BuilderConfig for CLUE. Args: text_features:...
BuilderConfig for CLUE. Args: text_features: `dict[string, string]`, map from the name of the feature dict for each text field to the name of the column in the tsv file label_column: `string`, name of the column in the tsv file corresponding to the label dat...
__init__
python
JunnYu/RoFormer_pytorch
examples/clue/classification/clue_11.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/examples/clue/classification/clue_11.py
Apache-2.0
def create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = line[1] text_b = None ...
Creates examples for the training and dev sets.
create_examples
python
JunnYu/RoFormer_pytorch
examples/dummpy/task_text_classification_chnsenti.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/examples/dummpy/task_text_classification_chnsenti.py
Apache-2.0
def _init_weight(out: nn.Parameter): """ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:] """ n_pos, dim = out.shape position_enc = np.array( [ ...
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:]
_init_weight
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward(self, seq_len: int, past_key_values_length: int = 0): """`input_ids_shape` is expected to be [bsz x seqlen].""" positions = torch.arange( past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device, ...
`input_ids_shape` is expected to be [bsz x seqlen].
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def load_tf_weights_in_roformer(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFl...
Load tf checkpoints in a pytorch model.
load_tf_weights_in_roformer
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, ...
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attent...
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None...
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored ...
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`tor...
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), ...
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`tor...
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the multiple choice classification loss. Indices should be in ``[0, ..., num_choices-1]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See ...
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`tor...
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``.
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): ...
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside ...
forward
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_roformer.py
Apache-2.0
def build(self, input_shape: tf.TensorShape): """ Build shared token embedding layer Shared weights logic adapted from https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24 """ weight = self._init_weight...
Build shared token embedding layer Shared weights logic adapted from https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24
build
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def _init_weight(n_pos: int, dim: int): """ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:] """ position_enc = np.array( [ [pos / np.power(10000, 2 *...
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:]
_init_weight
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call(self, input_shape: tf.TensorShape, past_key_values_length: int = 0): """Input is expected to be of size [bsz x seqlen].""" bsz, seq_len = input_shape[:2] positions = tf.range( past_key_values_length, seq_len + past_key_values_length, delta=1, ...
Input is expected to be of size [bsz x seqlen].
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: tf.Tensor = None, token_type_ids: tf.Tensor = None, inputs_embeds: tf.Tensor = None, training: bool = False, ) -> tf.Tensor: """ Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor...
Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor`): output embedding tensor.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` ...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the cross entropy classification loss. Indices should be in ``[0, ..., config.vocab_size - 1]``.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-S...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the multiple choice classification loss. Indices should be in ``[0, ..., num_choices]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See ...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
start_positions (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Pos...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence h...
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence has the following format: - single sequence: ``[CLS] X [SEP]`` - pair of sequences: ``[CLS] A [SEP] B [SEP]`` Args: ...
build_inputs_with_special_tokens
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False, ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when addin...
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, ...
get_special_tokens_mask
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: ...
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj...
create_token_type_ids_from_sequences
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence has the following format: - single sequence: ``[CLS] X...
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence has the following format: - single sequence: ``[CLS] X [SEP]`` - pair of sequences: ``[CLS] A [SEP] B [SEP]`` Args: ...
build_inputs_with_special_tokens
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer_fast.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer_fast.py
Apache-2.0
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: ...
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj...
create_token_type_ids_from_sequences
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer_fast.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer_fast.py
Apache-2.0
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--result_dir', help="Directory where the results are saved.") parser.add_argument('--checkpoint_dir', help="Directory that con...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
src/inference.py
https://github.com/salu133445/musegan/blob/master/src/inference.py
MIT
def setup(): """Parse command line arguments, load model parameters, load configurations and setup environment.""" # Parse the command line arguments args = parse_arguments() # Load parameters params = load_yaml(args.params) # Load training configurations config = load_yaml(args.config...
Parse command line arguments, load model parameters, load configurations and setup environment.
setup
python
salu133445/musegan
src/inference.py
https://github.com/salu133445/musegan/blob/master/src/inference.py
MIT
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--result_dir', help="Directory where the results are saved.") parser.add_argument('--checkpoint_dir', help="Directory that con...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def setup(): """Parse command line arguments, load model parameters, load configurations and setup environment.""" # Parse the command line arguments args = parse_arguments() # Load parameters params = load_yaml(args.params) # Load training configurations config = load_yaml(args.config...
Parse command line arguments, load model parameters, load configurations and setup environment.
setup
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def slerp(a, b, t): """Return the spherical linear interpolation of point `a` and `b` at specific ratio `t`.""" omega = np.arccos(np.dot(a / np.linalg.norm(a), b / np.linalg.norm(b))) so = np.sin(omega) return np.sin((1 - t) * omega) / so * a + np.sin(t * omega) / so * b
Return the spherical linear interpolation of point `a` and `b` at specific ratio `t`.
slerp
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def lerp(a, b1, b2, t1, t2): """Return the 2D linear interpolation of point `a`, `b1` and `b2` at specific ratio `t1` and `t2`.""" inter1 = a * (1 - t1) + b1 * t1 inter2 = b2 * (1 - t1) + (b2 + (b1 - a)) * t1 return inter1 * (1 - t2) + t2 * inter2
Return the 2D linear interpolation of point `a`, `b1` and `b2` at specific ratio `t1` and `t2`.
lerp
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def get_input_z(config, params): """Return input latent code to the generator.""" if ((config['mode'] == 'slerp') and (config['rows'] > 1) and (config['columns'] > 1)): raise ValueError("Only supports 1D interpolation in 'slerp' mode.") a = scipy.stats.truncnorm.rvs( config['low...
Return input latent code to the generator.
get_input_z
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument("filepath", help="Path to the data file.") parser.add_argument( "--name", help="File name to save in SharedArray. Defaults to the original file name.", ) ...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
src/process_data.py
https://github.com/salu133445/musegan/blob/master/src/process_data.py
MIT
def create_shared_array(name, shape, dtype): """Create shared array. Prompt if a file with the same name existed.""" try: return sa.create(name, shape, dtype) except FileExistsError: response = "" while response.lower() not in ["y", "n", "yes", "no"]: response = input( ...
Create shared array. Prompt if a file with the same name existed.
create_shared_array
python
salu133445/musegan
src/process_data.py
https://github.com/salu133445/musegan/blob/master/src/process_data.py
MIT
def main(): """Load and save an array to shared memory.""" filepath, name, prefix, dtype = parse_arguments() if name is None: name = os.path.splitext(os.path.basename(filepath))[0] if prefix is not None: name = prefix + "_" + name print("Loading data from '{}'.".format(file...
Load and save an array to shared memory.
main
python
salu133445/musegan
src/process_data.py
https://github.com/salu133445/musegan/blob/master/src/process_data.py
MIT
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--exp_dir', help="Directory to save all the results.") parser.add_argument('--params', help="Path to the model parameter file.") parser.add_argument('--config', help="Pat...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def setup_dirs(config): """Setup an experiment directory structure and update the `params` dictionary with the directory paths.""" # Get experiment directory structure config['exp_dir'] = os.path.realpath(config['exp_dir']) config['src_dir'] = os.path.join(config['exp_dir'], 'src') config['eval_...
Setup an experiment directory structure and update the `params` dictionary with the directory paths.
setup_dirs
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def setup(): """Parse command line arguments, load model parameters, load configurations, setup environment and setup loggers.""" # Parse the command line arguments args = parse_arguments() # Load parameters params = load_yaml(args.params) if params.get('is_accompaniment') and params.get('c...
Parse command line arguments, load model parameters, load configurations, setup environment and setup loggers.
setup
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_training_data(params, config): """Load and return the training data.""" # Load data if params['is_conditional']: raise ValueError("Not supported yet.") else: labels = None LOGGER.info("Loading training data.") data = load_data(config['data_source'], config['data_filename...
Load and return the training data.
load_training_data
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_or_create_samples(params, config): """Load or create the samples used as the sampler inputs.""" # Load sample_z LOGGER.info("Loading sample_z.") sample_z_path = os.path.join(config['model_dir'], 'sample_z.npy') if os.path.exists(sample_z_path): sample_z = np.load(sample_z_path) ...
Load or create the samples used as the sampler inputs.
load_or_create_samples
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def get_n_params(var_list): """Return the number of variables in a variable list.""" return int(np.sum([np.product( [x.value for x in var.get_shape()]) for var in var_list]))
Return the number of variables in a variable list.
get_n_params
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_data_from_npz(filename): """Load and return the training data from a npz file (sparse format).""" with np.load(filename) as f: data = np.zeros(f['shape'], np.bool_) data[[x for x in f['nonzero']]] = True return data
Load and return the training data from a npz file (sparse format).
load_data_from_npz
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def load_data(data_source, data_filename): """Load and return the training data.""" if data_source == 'sa': import SharedArray as sa return sa.attach(data_filename) if data_source == 'npy': return load_data_from_npy(data_filename) if data_source == 'npz': return load_data...
Load and return the training data.
load_data
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def get_samples(n_samples, data, labels=None, use_random_transpose=False): """Return some random samples of the training data.""" indices = np.random.choice(len(data), n_samples, False) if np.issubdtype(data.dtype, np.bool_): sample_data = data[indices] * 2. - 1. else: sample_data = data...
Return some random samples of the training data.
get_samples
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def get_dataset(data, labels=None, batch_size=None, data_shape=None, use_random_transpose=False, num_threads=1): """Create and return a tensorflow dataset from an array.""" if labels is None: dataset = tf.data.Dataset.from_generator( lambda: _gen_data(data), tf.float32) ...
Create and return a tensorflow dataset from an array.
get_dataset
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def vector_to_image(array, inverted=True): """ Convert a batched vector array to an image array. Arguments --------- array : `np.array`, ndim=2 The vector array. Returns ------- image : `np.array`, ndim=4 The image array. """ if array.ndim != 2: raise Va...
Convert a batched vector array to an image array. Arguments --------- array : `np.array`, ndim=2 The vector array. Returns ------- image : `np.array`, ndim=4 The image array.
vector_to_image
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def pianoroll_to_image(pianoroll, colormap=None, inverted=True, boundary_width=1, boundary_color=0, frame=False, gamma=1.): """ Convert a batched pianoroll array to an image array. Arguments --------- pianoroll : `np.array`, ndim=5 The pianoroll...
Convert a batched pianoroll array to an image array. Arguments --------- pianoroll : `np.array`, ndim=5 The pianoroll array. The shape is (n_pianorolls, n_bars, n_timestep, n_pitches, n_tracks). boundary_width : int Linewidth of the boundary lines. Default to 0. boundar...
pianoroll_to_image
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def image_pair(image1, image2, mode='side-by-side', boundary_width=1, boundary_color=0, frame=False): """ Pair two image arrays to one single image array. Arguments --------- image1 : `np.array`, ndim=4 The image array at the left in 'side-by-side' mode or at the top in ...
Pair two image arrays to one single image array. Arguments --------- image1 : `np.array`, ndim=4 The image array at the left in 'side-by-side' mode or at the top in 'top-bottom' mode. image2 : `np.array`, ndim=4 The image array at the right in 'side-by-side' mode or at the ...
image_pair
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def image_grid(image, grid_shape, grid_width=3, grid_color=0, frame=True): """ Convert a batched image array to one merged grid image array. Arguments --------- pianoroll : `np.array`, ndim=4 The pianoroll array. The first axis is the batch axis. The second and third axes are the ti...
Convert a batched image array to one merged grid image array. Arguments --------- pianoroll : `np.array`, ndim=4 The pianoroll array. The first axis is the batch axis. The second and third axes are the time and pitch axes, respectively, of the pianorolls. The last axis is the t...
image_grid
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def save_pianoroll(filename, pianoroll, programs, is_drums, tempo, beat_resolution, lowest_pitch): """Saves a batched pianoroll array to a npz file.""" if not np.issubdtype(pianoroll.dtype, np.bool_): raise TypeError("Input pianoroll array must have a boolean dtype.") if pianoroll...
Saves a batched pianoroll array to a npz file.
save_pianoroll
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT