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 fill_result_with_error(result, error, models_to_create):
"""Fill `result` with errors for all target model arch if we can't build processor"""
result["error"] = error
for framework in FRAMEWORKS:
if framework in models_to_create:
result[framework] = {}
for model_arch in ... | Fill `result` with errors for all target model arch if we can't build processor | fill_result_with_error | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/create_dummy_models.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/create_dummy_models.py | Apache-2.0 |
def build(config_class, models_to_create, output_dir):
"""Create all models for a certain model type.
Args:
config_class (`PretrainedConfig`):
A subclass of `PretrainedConfig` that is used to determine `models_to_create`.
models_to_create (`dict`):
A dictionary containin... | Create all models for a certain model type.
Args:
config_class (`PretrainedConfig`):
A subclass of `PretrainedConfig` that is used to determine `models_to_create`.
models_to_create (`dict`):
A dictionary containing the processor/model classes that we want to create the insta... | build | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/create_dummy_models.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/create_dummy_models.py | Apache-2.0 |
def split_code_in_indented_blocks(code, indent_level="", start_prompt=None, end_prompt=None):
"""
Split `code` into its indented blocks, starting at `indent_level`. If provided, begins splitting after
`start_prompt` and stops at `end_prompt` (but returns what's before `start_prompt` as a first block and wha... |
Split `code` into its indented blocks, starting at `indent_level`. If provided, begins splitting after
`start_prompt` and stops at `end_prompt` (but returns what's before `start_prompt` as a first block and what's
after `end_prompt` as a last block, so `code` is always the same as joining the result of thi... | split_code_in_indented_blocks | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/custom_init_isort.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/custom_init_isort.py | Apache-2.0 |
def ignore_underscore(key):
"Wraps a `key` (that maps an object to string) to lower case and remove underscores."
def _inner(x):
return key(x).lower().replace("_", "")
return _inner | Wraps a `key` (that maps an object to string) to lower case and remove underscores. | ignore_underscore | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/custom_init_isort.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/custom_init_isort.py | Apache-2.0 |
def sort_objects(objects, key=None):
"Sort a list of `objects` following the rules of isort. `key` optionally maps an object to a str."
# If no key is provided, we use a noop.
def noop(x):
return x
if key is None:
key = noop
# Constants are all uppercase, they go first.
constant... | Sort a list of `objects` following the rules of isort. `key` optionally maps an object to a str. | sort_objects | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/custom_init_isort.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/custom_init_isort.py | Apache-2.0 |
def sort_objects_in_import(import_statement):
"""
Return the same `import_statement` but with objects properly sorted.
"""
# This inner function sort imports between [ ].
def _replace(match):
imports = match.groups()[0]
if "," not in imports:
return f"[{imports}]"
... |
Return the same `import_statement` but with objects properly sorted.
| sort_objects_in_import | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/custom_init_isort.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/custom_init_isort.py | Apache-2.0 |
def sort_imports(file, check_only=True):
"""
Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite.
"""
with open(file, encoding="utf-8") as f:
code = f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
... |
Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite.
| sort_imports | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/custom_init_isort.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/custom_init_isort.py | Apache-2.0 |
def get_job_links(workflow_run_id):
"""Extract job names and their job links in a GitHub Actions workflow run"""
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
result = requests.get(url).json()
job_links = {}
try:
job_links.u... | Extract job names and their job links in a GitHub Actions workflow run | get_job_links | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def get_artifacts_links(worflow_run_id):
"""Get all artifact links from a workflow run"""
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100"
result = requests.get(url).json()
artifacts = {}
try:
artifacts.update({artifact["na... | Get all artifact links from a workflow run | get_artifacts_links | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def download_artifact(artifact_name, artifact_url, output_dir, token):
"""Download a GitHub Action artifact from a URL.
The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`,
but it can't be used to download directly. We need to get a redirect UR... | Download a GitHub Action artifact from a URL.
The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`,
but it can't be used to download directly. We need to get a redirect URL first.
See https://docs.github.com/en/rest/actions/artifacts#download-an... | download_artifact | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def get_errors_from_single_artifact(artifact_zip_path, job_links=None):
"""Extract errors from a downloaded artifact (in .zip format)"""
errors = []
failed_tests = []
job_name = None
with zipfile.ZipFile(artifact_zip_path) as z:
for filename in z.namelist():
if not os.path.isdir... | Extract errors from a downloaded artifact (in .zip format) | get_errors_from_single_artifact | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def get_all_errors(artifact_dir, job_links=None):
"""Extract errors from all artifact files"""
errors = []
paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")]
for p in paths:
errors.extend(get_errors_from_single_artifact(p, job_links=job_links))
... | Extract errors from all artifact files | get_all_errors | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def get_model(test):
"""Get the model name from a test method"""
test = test.split("::")[0]
if test.startswith("tests/models/"):
test = test.split("/")[2]
else:
test = None
return test | Get the model name from a test method | get_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_ci_error_statistics.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_ci_error_statistics.py | Apache-2.0 |
def extract_time_from_single_job(job):
"""Extract time info from a single job in a GitHub Actions workflow run"""
job_info = {}
start = job["started_at"]
end = job["completed_at"]
start_datetime = date_parser.parse(start)
end_datetime = date_parser.parse(end)
duration_in_min = round((end... | Extract time info from a single job in a GitHub Actions workflow run | extract_time_from_single_job | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_github_job_time.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_github_job_time.py | Apache-2.0 |
def get_job_time(workflow_run_id):
"""Extract time info for all jobs in a GitHub Actions workflow run"""
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
result = requests.get(url).json()
job_time = {}
try:
job_time.update({job... | Extract time info for all jobs in a GitHub Actions workflow run | get_job_time | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/get_github_job_time.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/get_github_job_time.py | Apache-2.0 |
def get_reply_blocks(self, job_name, job_result, failures, device, text):
"""
failures: A list with elements of the form {"line": full test name, "trace": error trace}
"""
# `text` must be less than 3001 characters in Slack SDK
# keep some room for adding "[Truncated]" when neces... |
failures: A list with elements of the form {"line": full test name, "trace": error trace}
| get_reply_blocks | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/notification_service.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/notification_service.py | Apache-2.0 |
def maybe_append_new_line(code):
"""
Append new line if code snippet is a
Python code snippet
"""
lines = code.split("\n")
if lines[0] in ["py", "python"]:
# add new line before last line being ```
last_line = lines[-1]
lines.pop()
lines.append("\n" + last_line)
... |
Append new line if code snippet is a
Python code snippet
| maybe_append_new_line | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/prepare_for_doc_test.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/prepare_for_doc_test.py | Apache-2.0 |
def maybe_remove_new_line(code):
"""
Remove new line if code snippet is a
Python code snippet
"""
lines = code.split("\n")
if lines[0] in ["py", "python"]:
# add new line before last line being ```
lines = lines[:-2] + lines[-1:]
return "\n".join(lines) |
Remove new line if code snippet is a
Python code snippet
| maybe_remove_new_line | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/prepare_for_doc_test.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/prepare_for_doc_test.py | Apache-2.0 |
def process_doc_file(code_file, add_new_line=True):
"""
Process given file.
Args:
code_file (`str` or `os.PathLike`): The file in which we want to style the docstring.
"""
with open(code_file, "r", encoding="utf-8", newline="\n") as f:
code = f.read()
# fmt: off
splits = co... |
Process given file.
Args:
code_file (`str` or `os.PathLike`): The file in which we want to style the docstring.
| process_doc_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/prepare_for_doc_test.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/prepare_for_doc_test.py | Apache-2.0 |
def process_doc_files(*files, add_new_line=True):
"""
Applies doc styling or checks everything is correct in a list of files.
Args:
files (several `str` or `os.PathLike`): The files to treat.
Whether to restyle file or just check if they should be restyled.
Returns:
List[`s... |
Applies doc styling or checks everything is correct in a list of files.
Args:
files (several `str` or `os.PathLike`): The files to treat.
Whether to restyle file or just check if they should be restyled.
Returns:
List[`str`]: The list of files changed or that should be restyle... | process_doc_files | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/prepare_for_doc_test.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/prepare_for_doc_test.py | Apache-2.0 |
def update_version_in_file(fname, version, pattern):
"""Update the version in one file using a specific pattern."""
with open(fname, "r", encoding="utf-8", newline="\n") as f:
code = f.read()
re_pattern, replace = REPLACE_PATTERNS[pattern]
replace = replace.replace("VERSION", version)
code =... | Update the version in one file using a specific pattern. | update_version_in_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def update_version_in_examples(version):
"""Update the version in all examples files."""
for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):
# Removing some of the folders with non-actively maintained examples from the walk
if "research_projects" in directories:
directories... | Update the version in all examples files. | update_version_in_examples | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def global_version_update(version, patch=False):
"""Update the version in all needed files."""
for pattern, fname in REPLACE_FILES.items():
update_version_in_file(fname, version, pattern)
if not patch:
update_version_in_examples(version) | Update the version in all needed files. | global_version_update | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def get_version():
"""Reads the current version in the __init__."""
with open(REPLACE_FILES["init"], "r") as f:
code = f.read()
default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
return packaging.version.parse(default_version) | Reads the current version in the __init__. | get_version | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def pre_release_work(patch=False):
"""Do all the necessary pre-release steps."""
# First let's get the default version: base version if we are in dev, bump minor otherwise.
default_version = get_version()
if patch and default_version.is_devrelease:
raise ValueError("Can't create a patch version ... | Do all the necessary pre-release steps. | pre_release_work | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def post_release_work():
"""Do all the necesarry post-release steps."""
# First let's get the current version
current_version = get_version()
dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
current_version = current_version.base_version
# Check with the user we got t... | Do all the necesarry post-release steps. | post_release_work | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/release.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/release.py | Apache-2.0 |
def clean_code(content):
"""
Remove docstrings, empty line or comments from `content`.
"""
# fmt: off
# Remove docstrings by splitting on triple " then triple ':
splits = content.split('\"\"\"')
content = "".join(splits[::2])
splits = content.split("\'\'\'")
# fmt: on
content = "... |
Remove docstrings, empty line or comments from `content`.
| clean_code | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def get_all_tests():
"""
Return a list of paths to all test folders and files under `tests`. All paths are rooted at `tests`.
- folders under `tests`: `tokenization`, `pipelines`, etc. The folder `models` is excluded.
- folders under `tests/models`: `bert`, `gpt2`, etc.
- test files under `tests`: ... |
Return a list of paths to all test folders and files under `tests`. All paths are rooted at `tests`.
- folders under `tests`: `tokenization`, `pipelines`, etc. The folder `models` is excluded.
- folders under `tests/models`: `bert`, `gpt2`, etc.
- test files under `tests`: `test_modeling_common.py`, `... | get_all_tests | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def diff_is_docstring_only(repo, branching_point, filename):
"""
Check if the diff is only in docstrings in a filename.
"""
with checkout_commit(repo, branching_point):
with open(filename, "r", encoding="utf-8") as f:
old_content = f.read()
with open(filename, "r", encoding="utf... |
Check if the diff is only in docstrings in a filename.
| diff_is_docstring_only | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def get_test_dependencies(test_fname):
"""
Get the dependencies of a test file.
"""
with open(os.path.join(PATH_TO_TRANFORMERS, test_fname), "r", encoding="utf-8") as f:
content = f.read()
# Tests only have relative imports for other test files
# TODO Sylvain: handle relative imports cl... |
Get the dependencies of a test file.
| get_test_dependencies | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def create_reverse_dependency_tree():
"""
Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
"""
modules = [
str(f.relative_to(PATH_TO_TRANFORMERS))
for f in (Path(PATH_TO_TRANFORMERS) / "src/transformers").glob("**/*.py")... |
Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
| create_reverse_dependency_tree | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def get_tree_starting_at(module, edges):
"""
Returns the tree starting at a given module following all edges in the following format: [module, [list of edges
starting at module], [list of edges starting at the preceding level], ...]
"""
vertices_seen = [module]
new_edges = [edge for edge in edge... |
Returns the tree starting at a given module following all edges in the following format: [module, [list of edges
starting at module], [list of edges starting at the preceding level], ...]
| get_tree_starting_at | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def print_tree_deps_of(module, all_edges=None):
"""
Prints the tree of modules depending on a given module.
"""
if all_edges is None:
all_edges = create_reverse_dependency_tree()
tree = get_tree_starting_at(module, all_edges)
# The list of lines is a list of tuples (line_to_be_printed, ... |
Prints the tree of modules depending on a given module.
| print_tree_deps_of | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def create_reverse_dependency_map():
"""
Create the dependency map from module/test filename to the list of modules/tests that depend on it (even
recursively).
"""
modules = [
str(f.relative_to(PATH_TO_TRANFORMERS))
for f in (Path(PATH_TO_TRANFORMERS) / "src/transformers").glob("**/*... |
Create the dependency map from module/test filename to the list of modules/tests that depend on it (even
recursively).
| create_reverse_dependency_map | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def module_to_test_file(module_fname):
"""
Returns the name of the file(s) where `module_fname` is tested.
"""
splits = module_fname.split(os.path.sep)
# Special map has priority
short_name = os.path.sep.join(splits[2:])
if short_name in SPECIAL_MODULE_TO_TEST_MAP:
test_file = SPECI... |
Returns the name of the file(s) where `module_fname` is tested.
| module_to_test_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def sanity_check():
"""
Checks that all test files can be touched by a modification in at least one module/utils. This test ensures that
newly-added test files are properly mapped to some module or utils, so they can be run by the CI.
"""
# Grab all module and utils
all_files = [
str(p.r... |
Checks that all test files can be touched by a modification in at least one module/utils. This test ensures that
newly-added test files are properly mapped to some module or utils, so they can be run by the CI.
| sanity_check | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def filter_tests(output_file, filters):
"""
Reads the content of the output file and filters out all the tests in a list of given folders.
Args:
output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
filters (`List[str]`): A list of folders to filter.
""... |
Reads the content of the output file and filters out all the tests in a list of given folders.
Args:
output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
filters (`List[str]`): A list of folders to filter.
| filter_tests | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/tests_fetcher.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/tests_fetcher.py | Apache-2.0 |
def get_frameworks_table():
"""
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
modules.
"""
# Dictionary model names to config.
config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
model_... |
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
modules.
| get_frameworks_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/update_metadata.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/update_metadata.py | Apache-2.0 |
def update_pipeline_and_auto_class_table(table):
"""
Update the table of model class to (pipeline_tag, auto_class) without removing old keys if they don't exist
anymore.
"""
auto_modules = [
transformers_module.models.auto.modeling_auto,
transformers_module.models.auto.modeling_tf_au... |
Update the table of model class to (pipeline_tag, auto_class) without removing old keys if they don't exist
anymore.
| update_pipeline_and_auto_class_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/update_metadata.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/update_metadata.py | Apache-2.0 |
def update_metadata(token, commit_sha):
"""
Update the metada for the Transformers repo.
"""
with tempfile.TemporaryDirectory() as tmp_dir:
repo = Repository(
tmp_dir, clone_from="huggingface/transformers-metadata", repo_type="dataset", use_auth_token=token
)
framewo... |
Update the metada for the Transformers repo.
| update_metadata | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/utils/update_metadata.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/utils/update_metadata.py | Apache-2.0 |
def allocate(self, shape, dtype, comp_config, pin_memory=None, name=None):
"""Allocate a compressed TorchTensor. Round up the shape to group boundary."""
assert comp_config.num_bits == 4 and dtype == np.float16
group_size, group_dim = comp_config.group_size, comp_config.group_dim
# Rou... | Allocate a compressed TorchTensor. Round up the shape to group boundary. | allocate | python | FMInference/FlexLLMGen | flexllmgen/compression.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/compression.py | Apache-2.0 |
def compress(self, tensor, comp_config):
"""Compress a torch.Tensor. Round up the shape to group boundary."""
group_size, num_bits, group_dim, symmetric = (
comp_config.group_size, comp_config.num_bits,
comp_config.group_dim, comp_config.symmetric)
assert num_bits == 4 an... | Compress a torch.Tensor. Round up the shape to group boundary. | compress | python | FMInference/FlexLLMGen | flexllmgen/compression.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/compression.py | Apache-2.0 |
def suppress_output(rank):
"""Suppress printing on the current device. Force printing with `force=True`."""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', True)
if force:
builtin_print("rank #%d:" % ra... | Suppress printing on the current device. Force printing with `force=True`. | suppress_output | python | FMInference/FlexLLMGen | flexllmgen/dist_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/dist_utils.py | Apache-2.0 |
def disable_hf_opt_init():
"""
Disable the redundant default initialization to accelerate model creation.
"""
import transformers
setattr(transformers.models.opt.modeling_opt.OPTPreTrainedModel,
"_init_weights", lambda *args, **kwargs: None) |
Disable the redundant default initialization to accelerate model creation.
| disable_hf_opt_init | python | FMInference/FlexLLMGen | flexllmgen/opt_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/opt_config.py | Apache-2.0 |
def general_copy(dst: TorchTensor, dst_indices: Tuple[slice],
src: TorchTensor, src_indices: Tuple[slice]):
"""Launch a general asynchronous copy between two tensors.
It is equivalent to `dst[dst_indices] = src[src_indices]` in numpy syntax.
The copy is asynchronous. To wait for the copy to... | Launch a general asynchronous copy between two tensors.
It is equivalent to `dst[dst_indices] = src[src_indices]` in numpy syntax.
The copy is asynchronous. To wait for the copy to complete, you need to call
>>> env.disk.synchronize()
>>> torch.cuda.synchronize()
| general_copy | python | FMInference/FlexLLMGen | flexllmgen/pytorch_backend.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/pytorch_backend.py | Apache-2.0 |
def piecewise_linear_func(xs, ys):
"""Return a function created by linear inerpolation."""
indices = np.argsort(xs)
xs = [xs[i] for i in indices]
ys = [ys[i] for i in indices]
# pad left and right
k = 1e5
delta_x_left = xs[0] - xs[1]
delta_y_left = ys[0] - ys[1]
delta_x_right = xs[-... | Return a function created by linear inerpolation. | piecewise_linear_func | python | FMInference/FlexLLMGen | flexllmgen/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/utils.py | Apache-2.0 |
def vector_gather(vectors, indices):
"""
Gathers (batched) vectors according to indices.
Arguments:
vectors: Tensor[S, B, H]
indices: Tensor[K, B]
Returns:
Tensor[K, B, H]
"""
S, B, H = vectors.shape
K, B2 = indices.shape
assert B == B2
indices = indices.resha... |
Gathers (batched) vectors according to indices.
Arguments:
vectors: Tensor[S, B, H]
indices: Tensor[K, B]
Returns:
Tensor[K, B, H]
| vector_gather | python | FMInference/FlexLLMGen | flexllmgen/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/utils.py | Apache-2.0 |
def serialize_match_pair(
row: pd.core.series.Series,
column_mapA: Dict[str, str],
column_mapB: Dict[str, str],
add_instruction: bool,
instruction: str,
suffix: str,
prod_name: str,
sep_tok: str,
nan_tok: str,
) -> str:
"""Turn structured pair of entities into string for matching... | Turn structured pair of entities into string for matching. | serialize_match_pair | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def serialize_imputation(
row: pd.core.series.Series,
column_map: Dict[str, str],
impute_col: str,
add_instruction: bool,
instruction: str,
suffix: str,
sep_tok: str,
nan_tok: str,
) -> str:
"""Turn single entity into string for imputation."""
assert impute_col not in column_map,... | Turn single entity into string for imputation. | serialize_imputation | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def serialize_error_detection_spelling(
row: pd.core.series.Series,
add_instruction: bool,
instruction: str,
suffix: str,
sep_tok: str,
nan_tok: str,
) -> str:
"""Turn single cell into string for error detection."""
column_map = {row["col_name"]: row["col_name"]}
res = f"Is there a x... | Turn single cell into string for error detection. | serialize_error_detection_spelling | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def serialize_schema_match(
row: pd.core.series.Series,
add_prefix: bool,
instruction: str,
suffix: str,
sep_tok: str,
nan_tok: str,
) -> str:
"""Turn single cell into string for schema matching."""
res = f"A is {row['left']}. B is {row['right']}. {suffix} "
if add_prefix:
re... | Turn single cell into string for schema matching. | serialize_schema_match | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def read_blocked_pairs(
split_path: str,
tableA: pd.DataFrame,
tableB: pd.DataFrame,
cols_to_drop: List[str],
col_renaming: Dict[str, str],
add_instruction: bool,
instruction: str,
suffix: str,
prod_name: str,
sep_tok: str,
nan_tok: str,
) -> pd.DataFrame:
"""Read in pre-... | Read in pre-blocked pairs with T/F match labels. | read_blocked_pairs | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def read_imputation_single(
split_path: str,
impute_col: str,
cols_to_drop: List[str],
col_renaming: Dict[str, str],
add_instruction: bool,
instruction: str,
suffix: str,
sep_tok: str,
nan_tok: str,
) -> pd.DataFrame:
"""Read in table and create label impute col."""
table = p... | Read in table and create label impute col. | read_imputation_single | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def read_raw_data(
data_dir: str,
add_instruction: bool = False,
task_instruction_idx: int = 0,
sep_tok: str = ".",
nan_tok: str = "nan",
):
"""Read in data where each directory is unique for a task."""
data_files_sep = {"test": {}, "train": {}, "validation": {}}
logger.info(f"Processing... | Read in data where each directory is unique for a task. | read_raw_data | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/data_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/data_utils.py | Apache-2.0 |
def get_manual_prompt(data_dir: str, example: pd.Series) -> str:
"""Get manual prompt for data name."""
if data_dir not in constants.DATA2TASK.keys():
raise ValueError(f"{data_dir} not recognized for prompts")
subkey_attr = constants.DATA2EXAMPLE_SUBKEY_ATTR[data_dir]
if subkey_attr is None:
... | Get manual prompt for data name. | get_manual_prompt | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/prompt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/prompt_utils.py | Apache-2.0 |
def get_random_prompt(train_data: pd.DataFrame, num_examples: int = 10) -> str:
"""Get random examples for prompt from trian data."""
prefix_exs_rows = sample_train_data(train_data, num_examples)
serialized_prefixes = [
(txt + label).strip()
for txt, label in zip(prefix_exs_rows["text"], pre... | Get random examples for prompt from trian data. | get_random_prompt | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/prompt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/prompt_utils.py | Apache-2.0 |
def get_hard_samples(
df: pd.DataFrame, errors_index: pd.Index, embs: np.ndarray, num_clusters: int = 10
) -> Tuple[pd.DataFrame, Any]:
"""
Choose samples that are nearby eachother in embedding space but different labels.
One sample must be an error.
"""
from sklearn.metrics.pairwise import cos... |
Choose samples that are nearby eachother in embedding space but different labels.
One sample must be an error.
| get_hard_samples | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/prompt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/prompt_utils.py | Apache-2.0 |
def get_validation_embs_prompts(
df: pd.DataFrame,
num_exs: int = 10,
model_name: str = "sentence-transformers/sentence-t5-base",
task: str = "entity_matching",
) -> str:
"""
Generate prompt from cluster of data errors.
We use sentence embeddings to cluster each error example.
We then s... |
Generate prompt from cluster of data errors.
We use sentence embeddings to cluster each error example.
We then select `num_exs` examples from each cluster.
If all examples are of one class, we randomly swap one
example for an instance from the validation data with the missing
class.
| get_validation_embs_prompts | python | FMInference/FlexLLMGen | flexllmgen/apps/data_wrangle/utils/prompt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/flexllmgen/apps/data_wrangle/utils/prompt_utils.py | Apache-2.0 |
def consolidate_shard_weights(
shard_weights: List[Dict[str, torch.Tensor]],
shard_metadata: List[Dict[str, Any]],
with_module_buffers: bool = True,
strict: bool = True,
) -> Dict[str, torch.Tensor]:
"""
Given a list of weights and meta data associated to N shards, reconstruct
... |
Given a list of weights and meta data associated to N shards, reconstruct
the weights of an equivalent consolidated (non-sharded) state dict.
Module parameters are consolidated using the shard metadata.
Module buffers are taken from shard 0: this assumes that module buffers
are either synchronized ... | consolidate_shard_weights | python | FMInference/FlexLLMGen | scripts/step_2_consolidate_992_shards_to_singleton.py | https://github.com/FMInference/FlexLLMGen/blob/master/scripts/step_2_consolidate_992_shards_to_singleton.py | Apache-2.0 |
def _handle_one(parts, is_weight):
"""Make it look like a normal LayerNorm"""
n_parts = len(parts)
err_msg = f"Redundant ModelParallelFusedLayerNorm params have been updated."
if is_weight:
init = 1.0
assert not torch.logical_and(parts[0].ne(1), parts[1].ne(1)).any(), err_msg
else:
... | Make it look like a normal LayerNorm | _handle_one | python | FMInference/FlexLLMGen | scripts/step_2_consolidate_992_shards_to_singleton.py | https://github.com/FMInference/FlexLLMGen/blob/master/scripts/step_2_consolidate_992_shards_to_singleton.py | Apache-2.0 |
def _get_css_file(template_name, url, filename):
"""Get a css file and download it to the templates dir"""
directory = osp.join(templates_dir, template_name, "static")
dest = osp.join(directory, filename)
if osp.exists(dest):
print("Already have CSS: %s, moving on." % dest)
return
if... | Get a css file and download it to the templates dir | _get_css_file | python | jupyter/nbconvert | hatch_build.py | https://github.com/jupyter/nbconvert/blob/master/hatch_build.py | BSD-3-Clause |
def _get_css_files():
"""Get all of the css files if necessary"""
in_checkout = osp.exists(osp.abspath(osp.join(here, "..", ".git")))
if in_checkout:
print("Not running from git, nothing to do")
return
for template_name, resources in template_css_urls.items():
for url, filename ... | Get all of the css files if necessary | _get_css_files | python | jupyter/nbconvert | hatch_build.py | https://github.com/jupyter/nbconvert/blob/master/hatch_build.py | BSD-3-Clause |
def initialize(self, argv=None):
"""Initialize application, notebooks, writer, and postprocessor"""
# See https://bugs.python.org/issue37373 :(
if sys.version_info > (3, 8) and sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
... | Initialize application, notebooks, writer, and postprocessor | initialize | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def init_notebooks(self):
"""Construct the list of notebooks.
If notebooks are passed on the command-line,
they override (rather than add) notebooks specified in config files.
Glob each notebook to replace notebook patterns with filenames.
"""
# Specifying notebooks on ... | Construct the list of notebooks.
If notebooks are passed on the command-line,
they override (rather than add) notebooks specified in config files.
Glob each notebook to replace notebook patterns with filenames.
| init_notebooks | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def init_writer(self):
"""Initialize the writer (which is stateless)"""
self._writer_class_changed({"new": self.writer_class})
if self.writer_factory:
self.writer = self.writer_factory(parent=self)
if hasattr(self.writer, "build_directory") and self.writer.build_directory... | Initialize the writer (which is stateless) | init_writer | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def init_postprocessor(self):
"""Initialize the postprocessor (which is stateless)"""
self._postprocessor_class_changed({"new": self.postprocessor_class})
if self.postprocessor_factory:
self.postprocessor = self.postprocessor_factory(parent=self) | Initialize the postprocessor (which is stateless) | init_postprocessor | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def _notebook_filename_to_name(self, notebook_filename):
"""
Returns the notebook name from the notebook filename by
applying `output_base` pattern and stripping extension
"""
basename = os.path.basename(notebook_filename)
notebook_name = basename[: basename.rfind(".")]
... |
Returns the notebook name from the notebook filename by
applying `output_base` pattern and stripping extension
| _notebook_filename_to_name | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def init_single_notebook_resources(self, notebook_filename):
"""Step 1: Initialize resources
This initializes the resources dictionary for a single notebook.
Returns
-------
dict
resources dictionary for a single notebook that MUST include the following keys:
... | Step 1: Initialize resources
This initializes the resources dictionary for a single notebook.
Returns
-------
dict
resources dictionary for a single notebook that MUST include the following keys:
- config_dir: the location of the Jupyter config directory
... | init_single_notebook_resources | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def export_single_notebook(self, notebook_filename, resources, input_buffer=None):
"""Step 2: Export the notebook
Exports the notebook to a particular format according to the specified
exporter. This function returns the output and (possibly modified)
resources from the exporter.
... | Step 2: Export the notebook
Exports the notebook to a particular format according to the specified
exporter. This function returns the output and (possibly modified)
resources from the exporter.
Parameters
----------
notebook_filename : str
name of notebook ... | export_single_notebook | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def write_single_notebook(self, output, resources):
"""Step 3: Write the notebook to file
This writes output from the exporter to file using the specified writer.
It returns the results from the writer.
Parameters
----------
output :
resources : dict
... | Step 3: Write the notebook to file
This writes output from the exporter to file using the specified writer.
It returns the results from the writer.
Parameters
----------
output :
resources : dict
resources for a single notebook including name, config directo... | write_single_notebook | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def postprocess_single_notebook(self, write_results):
"""Step 4: Post-process the written file
Only used if a postprocessor has been specified. After the
converted notebook is written to a file in Step 3, this post-processes
the notebook.
"""
# Post-process if post proce... | Step 4: Post-process the written file
Only used if a postprocessor has been specified. After the
converted notebook is written to a file in Step 3, this post-processes
the notebook.
| postprocess_single_notebook | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def convert_single_notebook(self, notebook_filename, input_buffer=None):
"""Convert a single notebook.
Performs the following steps:
1. Initialize notebook resources
2. Export the notebook to a particular format
3. Write the exported notebook to file
4. ... | Convert a single notebook.
Performs the following steps:
1. Initialize notebook resources
2. Export the notebook to a particular format
3. Write the exported notebook to file
4. (Maybe) postprocess the written file
Parameters
----------
... | convert_single_notebook | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def convert_notebooks(self):
"""Convert the notebooks in the self.notebooks traitlet"""
# no notebooks to convert!
if len(self.notebooks) == 0 and not self.from_stdin:
self.print_help()
sys.exit(-1)
if not self.export_format:
msg = (
... | Convert the notebooks in the self.notebooks traitlet | convert_notebooks | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def document_flag_help(self):
"""
Return a string containing descriptions of all the flags.
"""
flags = "The following flags are defined:\n\n"
for flag, (cfg, fhelp) in self.flags.items():
flags += f"{flag}\n"
flags += indent(fill(fhelp, 80)) + "\n\n"
... |
Return a string containing descriptions of all the flags.
| document_flag_help | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def document_alias_help(self):
"""Return a string containing all of the aliases"""
aliases = "The following aliases are defined:\n\n"
for alias, longname in self.aliases.items():
aliases += f"\t**{alias}** ({longname})\n\n"
return aliases | Return a string containing all of the aliases | document_alias_help | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def document_config_options(self):
"""
Provides a much improves version of the configuration documentation by
breaking the configuration options into app, exporter, writer,
preprocessor, postprocessor, and other sections.
"""
categories = {
category: [c for c ... |
Provides a much improves version of the configuration documentation by
breaking the configuration options into app, exporter, writer,
preprocessor, postprocessor, and other sections.
| document_config_options | python | jupyter/nbconvert | nbconvert/nbconvertapp.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/nbconvertapp.py | BSD-3-Clause |
def export(exporter, nb, **kw):
"""
Export a notebook object using specific exporter class.
Parameters
----------
exporter : ``Exporter`` class or instance
Class or instance of the exporter that should be used. If the
method initializes its own instance of the class, it is ASSUMED ... |
Export a notebook object using specific exporter class.
Parameters
----------
exporter : ``Exporter`` class or instance
Class or instance of the exporter that should be used. If the
method initializes its own instance of the class, it is ASSUMED that
the class type provided ex... | export | python | jupyter/nbconvert | nbconvert/exporters/base.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/base.py | BSD-3-Clause |
def get_exporter(name, config=get_config()): # noqa: B008
"""Given an exporter name or import path, return a class ready to be instantiated
Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled
"""
if name == "ipynb":
name = "notebook"
try:
exporter... | Given an exporter name or import path, return a class ready to be instantiated
Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled
| get_exporter | python | jupyter/nbconvert | nbconvert/exporters/base.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/base.py | BSD-3-Clause |
def get_export_names(config=get_config()): # noqa: B008
"""Return a list of the currently supported export targets
Exporters can be found in external packages by registering
them as an nbconvert.exporter entrypoint.
"""
exporters = sorted(e.name for e in entry_points(group="nbconvert.exporters"))
... | Return a list of the currently supported export targets
Exporters can be found in external packages by registering
them as an nbconvert.exporter entrypoint.
| get_export_names | python | jupyter/nbconvert | nbconvert/exporters/base.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/base.py | BSD-3-Clause |
def __init__(self, config=None, **kw):
"""
Public constructor
Parameters
----------
config : ``traitlets.config.Config``
User configuration instance.
`**kw`
Additional keyword arguments passed to parent __init__
"""
with_default_c... |
Public constructor
Parameters
----------
config : ``traitlets.config.Config``
User configuration instance.
`**kw`
Additional keyword arguments passed to parent __init__
| __init__ | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def from_notebook_node(
self, nb: NotebookNode, resources: t.Any | None = None, **kw: t.Any
) -> tuple[NotebookNode, dict[str, t.Any]]:
"""
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :class:`~nbformat.NotebookNode`
Notebo... |
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :class:`~nbformat.NotebookNode`
Notebook node (dict-like with attr-access)
resources : dict
Additional resources that can be accessed read/write by
preprocessors and... | from_notebook_node | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def from_filename(
self, filename: str, resources: dict[str, t.Any] | None = None, **kw: t.Any
) -> tuple[NotebookNode, dict[str, t.Any]]:
"""
Convert a notebook from a notebook file.
Parameters
----------
filename : str
Full filename of the notebook file... |
Convert a notebook from a notebook file.
Parameters
----------
filename : str
Full filename of the notebook file to open and convert.
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
... | from_filename | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def from_file(
self, file_stream: t.Any, resources: dict[str, t.Any] | None = None, **kw: t.Any
) -> tuple[NotebookNode, dict[str, t.Any]]:
"""
Convert a notebook from a notebook file.
Parameters
----------
file_stream : file-like object
Notebook file-lik... |
Convert a notebook from a notebook file.
Parameters
----------
file_stream : file-like object
Notebook file-like object to convert.
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
`*... | from_file | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def register_preprocessor(self, preprocessor, enabled=False):
"""
Register a preprocessor.
Preprocessors are classes that act upon the notebook before it is
passed into the Jinja templating engine. Preprocessors are also
capable of passing additional information to the Jinja
... |
Register a preprocessor.
Preprocessors are classes that act upon the notebook before it is
passed into the Jinja templating engine. Preprocessors are also
capable of passing additional information to the Jinja
templating engine.
Parameters
----------
pre... | register_preprocessor | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def _init_preprocessors(self):
"""
Register all of the preprocessors needed for this exporter, disabled
unless specified explicitly.
"""
self._preprocessors = []
# Load default preprocessors (not necessarily enabled by default).
for preprocessor in self.default_p... |
Register all of the preprocessors needed for this exporter, disabled
unless specified explicitly.
| _init_preprocessors | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def _preprocess(self, nb, resources):
"""
Preprocess the notebook before passing it into the Jinja engine.
To preprocess the notebook is to successively apply all the
enabled preprocessors. Output from each preprocessor is passed
along to the next one.
Parameters
... |
Preprocess the notebook before passing it into the Jinja engine.
To preprocess the notebook is to successively apply all the
enabled preprocessors. Output from each preprocessor is passed
along to the next one.
Parameters
----------
nb : notebook node
... | _preprocess | python | jupyter/nbconvert | nbconvert/exporters/exporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/exporter.py | BSD-3-Clause |
def find_lab_theme(theme_name):
"""
Find a JupyterLab theme location by name.
Parameters
----------
theme_name : str
The name of the labextension theme you want to find.
Raises
------
ValueError
If the theme was not found, or if it was not specific enough.
Returns
... |
Find a JupyterLab theme location by name.
Parameters
----------
theme_name : str
The name of the labextension theme you want to find.
Raises
------
ValueError
If the theme was not found, or if it was not specific enough.
Returns
-------
theme_name: str
... | find_lab_theme | python | jupyter/nbconvert | nbconvert/exporters/html.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/html.py | BSD-3-Clause |
def markdown2html(self, context, source):
"""Markdown to HTML filter respecting the anchor_link_text setting"""
cell = context.get("cell", {})
attachments = cell.get("attachments", {})
path = context.get("resources", {}).get("metadata", {}).get("path", "")
renderer = IPythonRend... | Markdown to HTML filter respecting the anchor_link_text setting | markdown2html | python | jupyter/nbconvert | nbconvert/exporters/html.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/html.py | BSD-3-Clause |
def resources_include_js(name, module=False):
"""Get the resources include JS for a name. If module=True, import as ES module"""
env = self.environment
code = f"""<script {'type="module"' if module else ""}>\n{env.loader.get_source(env, name)[0]}</script>"""
return markup... | Get the resources include JS for a name. If module=True, import as ES module | resources_include_js | python | jupyter/nbconvert | nbconvert/exporters/html.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/html.py | BSD-3-Clause |
def resources_include_url(name):
"""Get the resources include url for a name."""
env = self.environment
mime_type, encoding = mimetypes.guess_type(name)
try:
# we try to load via the jinja loader, but that tries to load
# as (encoded) text
... | Get the resources include url for a name. | resources_include_url | python | jupyter/nbconvert | nbconvert/exporters/html.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/html.py | BSD-3-Clause |
def prepend_to_env_search_path(varname, value, envdict):
"""Add value to the environment variable varname in envdict
e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ)
"""
if not value:
return # Nothing to add
envdict[varname] = value + os.pathsep + envdict.get(va... | Add value to the environment variable varname in envdict
e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ)
| prepend_to_env_search_path | python | jupyter/nbconvert | nbconvert/exporters/pdf.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/pdf.py | BSD-3-Clause |
def run_command(self, command_list, filename, count, log_function, raise_on_failure=None):
"""Run command_list count times.
Parameters
----------
command_list : list
A list of args to provide to Popen. Each element of this
list will be interpolated with the filen... | Run command_list count times.
Parameters
----------
command_list : list
A list of args to provide to Popen. Each element of this
list will be interpolated with the filename to convert.
filename : unicode
The name of the file to convert.
count ... | run_command | python | jupyter/nbconvert | nbconvert/exporters/pdf.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/pdf.py | BSD-3-Clause |
def default_filters(self):
"""Override filter_data_type to use native rst outputs"""
dtf = DataTypeFilter()
dtf.display_data_priority = [self.output_mimetype, *dtf.display_data_priority]
filters = dict(super().default_filters())
filters["filter_data_type"] = dtf
return fi... | Override filter_data_type to use native rst outputs | default_filters | python | jupyter/nbconvert | nbconvert/exporters/rst.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/rst.py | BSD-3-Clause |
def _get_language_exporter(self, lang_name):
"""Find an exporter for the language name from notebook metadata.
Uses the nbconvert.exporters.script group of entry points.
Returns None if no exporter is found.
"""
if lang_name not in self._lang_exporters:
try:
... | Find an exporter for the language name from notebook metadata.
Uses the nbconvert.exporters.script group of entry points.
Returns None if no exporter is found.
| _get_language_exporter | python | jupyter/nbconvert | nbconvert/exporters/script.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/script.py | BSD-3-Clause |
def recursive_update(target, new):
"""Recursively update one dictionary using another.
None values will delete their keys.
"""
for k, v in new.items():
if isinstance(v, dict):
if k not in target:
target[k] = {}
recursive_update(target[k], v)
if... | Recursively update one dictionary using another.
None values will delete their keys.
| recursive_update | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
def __init__(self, config=None, **kw):
"""
Public constructor
Parameters
----------
config : config
User configuration instance.
extra_loaders : list[of Jinja Loaders]
ordered list of Jinja loader to find templates. Will be tried in order
... |
Public constructor
Parameters
----------
config : config
User configuration instance.
extra_loaders : list[of Jinja Loaders]
ordered list of Jinja loader to find templates. Will be tried in order
before the default FileSystem ones.
te... | __init__ | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
def _load_template(self):
"""Load the Jinja template object from the template file
This is triggered by various trait changes that would change the template.
"""
# this gives precedence to a raw_template if present
with self.hold_trait_notifications():
if self.templ... | Load the Jinja template object from the template file
This is triggered by various trait changes that would change the template.
| _load_template | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
def from_notebook_node( # type:ignore[explicit-override, override]
self, nb: NotebookNode, resources: dict[str, t.Any] | None = None, **kw: t.Any
) -> tuple[str, dict[str, t.Any]]:
"""
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :cla... |
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :class:`~nbformat.NotebookNode`
Notebook node
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
| from_notebook_node | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
def _register_filter(self, environ, name, jinja_filter):
"""
Register a filter.
A filter is a function that accepts and acts on one string.
The filters are accessible within the Jinja templating engine.
Parameters
----------
name : str
name to give th... |
Register a filter.
A filter is a function that accepts and acts on one string.
The filters are accessible within the Jinja templating engine.
Parameters
----------
name : str
name to give the filter in the Jinja engine
filter : filter
| _register_filter | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
def get_template_names(self):
"""Finds a list of template names where each successive template name is the base template"""
template_names = []
root_dirs = self.get_prefix_root_dirs()
base_template: str | None = self.template_name
merged_conf: dict[str, t.Any] = {} # the configu... | Finds a list of template names where each successive template name is the base template | get_template_names | python | jupyter/nbconvert | nbconvert/exporters/templateexporter.py | https://github.com/jupyter/nbconvert/blob/master/nbconvert/exporters/templateexporter.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.