response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Treebeard's path comparison logic can fail on certain locales such as sk_SK, which
sort numbers after letters. To avoid this, we explicitly set the collation for the
'path' column to the (non-locale-specific) 'C' collation.
See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ | def set_collection_path_collation(apps, schema_editor):
"""
Treebeard's path comparison logic can fail on certain locales such as sk_SK, which
sort numbers after letters. To avoid this, we explicitly set the collation for the
'path' column to the (non-locale-specific) 'C' collation.
See: https://gr... |
Give the groups who currently manage all collections permission to manage root collections | def grant_instance_level_collection_management_permissions(apps, schema_editor):
"""
Give the groups who currently manage all collections permission to manage root collections
"""
Collection = apps.get_model("wagtailcore.Collection")
Group = apps.get_model("auth.Group")
GroupCollectionPermission... |
Give model-level permission to all groups who have that permission on the root collection | def revert_to_model_level_collection_management_permissions(apps, schema_editor):
"""
Give model-level permission to all groups who have that permission on the root collection
"""
Collection = apps.get_model("wagtailcore.Collection")
GroupCollectionPermission = apps.get_model("wagtailcore.GroupColle... |
Get dictionaries representing the model's field data.
This excludes many to many fields (which are handled by _copy_m2m_relations)' | def _extract_field_data(source, exclude_fields=None):
"""
Get dictionaries representing the model's field data.
This excludes many to many fields (which are handled by _copy_m2m_relations)'
"""
exclude_fields = exclude_fields or []
data_dict = {}
for field in source._meta.get_fields():
... |
Copies non-ParentalManyToMany m2m relations | def _copy_m2m_relations(source, target, exclude_fields=None, update_attrs=None):
"""
Copies non-ParentalManyToMany m2m relations
"""
update_attrs = update_attrs or {}
exclude_fields = exclude_fields or []
for field in source._meta.get_fields():
# Copy m2m relations. Ignore explicitly ex... |
This function populates the "translation_key", and "locale" fields on model instances that were created
before wagtail-localize was added to the site.
This can be called from a data migration, or instead you could use the "bootstrap_translatable_models"
management command. | def bootstrap_translatable_model(model, locale):
"""
This function populates the "translation_key", and "locale" fields on model instances that were created
before wagtail-localize was added to the site.
This can be called from a data migration, or instead you could use the "bootstrap_translatable_mode... |
Returns a list of all concrete models that inherit from TranslatableMixin.
By default, this only includes models that are direct children of TranslatableMixin,
to get all models, set the include_subclasses attribute to True. | def get_translatable_models(include_subclasses=False):
"""
Returns a list of all concrete models that inherit from TranslatableMixin.
By default, this only includes models that are direct children of TranslatableMixin,
to get all models, set the include_subclasses attribute to True.
"""
translat... |
Return the wagtailcore.Site object for the given hostname and port. | def get_site_for_hostname(hostname, port):
"""Return the wagtailcore.Site object for the given hostname and port."""
Site = apps.get_model("wagtailcore.Site")
sites = list(
Site.objects.annotate(
match=Case(
# annotate the results by best choice descending
... |
Returns a list of all non-abstract Page model classes defined in this project. | def get_page_models():
"""
Returns a list of all non-abstract Page model classes defined in this project.
"""
return PAGE_MODEL_CLASSES.copy() |
Returns a queryset of all ContentType objects corresponding to Page model classes. | def get_page_content_types(include_base_page_type=True):
"""
Returns a queryset of all ContentType objects corresponding to Page model classes.
"""
models = get_page_models()
if not include_base_page_type:
models.remove(Page)
content_type_ids = [
ct.pk for ct in ContentType.obje... |
Returns the content type to use as a default for pages whose content type
has been deleted. | def get_default_page_content_type():
"""
Returns the content type to use as a default for pages whose content type
has been deleted.
"""
return ContentType.objects.get_for_model(Page) |
helper method to extract tag attributes, as a dict of un-escaped strings | def extract_attrs(attr_string: str) -> dict:
"""
helper method to extract tag attributes, as a dict of un-escaped strings
"""
attributes = {}
for name, val in FIND_ATTRS.findall(attr_string):
val = (
val.replace("<", "<")
.replace(">", ">")
.replace(... |
Expand database-representation HTML into proper HTML usable on front-end templates | def expand_db_html(html):
"""
Expand database-representation HTML into proper HTML usable on front-end templates
"""
rewriter = get_rewriter()
return rewriter(html) |
Return a plain text version of a rich text string, suitable for search indexing;
like Django's strip_tags, but ensures that whitespace is left between block elements
so that <p>hello</p><p>world</p> gives "hello world", not "helloworld". | def get_text_for_indexing(richtext):
"""
Return a plain text version of a rich text string, suitable for search indexing;
like Django's strip_tags, but ensures that whitespace is left between block elements
so that <p>hello</p><p>world</p> gives "hello world", not "helloworld".
"""
# insert spac... |
Checks each page model with search_fields to core fields are included | def page_search_fields_check(app_configs, **kwargs):
"""Checks each page model with search_fields to core fields are included"""
from wagtail.models import Page, get_page_models
page_models = get_page_models()
errors = []
for cls in page_models:
# Don't check models where indexing has been... |
Has the same result as Python's reduce function, but performs the calculations in a different order.
This is important when the operator is constructing data structures such as search query classes.
This method will make the resulting data structures flatter, so operations that need to traverse
them don't end up crash... | def balanced_reduce(operator, seq, initializer=NOT_SET):
"""
Has the same result as Python's reduce function, but performs the calculations in a different order.
This is important when the operator is constructing data structures such as search query classes.
This method will make the resulting data st... |
This takes a query string typed in by a user and extracts the following:
- Quoted terms (for phrase search)
- Filters
For example, the following query:
`hello "this is a phrase" live:true` would be parsed into:
filters: {'live': 'true'}
tokens: And([PlainText('hello'), Phrase('this is a phrase')]) | def parse_query_string(query_string, operator=None, zero_terms=MATCH_NONE):
"""
This takes a query string typed in by a user and extracts the following:
- Quoted terms (for phrase search)
- Filters
For example, the following query:
`hello "this is a phrase" live:true` would be parsed into... |
Returns all descendants of a model, including the model itself. | def get_descendant_models(model):
"""
Returns all descendants of a model, including the model itself.
"""
descendant_models = {
other_model
for other_model in apps.get_models()
if issubclass(other_model, model)
}
descendant_models.add(model)
return descendant_models |
Returns content types ids for the ancestors of this model, excluding it. | def get_ancestors_content_types_pks(model):
"""
Returns content types ids for the ancestors of this model, excluding it.
"""
from django.contrib.contenttypes.models import ContentType
return [
ct.pk
for ct in ContentType.objects.get_for_models(
*model._meta.get_parent_li... |
Returns content types ids for the descendants of this model, including it. | def get_descendants_content_types_pks(model):
"""
Returns content types ids for the descendants of this model, including it.
"""
from django.contrib.contenttypes.models import ContentType
return [
ct.pk
for ct in ContentType.objects.get_for_models(
*get_descendant_models... |
This function finds the root model for any given model. The root model is
the highest concrete model that it descends from. If the model doesn't
descend from another concrete model then the model is it's own root model so
it is returned.
Examples:
>>> get_model_root(wagtailcore.Page)
wagtailcore.Page
>>> get_model_ro... | def get_model_root(model):
"""
This function finds the root model for any given model. The root model is
the highest concrete model that it descends from. If the model doesn't
descend from another concrete model then the model is it's own root model so
it is returned.
Examples:
>>> get_mode... |
There's two formats for the dotted_path.
One with the backend class (old) and one without (new)
eg:
old: wagtail.search.backends.elasticsearch.ElasticsearchSearchBackend
new: wagtail.search.backends.elasticsearch
If a new style dotted path was specified, this function would
look for a backend class from the "Searc... | def import_backend(dotted_path):
"""
There's two formats for the dotted_path.
One with the backend class (old) and one without (new)
eg:
old: wagtail.search.backends.elasticsearch.ElasticsearchSearchBackend
new: wagtail.search.backends.elasticsearch
If a new style dotted path was specif... |
Returns the appropriate search backend for the current 'default' database system | def SearchBackend(params):
"""
Returns the appropriate search backend for the current 'default' database system
"""
if connection.vendor == "postgresql":
from .postgres.postgres import PostgresSearchBackend
return PostgresSearchBackend(params)
elif connection.vendor == "mysql":
... |
Turns this query into a normalized version.
For example, And(Not(PlainText("Arepa")), PlainText("Crepe")) would be turned into AndNot(PlainText("Crepe"), PlainText("Arepa")): "Crepe AND NOT Arepa".
This is done because we need to get the NOT operator to the front of the query, so it can be used in the search, because t... | def normalize(search_query: SearchQuery) -> Tuple[SearchQuery]:
"""
Turns this query into a normalized version.
For example, And(Not(PlainText("Arepa")), PlainText("Crepe")) would be turned into AndNot(PlainText("Crepe"), PlainText("Arepa")): "Crepe AND NOT Arepa".
This is done because we need to get th... |
This takes a search backend and a list of models. By calling the
get_index_for_model method on the search backend, it groups the models into
the indices that they will be indexed into.
It returns an ordered mapping of indices to lists of models within each
index.
For example, Elasticsearch 2 requires all page models ... | def group_models_by_index(backend, models):
"""
This takes a search backend and a list of models. By calling the
get_index_for_model method on the search backend, it groups the models into
the indices that they will be indexed into.
It returns an ordered mapping of indices to lists of models within... |
A context manager to allow testing of different search_fields configurations
without permanently changing the models' search_fields. | def patch_search_fields(model, new_search_fields):
"""
A context manager to allow testing of different search_fields configurations
without permanently changing the models' search_fields.
"""
old_search_fields = model.search_fields
model.search_fields = new_search_fields
yield
model.sear... |
Retrieve the global list of menu items for the snippet action menu,
which may then be customised on a per-request basis | def get_base_snippet_action_menu_items(model):
"""
Retrieve the global list of menu items for the snippet action menu,
which may then be customised on a per-request basis
"""
menu_items = [
SaveMenuItem(order=0),
DeleteMenuItem(order=10),
]
if issubclass(model, DraftStateMixi... |
Called from WagtailSnippetsAppConfig.ready(), at which point we can be sure all models
have been loaded and register_snippet can safely construct viewsets. | def register_deferred_snippets():
"""
Called from WagtailSnippetsAppConfig.ready(), at which point we can be sure all models
have been loaded and register_snippet can safely construct viewsets.
"""
global DEFER_REGISTRATION
DEFER_REGISTRATION = False
for registerable, viewset in DEFERRED_REG... |
true if user has 'add', 'change' or 'delete' permission on this model | def user_can_edit_snippet_type(user, model):
"""true if user has 'add', 'change' or 'delete' permission on this model"""
for action in ("add", "change", "delete"):
if user.has_perm(get_permission_name(action, model)):
return True
return False |
true if user has 'add', 'change' or 'delete' permission
on any model registered as a snippet type | def user_can_edit_snippets(user):
"""
true if user has 'add', 'change' or 'delete' permission
on any model registered as a snippet type
"""
snippet_models = get_snippet_models()
for model in snippet_models:
if user_can_edit_snippet_type(user, model):
return True
return... |
Retrieve a model from an app_label / model_name combo.
Raise Http404 if the model is not a valid snippet type. | def get_snippet_model_from_url_params(app_name, model_name):
"""
Retrieve a model from an app_label / model_name combo.
Raise Http404 if the model is not a valid snippet type.
"""
try:
model = apps.get_model(app_name, model_name)
except LookupError:
raise Http404
if model not... |
Outputs a page's URL as relative (/foo/bar/) if it's within the same site as the
current page, or absolute (http://example.com/foo/bar/) if not.
If kwargs contains a fallback view name and page is None, the fallback view url will be returned. | def pageurl(context, page, fallback=None):
"""
Outputs a page's URL as relative (/foo/bar/) if it's within the same site as the
current page, or absolute (http://example.com/foo/bar/) if not.
If kwargs contains a fallback view name and page is None, the fallback view url will be returned.
"""
if... |
Outputs a page's absolute URL (http://example.com/foo/bar/)
If kwargs contains a fallback view name and page is None, the fallback view url will be returned. | def fullpageurl(context, page, fallback=None):
"""
Outputs a page's absolute URL (http://example.com/foo/bar/)
If kwargs contains a fallback view name and page is None, the fallback view url will be returned.
"""
if page is None and fallback:
fallback_url = resolve_url(fallback)
if ... |
Returns the URL for the page that has the given slug.
First tries to find a page on the current site. If that fails or a request
is not available in the context, then returns the URL for the first page
that matches the slug on any site. | def slugurl(context, slug):
"""
Returns the URL for the page that has the given slug.
First tries to find a page on the current site. If that fails or a request
is not available in the context, then returns the URL for the first page
that matches the slug on any site.
"""
page = None
t... |
Render the passed item of StreamField content, passing the current template context
if there's an identifiable way of doing so (i.e. if it has a `render_as_block` method). | def include_block(parser, token):
"""
Render the passed item of StreamField content, passing the current template context
if there's an identifiable way of doing so (i.e. if it has a `render_as_block` method).
"""
tokens = token.split_contents()
try:
tag_name = tokens.pop(0)
blo... |
Returns the Site object for the given request | def wagtail_site(context):
"""
Returns the Site object for the given request
"""
try:
request = context["request"]
except KeyError:
return None
return Site.find_for_request(request=request) |
A helper function to define cache tags without duplicating `do_cache`. | def register_cache_tag(tag_name, node_class):
"""
A helper function to define cache tags without duplicating `do_cache`.
"""
@register.tag(tag_name)
def do_cache(parser, token):
# Implementation copied from `django.templatetags.cache.do_cache`
nodelist = parser.parse((f"end{tag_name... |
Dummy sendfile backend implementation. | def sendfile(request, filename, **kwargs):
"""
Dummy sendfile backend implementation.
"""
return HttpResponse("Dummy backend response") |
Translates a nested dict structure into a flat form data dict
with hyphen-separated keys.
.. code-block:: python
nested_form_data({
'foo': 'bar',
'parent': {
'child': 'field',
},
})
# Returns: {'foo': 'bar', 'parent-child': 'field'} | def nested_form_data(data):
"""
Translates a nested dict structure into a flat form data dict
with hyphen-separated keys.
.. code-block:: python
nested_form_data({
'foo': 'bar',
'parent': {
'child': 'field',
},
})
# Returns: {... |
Takes a list of (block_type, value) tuples and turns it in to
StreamField form data. Use this within a :func:`nested_form_data`
call, with the field name as the key.
.. code-block:: python
nested_form_data({'content': streamfield([
('text', 'Hello, world'),
])})
# Returns:
# {
# 'conte... | def streamfield(items):
"""
Takes a list of (block_type, value) tuples and turns it in to
StreamField form data. Use this within a :func:`nested_form_data`
call, with the field name as the key.
.. code-block:: python
nested_form_data({'content': streamfield([
('text', 'Hello, w... |
Takes a list of form data for an InlineFormset and translates
it in to valid POST data. Use this within a :func:`nested_form_data`
call, with the formset relation name as the key.
.. code-block:: python
nested_form_data({'lines': inline_formset([
{'text': 'Hello'},
{'text': 'World'},
])})
... | def inline_formset(items, initial=0, min=0, max=1000):
"""
Takes a list of form data for an InlineFormset and translates
it in to valid POST data. Use this within a :func:`nested_form_data`
call, with the formset relation name as the key.
.. code-block:: python
nested_form_data({'lines': i... |
Converts an HTML-like rich text string to the data format required by
the currently active rich text editor.
:param editor: An alternative editor name as defined in ``WAGTAILADMIN_RICH_TEXT_EDITORS``
:param features: A list of features allowed in the rich text content (see :ref:`rich_text_features`)
.. code-block:: p... | def rich_text(value, editor="default", features=None):
"""
Converts an HTML-like rich text string to the data format required by
the currently active rich text editor.
:param editor: An alternative editor name as defined in ``WAGTAILADMIN_RICH_TEXT_EDITORS``
:param features: A list of features allo... |
Helper function to translate a possibly-timezone-aware datetime into the format used in the
go_live_at / expire_at form fields - "YYYY-MM-DD hh:mm", with no timezone indicator.
This will be interpreted as being in the server's timezone (settings.TIME_ZONE), so we
need to pass it through timezone.localtime to ensure tha... | def submittable_timestamp(timestamp):
"""
Helper function to translate a possibly-timezone-aware datetime into the format used in the
go_live_at / expire_at form fields - "YYYY-MM-DD hh:mm", with no timezone indicator.
This will be interpreted as being in the server's timezone (settings.TIME_ZONE), so w... |
Registers order against the model content_type, used to
control the order the models and its permissions appear
in the groups object permission editor | def register(model, **kwargs):
"""
Registers order against the model content_type, used to
control the order the models and its permissions appear
in the groups object permission editor
"""
order = kwargs.pop("order", None)
if order is not None:
content_type = ContentType.objects.get... |
Strip model name from the end of the label, e.g. "Can deliver pizza" for a
Pizza model becomes "Can deliver". For permissions in the model's
Meta.default_permissions with default labels, also replace underscores
with spaces.
This is used to display custom model permissions in the admin.
See https://github.com/wagtail... | def normalize_permission_label(permission: Permission):
"""
Strip model name from the end of the label, e.g. "Can deliver pizza" for a
Pizza model becomes "Can deliver". For permissions in the model's
Meta.default_permissions with default labels, also replace underscores
with spaces.
This is us... |
Given a bound field with a queryset of Permission objects - which must be using
the CheckboxSelectMultiple widget - construct a list of dictionaries for 'objects':
'objects': [
{
'object': name_of_some_content_object,
'add': checkbox,
'change': checkbox,
'delete': checkbox,
... | def format_permissions(permission_bound_field):
"""
Given a bound field with a queryset of Permission objects - which must be using
the CheckboxSelectMultiple widget - construct a list of dictionaries for 'objects':
'objects': [
{
'object': name_of_some_content_object,
'... |
Generator function that yields a module object for each installed app
yields tuples of (app_name, module) | def get_app_modules():
"""
Generator function that yields a module object for each installed app
yields tuples of (app_name, module)
"""
for app in apps.get_app_configs():
yield app.name, app.module |
Searches each app module for the specified submodule
yields tuples of (app_name, module) | def get_app_submodules(submodule_name):
"""
Searches each app module for the specified submodule
yields tuples of (app_name, module)
"""
for name, module in get_app_modules():
if module_has_submodule(module, submodule_name):
yield name, import_module(f"{name}.{submodule_name}") |
Modify a view function so its response has the X-Frame-Options HTTP header
set to 'SAMEORIGIN'.
Adapted from Django's xframe_options_sameorigin so that it's always applied
even if the response already has that header set:
https://github.com/django/django/blob/3.2/django/views/decorators/clickjacking.py#L22-L37
Usage:... | def xframe_options_sameorigin_override(view_func):
"""
Modify a view function so its response has the X-Frame-Options HTTP header
set to 'SAMEORIGIN'.
Adapted from Django's xframe_options_sameorigin so that it's always applied
even if the response already has that header set:
https://github.com... |
Compute the hash of a file-like object, without loading it all into memory. | def hash_filelike(filelike):
"""
Compute the hash of a file-like object, without loading it all into memory.
"""
file_pos = 0
if hasattr(filelike, "tell"):
file_pos = filelike.tell()
try:
# Reset file handler to the start of the file so we hash it all
filelike.seek(0)
... |
Return custom form class if defined and available | def get_custom_form(form_setting):
"""Return custom form class if defined and available"""
try:
return import_string(getattr(settings, form_setting))
except ImportError:
raise ImproperlyConfigured(
"%s refers to a form '%s' that is not available"
% (form_setting, geta... |
create a response to send file using backend configured in SENDFILE_BACKEND
If attachment is True the content-disposition header will be set.
This will typically prompt the user to download the file, rather
than view it. The content-disposition filename depends on the
value of attachment_filename:
None (default)... | def sendfile(
request,
filename,
attachment=False,
attachment_filename=None,
mimetype=None,
encoding=None,
backend=None,
):
"""
create a response to send file using backend configured in SENDFILE_BACKEND
If attachment is True the content-disposition header will be set.
This ... |
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about. | def was_modified_since(header=None, mtime=0):
"""
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
"""
... |
Similar to how django-modelcluster stores the revision's data and similar to how
django stores dates in the database, this converts the date to UTC if required. | def ensure_utc(value):
"""
Similar to how django-modelcluster stores the revision's data and similar to how
django stores dates in the database, this converts the date to UTC if required.
"""
# https://github.com/wagtail/django-modelcluster/blob/8666f16eaf23ca98afc160b0a4729864411c0563/modelcluster/... |
Uses Django's parse_datetime(), but ensures to return an aware datetime. | def parse_datetime_localized(date_string):
"""
Uses Django's parse_datetime(), but ensures to return an aware datetime.
"""
dt = parse_datetime(date_string)
if settings.USE_TZ and timezone.is_naive(dt):
dt = timezone.make_aware(dt, timezone=timezone.get_default_timezone())
return dt |
Helper function to format a possibly-timezone-aware datetime into the format
used by Django (e.g. in templates). | def render_timestamp(timestamp):
"""
Helper function to format a possibly-timezone-aware datetime into the format
used by Django (e.g. in templates).
"""
if timezone.is_aware(timestamp):
timestamp = timezone.localtime(timestamp)
return formats.date_format(timestamp, "DATETIME_FORMAT") |
Decorate all the views in the passed urlpatterns list with the given decorator | def decorate_urlpatterns(urlpatterns, decorator):
"""Decorate all the views in the passed urlpatterns list with the given decorator"""
for pattern in urlpatterns:
if hasattr(pattern, "url_patterns"):
# this is an included RegexURLResolver; recursively decorate the views
# contai... |
Update a nested dictionary or similar mapping.
Modify ``source`` in place. | def deep_update(source, overrides):
"""Update a nested dictionary or similar mapping.
Modify ``source`` in place.
"""
for key, value in overrides.items():
if isinstance(value, Mapping) and value:
returned = deep_update(source.get(key, {}), value)
source[key] = returned
... |
Return a PEP 440-compliant version number from VERSION. | def get_version(version):
"""Return a PEP 440-compliant version number from VERSION."""
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|rc}N - for alpha, beta, and rc releases
main... |
Return main version (X.Y[.Z]) from VERSION. | def get_main_version(version=None, include_patch=True):
"""Return main version (X.Y[.Z]) from VERSION."""
version = get_complete_version(version)
if include_patch:
parts = 2 if version[2] == 0 else 3
else:
parts = 2
return ".".join(str(x) for x in version[:parts]) |
Return a tuple of the Wagtail version. If version argument is non-empty,
check for correctness of the tuple provided. | def get_complete_version(version=None):
"""
Return a tuple of the Wagtail version. If version argument is non-empty,
check for correctness of the tuple provided.
"""
if version is None:
from wagtail import VERSION as version
else:
assert len(version) == 5
assert version[... |
Returns the semver version (X.Y.Z[-(alpha|beta)]) from VERSION | def get_semver_version(version):
"Returns the semver version (X.Y.Z[-(alpha|beta)]) from VERSION"
main = ".".join(str(x) for x in version[:3])
sub = ""
if version[3] != "final":
sub = "-{}.{}".format(*version[3:])
return main + sub |
Open an audio file and read as mono waveform, resampling as necessary
Parameters
----------
file: str
The audio file to open
sr: int
The sample rate to resample the audio if necessary
Returns
-------
A NumPy array containing the audio waveform, in float32 dtype. | def load_audio(file: str, sr: int = SAMPLE_RATE):
"""
Open an audio file and read as mono waveform, resampling as necessary
Parameters
----------
file: str
The audio file to open
sr: int
The sample rate to resample the audio if necessary
Returns
-------
A NumPy arr... |
Pad or trim the audio array to N_SAMPLES, as expected by the encoder. | def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1):
"""
Pad or trim the audio array to N_SAMPLES, as expected by the encoder.
"""
if torch.is_tensor(array):
if array.shape[axis] > length:
array = array.index_select(
dim=axis, index=torch.arange(length... |
load the mel filterbank matrix for projecting STFT into a Mel spectrogram.
Allows decoupling librosa dependency; saved using:
np.savez_compressed(
"mel_filters.npz",
mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80),
mel_128=librosa.filters.mel(sr=16000, n_fft=400, n_mels=128),
... | def mel_filters(device, n_mels: int) -> torch.Tensor:
"""
load the mel filterbank matrix for projecting STFT into a Mel spectrogram.
Allows decoupling librosa dependency; saved using:
np.savez_compressed(
"mel_filters.npz",
mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_m... |
Compute the log-Mel spectrogram of
Parameters
----------
audio: Union[str, np.ndarray, torch.Tensor], shape = (*)
The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz
n_mels: int
The number of Mel-frequency filters, only 80 is supported
padding: int
Number of zero s... | def log_mel_spectrogram(
audio: Union[str, np.ndarray, torch.Tensor],
n_mels: int = 80,
padding: int = 0,
device: Optional[Union[str, torch.device]] = None,
):
"""
Compute the log-Mel spectrogram of
Parameters
----------
audio: Union[str, np.ndarray, torch.Tensor], shape = (*)
... |
Detect the spoken language in the audio, and return them as list of strings, along with the ids
of the most probable language tokens and the probability distribution over all language tokens.
This is performed outside the main decode loop in order to not interfere with kv-caching.
Returns
-------
language_tokens : Ten... | def detect_language(
model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None
) -> Tuple[Tensor, List[dict]]:
"""
Detect the spoken language in the audio, and return them as list of strings, along with the ids
of the most probable language tokens and the probability distribution over all language toke... |
Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s).
Parameters
----------
model: Whisper
the Whisper model instance
mel: torch.Tensor, shape = (80, 3000) or (*, 80, 3000)
A tensor containing the Mel spectrogram(s)
options: DecodingOptions
A dataclass that contains all necessa... | def decode(
model: "Whisper",
mel: Tensor,
options: DecodingOptions = DecodingOptions(),
**kwargs,
) -> Union[DecodingResult, List[DecodingResult]]:
"""
Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s).
Parameters
----------
model: Whisper
the ... |
Returns sinusoids for positional embedding | def sinusoids(length, channels, max_timescale=10000):
"""Returns sinusoids for positional embedding"""
assert channels % 2 == 0
log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1)
inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2))
scaled_time = torch... |
Apply a median filter of width `filter_width` along the last dimension of `x` | def median_filter(x: torch.Tensor, filter_width: int):
"""Apply a median filter of width `filter_width` along the last dimension of `x`"""
pad_width = filter_width // 2
if x.shape[-1] <= pad_width:
# F.pad requires the padding width to be smaller than the input dimension
return x
if (nd... |
Transcribe an audio file using Whisper
Parameters
----------
model: Whisper
The Whisper model instance
audio: Union[str, np.ndarray, torch.Tensor]
The path to the audio file to open, or the audio waveform
verbose: bool
Whether to display the text being decoded to the console. If True, displays all the de... | def transcribe(
model: "Whisper",
audio: Union[str, np.ndarray, torch.Tensor],
*,
verbose: Optional[bool] = None,
temperature: Union[float, Tuple[float, ...]] = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
compression_ratio_threshold: Optional[float] = 2.4,
logprob_threshold: Optional[float] = -1.0,
... |
Apply a median filter of given width along the last dimension of x | def median_filter_cuda(x: torch.Tensor, filter_width: int):
"""Apply a median filter of given width along the last dimension of x"""
slices = x.contiguous().unfold(-1, filter_width, 1)
grid = np.prod(slices.shape[:-2])
kernel = median_kernel(filter_width)
y = torch.empty_like(slices[..., 0])
B... |
Returns the names of available models | def available_models() -> List[str]:
"""Returns the names of available models"""
return list(_MODELS.keys()) |
Load a Whisper ASR model
Parameters
----------
name : str
one of the official model names listed by `whisper.available_models()`, or
path to a model checkpoint containing the model dimensions and the model state_dict.
device : Union[str, torch.device]
the PyTorch device to put the model into
download_root:... | def load_model(
name: str,
device: Optional[Union[str, torch.device]] = None,
download_root: str = None,
in_memory: bool = False,
) -> Whisper:
"""
Load a Whisper ASR model
Parameters
----------
name : str
one of the official model names listed by `whisper.available_models()... |
Replace any other markers, symbols, and punctuations with a space,
and drop any diacritics (category 'Mn' and some manual mappings) | def remove_symbols_and_diacritics(s: str, keep=""):
"""
Replace any other markers, symbols, and punctuations with a space,
and drop any diacritics (category 'Mn' and some manual mappings)
"""
return "".join(
c
if c in keep
else ADDITIONAL_DIACRITICS[c]
if c in ADDITI... |
Replace any other markers, symbols, punctuations with a space, keeping diacritics | def remove_symbols(s: str):
"""
Replace any other markers, symbols, punctuations with a space, keeping diacritics
"""
return "".join(
" " if unicodedata.category(c)[0] in "MSP" else c
for c in unicodedata.normalize("NFKC", s)
) |
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN that is only linear, and has a finite context window
of block_size, unlike an RNN that has an infin... | def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN that is... |
Allocate a cache to be used with the Transformer module.
Args:
args (ModelArgs): the model configuration.
length (int): per layer cache size.
It is usually budgeted as ``max_batch * max_seq``
device (torch.device, optional): the device on which
the cache should be allocated.
n_layers (i... | def make_cache(
args: ModelArgs,
length: int,
device: Optional[Union[str, torch.device]] = None,
n_layers: Optional[int] = None,
dtype: Optional[torch.dtype] = None,
) -> list[LayerCache]:
"""
Allocate a cache to be used with the Transformer module.
Args:
args (ModelArgs): the m... |
Take a prefix view of a larger cache.
The original cache object remains of identical size and valid
after the shrinked alias has been used. This function is useful
when a cache was allocated for a larger batch size than what is
necessary.
Args:
cache: the cache to take a view in.
length (int): the desired len... | def cache_prefix(cache: list[LayerCache], length: int) -> list[LayerCache]:
"""
Take a prefix view of a larger cache.
The original cache object remains of identical size and valid
after the shrinked alias has been used. This function is useful
when a cache was allocated for a larger batch size than... |
Initialize model parallelism support.
Args:
world_size (int): the number of processes running on
the current node available for model parallelism.
local_rank (int): the present process' rank.
group (torch.distributed.ProcessGroup, optional): the
process group to use for model parallel commu... | def initialize(
world_size: int,
local_rank: int,
group: Optional[ProcessGroup] = None,
use_gpu: bool = True,
seed: int = 80486,
) -> str:
"""
Initialize model parallelism support.
Args:
world_size (int): the number of processes running on
the current node available ... |
Gather a tensor of shape (n, m) into a tensor of shape (n, mp_size * m). | def all_gather(x: torch.Tensor) -> torch.Tensor:
"""
Gather a tensor of shape (n, m) into a tensor of shape (n, mp_size * m).
"""
mp_size = get_world_size()
if mp_size == 1:
return x
gather = [torch.empty_like(x) for _ in range(mp_size)]
torch.distributed.all_gather(gather, x, grou... |
Perform top-p (nucleus) sampling on a probability distribution.
Args:
probs (torch.Tensor): probability distribution tensor.
p (float): probability threshold for top-p sampling.
Returns:
torch.Tensor: sampled token indices.
Note:
Top-p sampling selects the smallest set of tokens whose cumulative
... | def top_p(probs: torch.Tensor, p: float) -> torch.Tensor:
"""
Perform top-p (nucleus) sampling on a probability distribution.
Args:
probs (torch.Tensor): probability distribution tensor.
p (float): probability threshold for top-p sampling.
Returns:
torch.Tensor: sampled token i... |
Return whether we are at an exact version (namely the version variable). | def get_tagged_version() -> Optional[str]:
"""
Return whether we are at an exact version (namely the version variable).
"""
try:
tag = subprocess.check_output(
["git", "describe", "--tags", "--exact-match", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
... |
Make sure that the causal flag is respected.
The input data is orthogonal by design if causal is respected, but if the attention looks ahead this will fail | def test_causal(
attention_name: str,
heads: int,
):
"""
Make sure that the causal flag is respected.
The input data is orthogonal by design if causal is respected, but if the attention looks ahead this will fail
"""
torch.random.manual_seed(42)
device = torch.device("cuda")
multi... |
LSE can be padded, let's remove the padding | def _block_diag_reshape_lse(
lse: torch.Tensor, q_seqinfo: fmha.attn_bias._SeqLenInfo
) -> torch.Tensor:
"""LSE can be padded, let's remove the padding"""
parts = []
for slice, (start, end) in zip(lse.unbind(0), q_seqinfo.intervals()):
parts.append(slice[:, : end - start])
return torch.cat(p... |
vectorized implementation of scipy.stats.binom_test
this makes our tests much faster
reference: https://github.com/scipy/scipy/blob/v1.8.0/scipy/stats/_morestats.py#L2609-L2702 | def _vec_binom_test(x, n, p):
"""
vectorized implementation of scipy.stats.binom_test
this makes our tests much faster
reference: https://github.com/scipy/scipy/blob/v1.8.0/scipy/stats/_morestats.py#L2609-L2702
"""
import numpy as np
from scipy.stats import distributions
x = np.atleast_... |
IMPORTANT:
This is the example in the doc for `BlockDiagonalMask`.
If this example needs to be updated, please also update the doc | def test_attn_bias_blockdiag_doc() -> None:
"""IMPORTANT:
This is the example in the doc for `BlockDiagonalMask`.
If this example needs to be updated, please also update the doc
"""
import torch
from xformers.ops import fmha
if torch.version.hip:
pytest.skip("backward pass/gradienc... |
This tests some internals of the cutlassB kernel
We test the iteration across blocks of [queries, keys] to ensure
that we correctly:
* Iterate over all the blocks that should be iterated
* Do *not* iterate over blocks that are completely masked out
* Correctly compute the number of parallel blocks that will compute
... | def test_cutlassB_iter_order(
dtype,
cc: int,
maxK: int,
num_queries: int,
num_keys: int,
custom_mask_type,
window_size,
) -> None:
"""
This tests some internals of the cutlassB kernel
We test the iteration across blocks of [queries, keys] to ensure
that we correctly:
* I... |
Merging the same attention twice shouldn't change anything.
This also tests the shape of the lse output of each permitted op. | def test_merge_attentions_nobias(
write_lse: bool,
stack_inputs: bool,
op: Type[AttentionFwOpBase],
G: Optional[int],
H: int,
):
"""
Merging the same attention twice shouldn't change anything.
This also tests the shape of the lse output of each permitted op.
"""
B, M, Mq, K = 13,... |
Compute decoding attention on chunks of K/V and merge them together.
Compare with computing attention on the whole K/V. | def test_merge_attentions_decoding(
dtype: torch.dtype,
op: Type[AttentionFwOpBase],
num_queries: int,
bmghk: bool,
stack_inputs: bool,
):
"""
Compute decoding attention on chunks of K/V and merge them together.
Compare with computing attention on the whole K/V.
"""
MAX_T = 8192
... |
attn_split: [split_k, B, M, (G,) H, Kq]
lse_split: [split_k, B, (G,) H, M] | def _merge_attentions_ref(attn_split, lse_split):
"""
attn_split: [split_k, B, M, (G,) H, Kq]
lse_split: [split_k, B, (G,) H, M]
"""
is_bmghk = len(attn_split.shape) == 6
if not is_bmghk:
attn_split = attn_split.unsqueeze(3)
lse_split = lse_split.unsqueeze(2)
lse_split = lse... |
Simple rope calculation of rope of one tensor
Args:
x: input, shape (B, M, H, K).
seqpos: gives the position of each sequence element in x in its sequence
(shape (M,)). | def _slow_rope(
x: torch.Tensor,
*,
seqpos: Optional[torch.Tensor] = None,
theta=10000,
adjacents: bool = True,
):
"""
Simple rope calculation of rope of one tensor
Args:
x: input, shape (B, M, H, K).
seqpos: gives the position of each sequence element in x in its sequen... |
More flexible unused version of _slow_rope
- allows varying dtypes. | def _slow_rope2(
x: torch.Tensor,
*,
seqpos: Optional[torch.Tensor] = None,
theta=10000,
adjacents: bool = True,
):
"""
More flexible unused version of _slow_rope
- allows varying dtypes.
"""
internal_dtype = torch.float64
dim = x.shape[-1]
seq_dim = 1
M = x.shape[seq... |
Improved version of
```
assert torch.allclose(out, ref)
```
Except that we provide useful error message, and also compare
to the output of the f32 calculation. | def assert_allclose(
# The output of the tested function
out: torch.Tensor,
# The output of the reference implementation
ref: torch.Tensor,
# The output of the reference implementation in f32
ref32: Optional[torch.Tensor] = None,
msg: str = "failed",
atol: Optional[float] = None,
rto... |
Produce lhs, rhs and reference output tensors
To dodge numerical accuracy differences between our kernels and PyTorch's
ones, we avoid random values and construct matrices whose product is an
exact mathematical computation, specifically: the remainder!
We do it by having the i-th row of lhs and the j-th column on rhs... | def make_operands(m, n, k, *, dtype):
"""Produce lhs, rhs and reference output tensors
To dodge numerical accuracy differences between our kernels and PyTorch's
ones, we avoid random values and construct matrices whose product is an
exact mathematical computation, specifically: the remainder!
We d... |
Check some basic dropout properties | def test_dropout(shape, amp, bias, p):
"""
Check some basic dropout properties
"""
torch.random.manual_seed(0)
torch.cuda.manual_seed_all(0)
x = torch.normal(0, 1, size=shape, device="cuda", requires_grad=True)
b = (
torch.normal(0, 1, size=(shape[-1],), device="cuda", requires_grad... |
Check some basic dropout properties | def test_dropout_parity(shape, amp, bias, activation, p):
"""
Check some basic dropout properties
"""
torch.random.manual_seed(0)
x = torch.normal(0, 1, size=shape, device="cuda", requires_grad=True)
b = (
torch.ones(size=(shape[-1],), device="cuda", requires_grad=True)
if bias
... |
Check that the matrix multiply kernel and Pytorch's give the same results | def test_fused_matmul(shape, dtype):
"""Check that the matrix multiply kernel and Pytorch's give the same results"""
# TODO: fix or remove this
pytest.skip("This is broken")
torch.random.manual_seed(0)
# Raw fused matrix multiply first, to catch gross errors
a = torch.normal(0, 1, size=(shape[-... |
Check that PyTorch and fused linear layers give the same result | def test_fused_linear_parity(shape, activation: Activation, bias: bool, amp: bool):
"""Check that PyTorch and fused linear layers give the same result"""
# TODO: fix or remove this
pytest.skip("This is broken")
torch.random.manual_seed(0)
# Instantiate pytorch and fused layers, same initialization
... |
Check that PyTorch and Triton softmax give the same result | def test_layernorm_parity(shape, amp):
"""Check that PyTorch and Triton softmax give the same result"""
# Get the same inputs
torch.random.manual_seed(0)
X = torch.normal(0, 1, size=shape, device="cuda", requires_grad=True)
torch.random.manual_seed(0)
X_ = torch.normal(0, 1, size=shape, device... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.