diff --git a/videollama2/lib/python3.10/site-packages/blobfile/VERSION b/videollama2/lib/python3.10/site-packages/blobfile/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..4a36342fcab700951adb18ae7adc930997f6c3f4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/VERSION @@ -0,0 +1 @@ +3.0.0 diff --git a/videollama2/lib/python3.10/site-packages/blobfile/__init__.py b/videollama2/lib/python3.10/site-packages/blobfile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a0f7611f023101a6f0629485aad29c6524b6b5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/__init__.py @@ -0,0 +1,85 @@ +import os + +# all the modules are under _internal to indicate that they are not exported +# the A as A syntax seems to cause pycharm to list these +# symbols as coming from blobfile instead of blobfile._internal +from blobfile._ops import ( + copy as copy, + exists as exists, + glob as glob, + scanglob as scanglob, + isdir as isdir, + listdir as listdir, + scandir as scandir, + makedirs as makedirs, + remove as remove, + rmdir as rmdir, + rmtree as rmtree, + stat as stat, + walk as walk, + basename as basename, + dirname as dirname, + join as join, + get_url as get_url, + md5 as md5, + set_mtime as set_mtime, + configure as configure, + BlobFile as BlobFile, + last_version_seen as last_version_seen, + read_bytes as read_bytes, + read_text as read_text, + write_bytes as write_bytes, + write_text as write_text, +) +from blobfile._context import Context as Context, create_context as create_context +from blobfile._common import ( + Request as Request, + Error as Error, + RequestFailure as RequestFailure, + RestartableStreamingWriteFailure as RestartableStreamingWriteFailure, + ConcurrentWriteFailure as ConcurrentWriteFailure, + VersionMismatch as VersionMismatch, + DeadlineExceeded as DeadlineExceeded, + Stat as Stat, + DirEntry as DirEntry, +) + + +_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +with open(os.path.join(_SCRIPT_DIR, "VERSION")) as _version_file: + __version__ = _version_file.read().strip() + +__all__ = [ + "copy", + "exists", + "glob", + "scanglob", + "isdir", + "listdir", + "scandir", + "makedirs", + "remove", + "rmdir", + "rmtree", + "stat", + "walk", + "basename", + "dirname", + "join", + "get_url", + "md5", + "set_mtime", + "configure", + "BlobFile", + "Request", + "Error", + "RequestFailure", + "RestartableStreamingWriteFailure", + "ConcurrentWriteFailure", + "DeadlineExceeded", + "Stat", + "DirEntry", + "Context", + "create_context", + "VersionMismatch", +] diff --git a/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_common.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6de6e82082f82ded67b76a114ebe5ef09f98836 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_common.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_context.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9147a1d9a3fd6efcb27aa0a8e7e6516320036e95 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_context.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_xml_test.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_xml_test.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57cdc7463766c46c37547c5d5d9532f601c23246 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_xml_test.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_azure.py b/videollama2/lib/python3.10/site-packages/blobfile/_azure.py new file mode 100644 index 0000000000000000000000000000000000000000..0986c4ce57a46fb235dba11747c5841d9e9c509b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_azure.py @@ -0,0 +1,1689 @@ +import base64 +import binascii +import calendar +import concurrent.futures +import datetime +import hashlib +import hmac +import json +import math +import os +import re +import time +import urllib.parse +from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple + +import urllib3 + +from blobfile import _common as common +from blobfile import _xml as xml +from blobfile._common import ( + DEFAULT_RETRY_CODES, + INVALID_HOSTNAME_STATUS, + BaseStreamingReadFile, + BaseStreamingWriteFile, + ConcurrentWriteFailure, + Config, + DirEntry, + Error, + FileBody, + Request, + RequestFailure, + Stat, + TokenManager, + VersionMismatch, + path_join, + rng, + strip_slashes, +) + +SHARED_KEY = "shared_key" +OAUTH_TOKEN = "oauth_token" +ANONYMOUS = "anonymous" + +# it looks like azure signed urls cannot exceed the lifetime of the token used +# to create them, so don't keep the key around too long +SAS_TOKEN_EXPIRATION_SECONDS = 60 * 60 +# these seem to be expired manually, but we don't currently detect that +SHARED_KEY_EXPIRATION_SECONDS = 24 * 60 * 60 + +# max 100MB https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#remarks +# there is a preview version of the API that allows this to be 4000MiB +MAX_BLOCK_SIZE = 100_000_000 + +BLOCK_COUNT_LIMIT = 50_000 + +RESPONSE_HEADER_TO_REQUEST_HEADER = { + "Cache-Control": "x-ms-blob-cache-control", + "Content-Type": "x-ms-blob-content-type", + "Content-MD5": "x-ms-blob-content-md5", + "Content-Encoding": "x-ms-blob-content-encoding", + "Content-Language": "x-ms-blob-content-language", + "Content-Disposition": "x-ms-blob-content-disposition", +} + + +def _load_credentials() -> Dict[str, Any]: + # When AZURE_USE_IDENTITY=1, blobfile will use the azure-identity package to retrieve AAD access tokens + if os.getenv("AZURE_USE_IDENTITY", "0") == "1": + return {"_azure_auth": "azure-identity"} + + # https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#environment-variables + # AZURE_STORAGE_KEY seems to be the environment variable mentioned by the az cli + # AZURE_STORAGE_ACCOUNT_KEY is mentioned elsewhere on the internet + for varname in ["AZURE_STORAGE_KEY", "AZURE_STORAGE_ACCOUNT_KEY"]: + if varname in os.environ: + account = {} + if "AZURE_STORAGE_ACCOUNT" in os.environ: + account["account"] = os.environ["AZURE_STORAGE_ACCOUNT"] + return {"_azure_auth": "sakey", "storage_account_key": os.environ[varname], **account} + + if "AZURE_STORAGE_CONNECTION_STRING" in os.environ: + connection_data = {} + # technically this should be parsed according to the rules in + # https://www.connectionstrings.com/formating-rules-for-connection-strings/ + for part in os.environ["AZURE_STORAGE_CONNECTION_STRING"].split(";"): + key, _, val = part.partition("=") + connection_data[key.lower()] = val + return { + "_azure_auth": "sakey", + "account": connection_data["accountname"], + "storage_account_key": connection_data["accountkey"], + } + + if "AZURE_APPLICATION_CREDENTIALS" in os.environ: + creds_path = os.environ["AZURE_APPLICATION_CREDENTIALS"] + if not os.path.exists(creds_path): + raise Error( + f"Credentials not found at '{creds_path}' specified by environment variable 'AZURE_APPLICATION_CREDENTIALS'" + ) + with open(creds_path) as f: + creds = json.load(f) + return { + "_azure_auth": "svcact", + "client_id": creds["appId"], + "client_secret": creds["password"], + "tenant_id": creds["tenant"], + } + + if "AZURE_CLIENT_ID" in os.environ: + return { + "_azure_auth": "svcact", + "client_id": os.environ["AZURE_CLIENT_ID"], + "client_secret": os.environ["AZURE_CLIENT_SECRET"], + "tenant_id": os.environ["AZURE_TENANT_ID"], + } + + # look for a refresh token in the az command line credentials + # we could also try to use any found access tokens + msal_tokens_path = os.path.expanduser("~/.azure/msal_token_cache.json") + if os.path.exists(msal_tokens_path): + with open(msal_tokens_path) as f: + tokens = json.load(f) + for token in tokens.get("RefreshToken", {}).values(): + if token["credential_type"] != "RefreshToken": + continue + return {"_azure_auth": "refresh", "refresh_token": token["secret"]} + + access_tokens_path = os.path.expanduser("~/.azure/accessTokens.json") + if os.path.exists(access_tokens_path): + with open(access_tokens_path) as f: + tokens = json.load(f) + best_token = None + for token in tokens: + if "refreshToken" not in token: + continue + creds = {"_azure_auth": "refresh", "refresh_token": token["refreshToken"]} + if best_token is None: + best_token = creds + else: + # expiresOn may be missing for tokens from service principals + if token.get("expiresOn", "") > best_token.get("expiresOn", ""): + best_token = creds + if best_token is not None: + return best_token + + return {} + + +def load_subscription_ids() -> List[str]: + """ + Return a list of subscription ids from the local azure profile + the default subscription will appear first in the list + """ + default_profile_path = os.path.expanduser("~/.azure/azureProfile.json") + if not os.path.exists(default_profile_path): + return [] + + with open(default_profile_path, "rb") as f: + # this file has a UTF-8 BOM + profile = json.loads(f.read().decode("utf-8-sig")) + + subscriptions = profile.get("subscriptions", []) + + def key_fn(x: Mapping[str, Any]) -> bool: + return x["isDefault"] + + subscriptions.sort(key=key_fn, reverse=True) + return [sub["id"] for sub in subscriptions] + + +def build_url(account: str, template: str, **data: str) -> str: + return common.build_url(f"https://{account}.blob.core.windows.net", template, **data) + + +def _create_access_token_request( + creds: Mapping[str, str], scope: str, success_codes: Sequence[int] = (200,) +) -> Request: + if creds["_azure_auth"] == "refresh": + # https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token + data = { + "grant_type": "refresh_token", + "refresh_token": creds["refresh_token"], + "scope": scope, + } + tenant_id = "common" + elif creds["_azure_auth"] == "svcact": + # https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#first-case-access-token-request-with-a-shared-secret + # https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-azure-active-directory#use-oauth-access-tokens-for-authentication + # The following Azure CLI commands will create an AzureAD service principal with sufficient access to use Azure's `client_credentials` grant type: + # az ad sp create-for-rbac --name + # az account list + # az role assignment create --role "Storage Blob Data Contributor" --assignee --scope "/subscriptions//resourceGroups//providers/Microsoft.Storage/storageAccounts/" + data = { + "grant_type": "client_credentials", + "client_id": creds["client_id"], + "client_secret": creds["client_secret"], + "scope": scope, + } + tenant_id = creds["tenant_id"] + else: + raise AssertionError + return Request( + url=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token", + method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data=urllib.parse.urlencode(data).encode("utf8"), + success_codes=success_codes, + ) + + +def create_api_request(req: Request, auth: Tuple[str, str]) -> Request: + if req.headers is None: + headers = {} + else: + headers = dict(req.headers).copy() + + if req.params is None: + params = {} + else: + params = dict(req.params).copy() + + # https://docs.microsoft.com/en-us/rest/api/storageservices/previous-azure-storage-service-versions + headers["x-ms-version"] = "2019-02-02" + headers["x-ms-date"] = datetime.datetime.now(tz=datetime.timezone.utc).strftime( + "%a, %d %b %Y %H:%M:%S GMT" + ) + data = req.data + if data is not None and isinstance(data, dict): + data = xml.unparse(data) + + result = Request( + method=req.method, + url=req.url, + params=params, + headers=headers, + data=data, + preload_content=req.preload_content, + success_codes=tuple(req.success_codes), + retry_codes=tuple(req.retry_codes), + ) + + kind, token = auth + if kind == SHARED_KEY: + # make sure we are signing the request that has the ms headers added already + headers["Authorization"] = sign_with_shared_key(result, token) + elif kind == OAUTH_TOKEN: + headers["Authorization"] = f"Bearer {token}" + elif kind == ANONYMOUS: + pass + return result + + +def generate_signed_url(key: Mapping[str, str], url: str) -> Tuple[str, float]: + # https://docs.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature + # https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + # https://docs.microsoft.com/en-us/rest/api/storageservices/service-sas-examples + params = { + "st": key["SignedStart"], + "se": key["SignedExpiry"], + "sks": key["SignedService"], + "skt": key["SignedStart"], + "ske": key["SignedExpiry"], + "sktid": key["SignedTid"], + "skoid": key["SignedOid"], + # signed key version (param name not mentioned in docs) + "skv": key["SignedVersion"], + "sv": "2018-11-09", # signed version + "sr": "b", # signed resource + "sp": "r", # signed permissions + "sip": "", # signed ip + "si": "", # signed identifier + "spr": "https,http", # signed http protocol + "rscc": "", # Cache-Control header + "rscd": "", # Content-Disposition header + "rsce": "", # Content-Encoding header + "rscl": "", # Content-Language header + "rsct": "", # Content-Type header + } + u = urllib.parse.urlparse(url) + storage_account = u.netloc.split(".")[0] + canonicalized_resource = urllib.parse.unquote(f"/blob/{storage_account}/{u.path[1:]}") + parts_to_sign = ( + params["sp"], + params["st"], + params["se"], + canonicalized_resource, + params["skoid"], + params["sktid"], + params["skt"], + params["ske"], + params["sks"], + params["skv"], + params["sip"], + params["spr"], + params["sv"], + params["sr"], + params["rscc"], + params["rscd"], + params["rsce"], + params["rscl"], + params["rsct"], + # this is documented on a different page + # https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#specifying-the-signed-identifier + params["si"], + ) + string_to_sign = "\n".join(parts_to_sign) + params["sig"] = base64.b64encode( + hmac.digest(base64.b64decode(key["Value"]), string_to_sign.encode("utf8"), "sha256") + ).decode("utf8") + query = urllib.parse.urlencode({k: v for k, v in params.items() if v != ""}) + # convert to a utc struct_time by replacing the timezone + ts = time.strptime(key["SignedExpiry"].replace("Z", "GMT"), "%Y-%m-%dT%H:%M:%S%Z") + t = calendar.timegm(ts) + return url + "?" + query, t + + +def split_path(path: str) -> Tuple[str, str, str]: + if path.startswith("az://"): + return split_az_path(path) + elif path.startswith("https://"): + return split_https_path(path) + else: + raise Error(f"Invalid path: '{path}'") + + +def split_az_path(path: str) -> Tuple[str, str, str]: + parts = path[len("az://") :].split("/") + if len(parts) < 2: + raise Error(f"Invalid path: '{path}'") + account = parts[0] + container = parts[1] + if container == "": + raise Error(f"Invalid path: '{path}'") + obj = "/".join(parts[2:]) + return account, container, obj + + +def split_https_path(path: str) -> Tuple[str, str, str]: + parts = path[len("https://") :].split("/") + if len(parts) < 2: + raise Error(f"Invalid path: '{path}'") + hostname = parts[0] + container = parts[1] + if not hostname.endswith(".blob.core.windows.net") or container == "": + raise Error(f"Invalid path: '{path}'") + obj = "/".join(parts[2:]) + account = hostname.split(".")[0] + return account, container, obj + + +def combine_https_path(account: str, container: str, obj: str) -> str: + return f"https://{account}.blob.core.windows.net/{container}/{obj}" + + +def combine_az_path(account: str, container: str, obj: str) -> str: + return f"az://{account}/{container}/{obj}" + + +def combine_path(conf: Config, account: str, container: str, obj: str) -> str: + if conf.output_az_paths: + return combine_az_path(account, container, obj) + else: + return combine_https_path(account, container, obj) + + +def mkdirfile(conf: Config, path: str) -> None: + if not path.endswith("/"): + path += "/" + account, container, blob = split_path(path) + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="PUT", + headers={"x-ms-blob-type": "BlockBlob"}, + success_codes=(201, 400), + ) + resp = execute_api_request(conf, req) + if resp.status == 400: + raise Error(f"Unable to create directory, account/container does not exist: '{path}'") + + +def sign_with_shared_key(req: Request, key: str) -> str: + # https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key + params_to_sign = [] + if req.params is not None: + for name, value in req.params.items(): + canonical_name = name.lower() + params_to_sign.append(f"{canonical_name}:{value}") + + u = urllib.parse.urlparse(req.url) + storage_account = u.netloc.split(".")[0] + canonical_url = f"/{storage_account}/{u.path[1:]}" + canonicalized_resource = "\n".join([canonical_url] + list(sorted(params_to_sign))) + + if req.headers is None: + headers = {} + else: + headers = dict(req.headers) + + headers_to_sign = [] + for name, value in headers.items(): + canonical_name = name.lower() + canonical_value = re.sub(r"\s+", " ", value).strip() + if canonical_name.startswith("x-ms-"): + headers_to_sign.append(f"{canonical_name}:{canonical_value}") + canonicalized_headers = "\n".join(sorted(headers_to_sign)) + + content_length = headers.get("Content-Length", "") + if req.data is not None: + content_length = str(len(req.data)) + + parts_to_sign = [ + req.method, + headers.get("Content-Encoding", ""), + headers.get("Content-Language", ""), + content_length, + headers.get("Content-MD5", ""), + headers.get("Content-Type", ""), + headers.get("Date", ""), + headers.get("If-Modified-Since", ""), + headers.get("If-Match", ""), + headers.get("If-None-Match", ""), + headers.get("If-Unmodified-Since", ""), + headers.get("Range", ""), + canonicalized_headers, + canonicalized_resource, + ] + string_to_sign = "\n".join(parts_to_sign) + + signature = base64.b64encode( + hmac.digest(base64.b64decode(key), string_to_sign.encode("utf8"), "sha256") + ).decode("utf8") + + return f"SharedKey {storage_account}:{signature}" + + +def _get_md5(metadata: Mapping[str, Any]) -> Optional[str]: + if "Content-MD5" in metadata: + b64_encoded = metadata["Content-MD5"] + if b64_encoded is None: + return None + return base64.b64decode(b64_encoded).hex() + else: + return None + + +_MONTH_NAME_TO_INDEX = { + "Jan": "01", + "Feb": "02", + "Mar": "03", + "Apr": "04", + "May": "05", + "Jun": "06", + "Jul": "07", + "Aug": "08", + "Sep": "09", + "Oct": "10", + "Nov": "11", + "Dec": "12", +} + + +def _parse_timestamp(text: str) -> float: + # this function seems faster than using strptime + # text="Sun, 27 Sep 2009 18:41:57 GMT" + # 0 1 2 3 4 5 + p = text.split() + date_string = f"{p[3]}-{_MONTH_NAME_TO_INDEX[p[2]]}-{p[1]}T{p[4]}+00:00" + dt = datetime.datetime.fromisoformat(date_string) + return dt.timestamp() + + +def make_stat(item: Mapping[str, str]) -> Stat: + if "Creation-Time" in item: + raw_ctime = item["Creation-Time"] + else: + raw_ctime = item["x-ms-creation-time"] + if "x-ms-meta-blobfilemtime" in item: + mtime = float(item["x-ms-meta-blobfilemtime"]) + else: + mtime = _parse_timestamp(item["Last-Modified"]) + return Stat( + size=int(item["Content-Length"]), + mtime=mtime, + ctime=_parse_timestamp(raw_ctime), + md5=_get_md5(item), + version=item["Etag"], + ) + + +def _can_access_container( + conf: Config, + account: str, + container: str, + auth: Tuple[str, str], + out_failures: List[RequestFailure], +) -> bool: + # https://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list + success_codes = [200, 403, 404, INVALID_HOSTNAME_STATUS] + if auth[0] == ANONYMOUS: + # some containers can produce a 409 error "PublicAccessNotPermitted" when accessed with an anonymous account + success_codes.append(409) + + def build_req() -> Request: + req = Request( + method="GET", + url=build_url(account, "/{container}", container=container), + params={"restype": "container", "comp": "list", "maxresults": "1"}, + success_codes=success_codes, + ) + return create_api_request(req, auth=auth) + + resp = common.execute_request(conf, build_req) + # technically INVALID_HOSTNAME_STATUS means we can't access the account because it + # doesn't exist, but to be consistent with how we treat this error elsewhere we + # ignore it here + if resp.status == INVALID_HOSTNAME_STATUS: + return True + # anonymous requests will for some reason get a 404 when they should get a 403 + # so treat a 404 from anon requests as a 403 + if resp.status == 404 and auth[0] == ANONYMOUS: + out_failures.append( + RequestFailure.create_from_request_response( + "Could not access container", build_req(), resp + ) + ) + return False + # if the container list succeeds or the container doesn't exist, return success + if resp.status in (200, 404): + return True + else: + out_failures.append( + RequestFailure.create_from_request_response( + "Could not access container", build_req(), resp + ) + ) + return False + + +def _get_storage_account_id( + conf: Config, subscription_id: str, account: str, auth: Tuple[str, str] +) -> Optional[str]: + # get a list of storage accounts + url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Storage/storageAccounts" + params = {"api-version": "2019-04-01"} + while True: + + def build_req() -> Request: + req = Request(method="GET", url=url, params=params, success_codes=(200, 401, 403)) + return create_api_request(req, auth=auth) + + resp = common.execute_request(conf, build_req) + if resp.status in (401, 403): + # we aren't allowed to query this for this subscription, skip it + return None + + out = json.loads(resp.data) + # check if we found the storage account we are looking for + for obj in out["value"]: + if obj["name"] == account: + return obj["id"] + + if "nextLink" not in out: + return None + + url = out["nextLink"] + params = None # the url will already have params on it + + +def _get_subscription_ids(conf: Config, auth: Tuple[str, str]) -> List[str]: + url = "https://management.azure.com/subscriptions" + params = {"api-version": "2020-01-01"} + result = [] + while True: + + def build_req() -> Request: + req = Request(method="GET", url=url, params=params) + return create_api_request(req, auth=auth) + + resp = common.execute_request(conf, build_req) + data = json.loads(resp.data) + result.extend([item["subscriptionId"] for item in data["value"]]) + if "nextLink" not in data: + return result + url = data["nextLink"] + params = None # the url will already have params on it + + +def _get_storage_account_key( + conf: Config, + account: str, + container: str, + creds: Mapping[str, Any], + out_failures: List[RequestFailure], +) -> Optional[Tuple[Any, float]]: + # azure resource manager has very low limits on number of requests, so we have + # to be careful to avoid extra requests here + # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#storage-resource-provider-limits + + # in general, this code path should be avoided by using a service principal and + # giving it access to the bucket + + # get an access token for the management service + def build_req_access_token() -> Request: + return _create_access_token_request( + creds=creds, scope="https://management.azure.com/.default" + ) + + resp = common.execute_request(conf, build_req_access_token) + result = json.loads(resp.data) + auth = (OAUTH_TOKEN, result["access_token"]) + + # attempt to use list of subscriptions from the azure cli tool + stored_subscription_ids = load_subscription_ids() + + storage_account_id = None + for subscription_id in stored_subscription_ids: + storage_account_id = _get_storage_account_id(conf, subscription_id, account, auth) + if storage_account_id is not None: + break + else: + # if we didn't find the storage account we are looking for, check to see if there + # are any subscriptions that we did not query + subscription_ids = _get_subscription_ids(conf, auth) + unchecked_subscription_ids = [ + id for id in subscription_ids if id not in stored_subscription_ids + ] + + for subscription_id in unchecked_subscription_ids: + storage_account_id = _get_storage_account_id(conf, subscription_id, account, auth) + if storage_account_id is not None: + break + else: + # we failed to find the storage account, give up + return None + + def build_req_list_keys() -> Request: + req = Request( + method="POST", + url=f"https://management.azure.com{storage_account_id}/listKeys", + params={"api-version": "2019-04-01"}, + ) + return create_api_request(req, auth=auth) + + resp = common.execute_request(conf, build_req_list_keys) + result = json.loads(resp.data) + for key in result["keys"]: + if key["permissions"] == "FULL": + storage_key_auth = (SHARED_KEY, key["value"]) + if _can_access_container( + conf, account, container, storage_key_auth, out_failures=out_failures + ): + return storage_key_auth + else: + raise Error( + f"Found storage account key, but it was unable to access storage account: '{account}' and container: '{container}'" + ) + raise Error(f"Storage account was found, but storage account keys were missing: '{account}'") + + +def _get_access_token(conf: Config, key: Any) -> Tuple[Any, float]: + account, container = key + now = time.time() + creds = _load_credentials() + azure_auth = creds.get("_azure_auth") + access_failures: List[RequestFailure] = [] + if azure_auth == "sakey": + if "account" in creds: + if creds["account"] != account: + raise Error( + f"Provided storage account key for account '{creds['account']}' via environment variables, " + f"but needed credentials for account '{account}'" + ) + auth = (SHARED_KEY, creds["storage_account_key"]) + if _can_access_container(conf, account, container, auth, out_failures=access_failures): + return (auth, now + SHARED_KEY_EXPIRATION_SECONDS) + elif azure_auth == "refresh": + # we have a refresh token, convert it into an access token for this account + def build_req() -> Request: + return _create_access_token_request( + creds=creds, + scope=f"https://{account}.blob.core.windows.net/.default", + success_codes=(200, 400), + ) + + resp = common.execute_request(conf, build_req) + result = json.loads(resp.data) + if resp.status == 400: + if ( + ( + result["error"] == "invalid_grant" + and "AADSTS700082" in result["error_description"] + ) + or ( + result["error"] == "interaction_required" + and "AADSTS50078" in result["error_description"] + ) + or ( + result["error"] == "interaction_required" + and "AADSTS50076" in result["error_description"] + ) + ): + raise Error( + "Your refresh token is no longer valid, please run `az login` to get a new one" + ) + else: + raise Error( + f"Encountered an error when requesting an access token: `{result['error']}: {result['error_description']}`. You can attempt to fix this by re-running `az login`." + ) + + auth = (OAUTH_TOKEN, result["access_token"]) + + # for some azure accounts this access token does not work, check if it works + if _can_access_container(conf, account, container, auth, out_failures=access_failures): + return (auth, now + float(result["expires_in"])) + + if conf.use_azure_storage_account_key_fallback: + # fall back to getting the storage keys + storage_account_key_auth = _get_storage_account_key( + conf=conf, + account=account, + container=container, + creds=creds, + out_failures=access_failures, + ) + if storage_account_key_auth is not None: + return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS) + elif azure_auth == "svcact": + # we have a service principal, get an oauth token + def build_req() -> Request: + return _create_access_token_request( + creds=creds, scope="https://storage.azure.com/.default" + ) + + resp = common.execute_request(conf, build_req) + result = json.loads(resp.data) + auth = (OAUTH_TOKEN, result["access_token"]) + if _can_access_container(conf, account, container, auth, out_failures=access_failures): + return (auth, now + float(result["expires_in"])) + + if conf.use_azure_storage_account_key_fallback: + # fall back to getting the storage keys + storage_account_key_auth = _get_storage_account_key( + conf=conf, + account=account, + container=container, + creds=creds, + out_failures=access_failures, + ) + if storage_account_key_auth is not None: + return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS) + + # If opted into using azure-identity, use DefaultAzureCredential to get a token + # This enables the use of Managed Identity, Workload Identity, and other auth methods not implemented here + elif azure_auth == "azure-identity": + try: + from azure.identity import DefaultAzureCredential # pyright: ignore + except ImportError: + raise RuntimeError( + "When setting AZURE_USE_IDENTITY=1, you must also install the azure-identity package" + ) + + with DefaultAzureCredential() as cred: + token = cred.get_token("https://storage.azure.com/.default") + auth = (OAUTH_TOKEN, token.token) + if _can_access_container(conf, account, container, auth, out_failures=access_failures): + return (auth, token.expires_on) + + if conf.use_azure_storage_account_key_fallback: + # fall back to getting the storage keys + storage_account_key_auth = _get_storage_account_key( + conf=conf, + account=account, + container=container, + creds=creds, + out_failures=access_failures, + ) + if storage_account_key_auth is not None: + return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS) + + # oddly, it seems that if you request a public container with a valid azure account, you cannot list the bucket + # but if you list it with no account, that works fine + anonymous_auth = (ANONYMOUS, "") + if _can_access_container( + conf, account, container, anonymous_auth, out_failures=access_failures + ): + return (anonymous_auth, float("inf")) + + msg = f"Could not find any credentials that grant access to storage account: '{account}' and container: '{container}'" + if len(access_failures) > 0: + for resp_failure in access_failures: + msg += f"\n Access Failure: {resp_failure}" + if len(creds) == 0: + msg += """ + +No Azure credentials were found. If the container is not marked as public, please do one of the following: + +* Log in with 'az login', blobfile will use your default credentials to lookup your storage account key +* Set the environment variable 'AZURE_STORAGE_KEY' to your storage account key which you can find by following this guide: https://docs.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage +* Create an account with 'az ad sp create-for-rbac --name ' and set the 'AZURE_APPLICATION_CREDENTIALS' environment variable to the path of the output from that command or individually set the 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', and 'AZURE_TENANT_ID' environment variables""" + raise Error(msg) + + +def _get_sas_token(conf: Config, key: Any) -> Tuple[Any, float]: + auth = access_token_manager.get_token(conf, key=key) + if auth[0] == ANONYMOUS: + # for public containers, use None as the token so that this will be cached + # and we can tell when we don't have a real SAS token for a container + return (None, time.time() + SAS_TOKEN_EXPIRATION_SECONDS) + + account, container = key + + def build_req() -> Request: + # https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + now = datetime.datetime.now(tz=datetime.timezone.utc) + start = (now + datetime.timedelta(hours=-1)).strftime("%Y-%m-%dT%H:%M:%SZ") + expiry = (now + datetime.timedelta(days=6)).strftime("%Y-%m-%dT%H:%M:%SZ") + req = Request( + url=f"https://{account}.blob.core.windows.net/", + method="POST", + params=dict(restype="service", comp="userdelegationkey"), + data={"KeyInfo": {"Start": start, "Expiry": expiry}}, + success_codes=(200, 403), + ) + auth = access_token_manager.get_token(conf, key=key) + if auth[0] != OAUTH_TOKEN: + raise Error( + "Only OAuth tokens can be used to get SAS tokens. You should set the Storage " + "Blob Data Reader or Storage Blob Data Contributor IAM role. You can run " + f"`az storage blob list --auth-mode login --account-name {account} --container {container}` " + "to confirm that the missing role is the issue." + ) + return create_api_request(req, auth=auth) + + resp = common.execute_request(conf, build_req) + if resp.status == 403: + raise Error( + f"You do not have permission to generate an SAS token for account {account}. " + "Try setting the Storage Blob Delegator or Storage Blob Data Contributor IAM role " + "at the account level." + ) + out = xml.parse(resp.data) + t = time.time() + SAS_TOKEN_EXPIRATION_SECONDS + return out["UserDelegationKey"], t + + +def execute_api_request(conf: Config, req: Request) -> "urllib3.BaseHTTPResponse": + u = urllib.parse.urlparse(req.url) + account = u.netloc.split(".")[0] + path_parts = u.path.split("/") + if len(path_parts) < 2: + raise Error("missing container from path") + container = u.path.split("/")[1] + + def build_req() -> Request: + return create_api_request( + req, auth=access_token_manager.get_token(conf, key=(account, container)) + ) + + return common.execute_request(conf, build_req) + + +def _block_index_to_block_id(index: int, upload_id: int) -> str: + assert index < 2**17 + id_plus_index = (upload_id << 17) + index + assert id_plus_index < 2**64 + return base64.b64encode(id_plus_index.to_bytes(8, byteorder="big")).decode("utf8") + + +def _clear_uncommitted_blocks( + conf: Config, url: str, metadata: Mapping[str, str] +) -> Optional["urllib3.BaseHTTPResponse"]: + # to avoid leaking uncommitted blocks, we can do a Put Block List with + # all the existing blocks for a file + # this will change the last-modified timestamp and the etag + req = Request(url=url, params=dict(comp="blocklist"), method="GET", success_codes=(200, 404)) + resp = execute_api_request(conf, req) + if resp.status != 200: + return + + result = xml.parse(resp.data, repeated_tags={"Block"}) + if result["BlockList"]["CommittedBlocks"] is None: + return + + blocks = result["BlockList"]["CommittedBlocks"]["Block"] + body = {"BlockList": {"Latest": [b["Name"] for b in blocks]}} + # make sure to preserve metadata for the file + headers: Dict[str, str] = {k: v for k, v in metadata.items() if k.startswith("x-ms-meta-")} + for src, dst in RESPONSE_HEADER_TO_REQUEST_HEADER.items(): + if src in metadata: + headers[dst] = metadata[src] + req = Request( + url=url, + method="PUT", + params=dict(comp="blocklist"), + headers={**headers, "If-Match": metadata["etag"]}, + data=body, + success_codes=(201, 404, 412), + ) + + return execute_api_request(conf, req) + + +def _finalize_blob( + conf: Config, + path: str, + url: str, + block_ids: List[str], + md5_digest: Optional[bytes], + version: Optional[str], +) -> "urllib3.BaseHTTPResponse": + body = {"BlockList": {"Latest": block_ids}} + headers = {} + if md5_digest is not None: + # azure does not calculate md5s for us, we have to do that manually + # https://web.archive.org/web/20190118183153/https://blogs.msdn.microsoft.com/windowsazurestorage/2011/02/17/windows-azure-blob-md5-overview/ + headers["x-ms-blob-content-md5"] = base64.b64encode(md5_digest).decode("utf8") + + if version is not None: + headers["If-Match"] = version + req = Request( + url=url, + method="PUT", + headers=headers, + params=dict(comp="blocklist"), + data=body, + success_codes=(201, 400, 404, 412, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + if resp.status == 400: + result = xml.parse(resp.data) + if result["Error"]["Code"] == "InvalidBlockList": + # the most likely way this could happen is if the file was deleted while + # we were uploading, so assume that is what happened + # this could be interpreted as a sort of RestartableStreamingWriteFailure but + # that could result in two processes fighting while uploading the file + raise ConcurrentWriteFailure.create_from_request_response( + f"Invalid block list, most likely a concurrent writer wrote to the same path: `{path}`", + request=req, + response=resp, + ) + else: + raise RequestFailure.create_from_request_response( + message=f"unexpected status {resp.status}", request=req, response=resp + ) + elif resp.status == 404 or resp.status == INVALID_HOSTNAME_STATUS: + # this can occur when using parallel upload + raise FileNotFoundError(f"No such file or directory: '{path}'") + elif resp.status == 412: + if resp.headers["x-ms-error-code"] != "ConditionNotMet": + raise RequestFailure.create_from_request_response( + message=f"unexpected status {resp.status}", request=req, response=resp + ) + else: + raise VersionMismatch.create_from_request_response( + message="etag mismatch", request=req, response=resp + ) + return resp + + +def isdir(conf: Config, path: str) -> bool: + """ + Return true if a path is an existing directory + """ + if not path.endswith("/"): + path += "/" + account, container, blob = split_path(path) + if blob == "": + req = Request( + url=build_url(account, "/{container}", container=container, blob=blob), + method="GET", + params=dict(restype="container"), + success_codes=(200, 404, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + return resp.status == 200 + else: + # even though we're only interested in having one result, we still need to make an + # iterator. as it happens, azure is perfectly willing to return an empty first page. + it = create_page_iterator( + conf, + url=build_url(account, "/{container}", container=container), + method="GET", + params=dict( + comp="list", restype="container", prefix=blob, delimiter="/", maxresults="1" + ), + ) + for result in it: + if result["Blobs"] is not None: + return "BlobPrefix" in result["Blobs"] or "Blob" in result["Blobs"] + return False + + +def create_page_iterator( + conf: Config, + url: str, + method: str, + data: Optional[Mapping[str, str]] = None, + params: Optional[Mapping[str, str]] = None, +) -> Iterator[Dict[str, Any]]: + if params is None: + p = {} + else: + p = dict(params).copy() + if data is None: + d = None + else: + d = dict(data).copy() + while True: + req = Request( + url=url, + method=method, + params=p, + data=d, + success_codes=(200, 404, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + if resp.status in (404, INVALID_HOSTNAME_STATUS): + return + result = xml.parse(resp.data, repeated_tags={"BlobPrefix", "Blob"})["EnumerationResults"] + yield result + if result["NextMarker"] is None: + break + p["marker"] = result["NextMarker"] + + +class StreamingReadFile(BaseStreamingReadFile): + def __init__( + self, conf: Config, path: str, size: Optional[int], version: Optional[str] + ) -> None: + self._version: Optional[str] = version + if size is None: + st = maybe_stat(conf, path, version=version) + if st is None: + raise FileNotFoundError(f"No such file or directory: '{path}'") + size = st.size + self._version = st.version + super().__init__(conf=conf, path=path, size=size) + + def _request_chunk( + self, streaming: bool, start: int, end: Optional[int] = None + ) -> "urllib3.BaseHTTPResponse": + account, container, blob = split_path(self._path) + headers = {"Range": common.calc_range(start=start, end=end)} + if self._version is not None: + headers["If-Match"] = self._version + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="GET", + headers=headers, + success_codes=(206, 416), + # if we are streaming the data, make + # sure we don't preload it + preload_content=not streaming, + ) + resp = execute_api_request(self._conf, req) + self._version = self._version or resp.headers.get("ETag") + return resp + + +class StreamingWriteFile(BaseStreamingWriteFile): + def __init__(self, conf: Config, path: str, version: Optional[str]) -> None: + self._path = path + account, container, blob = split_path(path) + self._url = build_url(account, "/{container}/{blob}", container=container, blob=blob) + # block blobs let you upload up to 100,000 "uncommitted" blocks with user-chosen block ids + # using the "Put Block" call + # you may then call "Put Block List" with up to 50,000 block ids of the blocks you + # want to be in the blob (50,000 is the max blocks per blob) + # all unused uncommitted blocks will be deleted + # uncommitted blocks also expire after a week if they are not committed + # + # since we use block blobs, there are a few ways we could implement this streaming write file + # + # method 1: + # upload the first chunk of the file as block id "0", the second as block id "1" etc + # when we are done writing the file, we call "Put Block List" using range(num_blocks) as + # the block ids + # + # this has the advantage that if our program crashes, the same block ids will be reused + # for the next upload and so we'll never get more than 50,000 uncommitted blocks + # + # in general, azure does not seem to support concurrent writers except maybe + # for writing small files (GCS does to a limited extent through resumable upload sessions) + # + # with method 1, if you have two writers: + # + # writer 0: write block id "0" + # writer 1: write block id "0" + # writer 1: crash + # writer 0: write block id "1" + # writer 0: put block list ["0", "1"] + # + # then you will end up with block "0" from writer 1 and block "1" from writer 0, which means + # your file will be corrupted + # + # this appears to be the method used by the azure python SDK + # + # method 2: + # generate a random session id + # upload the first chunk of the file as block id "-0", + # the second block as "-1" etc + # when we are done writing the file, call "Put Block List" using + # [f"-{i}" for i in range(num_blocks)] as the block list + # + # this has the advantage that we should not observe data corruption from concurrent writers + # assuming that the session ids are unique, although whichever writer finishes first will + # win, because calling "Put Block List" will delete all uncommitted blocks + # + # this has the disadvantage that we can end up hitting the uncommitted block limit + # 1) with 100,000 concurrent writers, each one would write the first block, then all + # would immediately hit the block limit and get 409 errors + # 2) with a single writer that crashes every time it writes the second block, it would + # retry 100,000 times, then be unable to continue due to all the uncommitted blocks + # it was generating + # + # the workaround we use here is that whenever a file is opened for reading, we clear all + # uncommitted blocks by calling "Put Block List" with the list of currently committed blocks + # + # this seems to be reasonably fast in practice, and means that failure #2 should not be an issue + # + # failure #1 could still happen with concurrent writers, but this should result only in a + # confusing error message (409 error) instead of a ConcurrentWriteFailure, though we + # could likely raise that error if we saw a 409 with the error RequestEntityTooLargeBlockCountExceedsLimit + # + # this does change the behavior slightly, now the writer that will end up succeeding on "Put Block List" + # is likely to be the last writer to open the file for writing, the others will fail + # because their uncommitted blocks have been cleared + # + # it would be nice to replace this with a less odd method, but it's not obvious how + # to do this on azure storage + # + # if there were upload sessions like GCS, this wouldn't be an issue + # if there was no uncommitted block limit, method 2 would work fine + # if blobs could automatically expire without having to add a container lifecycle rule + # then we could upload to a temp path, then copy to the final path (assuming copy is atomic) + # without automatic expiry, we'd leak temp files + # we can use the lease system, but then we have to deal with leases + + self._upload_id = rng.randint(0, 2**47 - 1) + self._block_index = 0 + self._version: Optional[str] = version # for azure, this is an etag + # check to see if there is an existing blob at this location with the wrong type + req = Request( + url=self._url, + method="HEAD", + headers={"If-Match": self._version} if self._version else {}, + success_codes=(200, 400, 404, 412, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + if resp.status == 200: + if resp.headers["x-ms-blob-type"] == "BlockBlob": + # because we delete all the uncommitted blocks, any concurrent writers will fail + # but they would fail anyway since the first writer to finish would end up + # deleting all uncommitted blocks + # this means that the last writer to start is likely to win, the others should fail + # with ConcurrentWriteFailure + resp = _clear_uncommitted_blocks(conf, self._url, resp.headers) + if resp: + self._version = resp.headers["ETag"] # update the version according to new etag + else: + # if the existing blob type is not compatible with the block blob we are about to write + # we have to delete the file before writing our block blob or else we will get a 409 + # error when putting the first block + remove(conf, path) + elif resp.status in (400, INVALID_HOSTNAME_STATUS) or ( + resp.status == 404 and resp.headers["x-ms-error-code"] == "ContainerNotFound" + ): + raise FileNotFoundError(f"No such file or container/account does not exist: '{path}'") + elif resp.status == 412: + if resp.headers["x-ms-error-code"] != "ConditionNotMet": + raise RequestFailure.create_from_request_response( + message=f"unexpected status {resp.status}", request=req, response=resp + ) + else: + raise VersionMismatch.create_from_request_response( + message="etag mismatch", request=req, response=resp + ) + self._md5 = hashlib.md5() + super().__init__(conf=conf, chunk_size=conf.azure_write_chunk_size) + + def _upload_chunk(self, chunk: memoryview, finalize: bool) -> None: + start = 0 + while start < len(chunk): + # premium block blob storage supports block blobs and append blobs + # https://azure.microsoft.com/en-us/blog/azure-premium-block-blob-storage-is-now-generally-available/ + # we use block blobs because they are compatible with WASB: + # https://docs.microsoft.com/en-us/azure/databricks/kb/data-sources/wasb-check-blob-types + end = start + self._conf.azure_write_chunk_size + data = chunk[start:end] + self._md5.update(data) + block_md5 = hashlib.md5(data) + req = Request( + url=self._url, + method="PUT", + headers={"Content-MD5": base64.b64encode(block_md5.digest()).decode("utf8")}, + params=dict( + comp="block", + blockid=_block_index_to_block_id(self._block_index, self._upload_id), + ), + data=data, + success_codes=(201,), + # retry if we get an MD5 mismatch error (unfortunately we are just guessing that it is a mismatch error + # from the 400 status code) + retry_codes=(400,) + DEFAULT_RETRY_CODES, + ) + try: + execute_api_request(self._conf, req) + except Exception: + del chunk, data, req.data, req + raise + + self._block_index += 1 + if self._block_index >= BLOCK_COUNT_LIMIT: + raise Error( + f"Exceeded block count limit of {BLOCK_COUNT_LIMIT} for Azure Storage. Increase `azure_write_chunk_size` so that {BLOCK_COUNT_LIMIT} * `azure_write_chunk_size` exceeds the size of the file you are writing." + ) + + start = end + + if finalize: + block_ids = [ + _block_index_to_block_id(i, self._upload_id) for i in range(self._block_index) + ] + resp = _finalize_blob( + conf=self._conf, + path=self._path, + url=self._url, + block_ids=block_ids, + md5_digest=self._md5.digest(), + version=self._version, + ) + # Update the version according to new etag. The file will be closed + # after this, but the version can still be retrieved. + self._version = resp.headers.get("ETag") or self._version + + +def _upload_chunk(conf: Config, path: str, start: int, size: int, url: str, block_id: str) -> None: + req = Request( + url=url, + method="PUT", + params=dict(comp="block", blockid=block_id), + # this needs to be specified since we use a file object for the data + headers={"Content-Length": str(size)}, + data=FileBody(path, start=start, end=start + size), + success_codes=(201, 404, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + if resp.status == 404 or resp.status == INVALID_HOSTNAME_STATUS: + # this can happen during parallel upload + raise FileNotFoundError(f"No such file or directory: '{url}'") + + +def parallel_upload( + conf: Config, + executor: concurrent.futures.Executor, + src: str, + dst: str, + return_md5: bool, + dst_version: Optional[str], +) -> Optional[str]: + with open(src, "rb") as f: + md5_digest = common.block_md5(f) + + account, container, blob = split_path(dst) + dst_url = build_url(account, "/{container}/{blob}", container=container, blob=blob) + + upload_id = rng.randint(0, 2**47 - 1) + s = os.stat(src) + block_ids = [] + max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1) + part_size = min( + max(math.ceil(s.st_size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE), + MAX_BLOCK_SIZE, + ) + i = 0 + start = 0 + futures = [] + while start < s.st_size: + block_id = _block_index_to_block_id(i, upload_id) + future = executor.submit( + _upload_chunk, conf, src, start, min(part_size, s.st_size - start), dst_url, block_id + ) + futures.append(future) + block_ids.append(block_id) + i += 1 + start += part_size + for future in futures: + future.result() + + _finalize_blob( + conf=conf, + path=dst, + url=dst_url, + block_ids=block_ids, + md5_digest=md5_digest, + version=dst_version, + ) + return binascii.hexlify(md5_digest).decode("utf8") if return_md5 else None + + +def maybe_stat(conf: Config, path: str, *, version: Optional[str] = None) -> Optional[Stat]: + account, container, blob = split_path(path) + if blob == "": + return None + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="HEAD", + success_codes=(200, 404, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + if resp.status != 200: + return None + stat = make_stat(resp.headers) + if version is not None and stat.version != version: + raise VersionMismatch.create_from_request_response( + message="etag mismatch", request=req, response=resp + ) + return stat + + +def remove(conf: Config, path: str) -> bool: + account, container, blob = split_path(path) + if blob == "": + raise FileNotFoundError(f"The system cannot find the path specified: '{path}'") + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="DELETE", + success_codes=(202, 404, INVALID_HOSTNAME_STATUS), + ) + resp = execute_api_request(conf, req) + return resp.status == 202 + + +def maybe_update_md5(conf: Config, path: str, etag: str, hexdigest: str) -> bool: + account, container, blob = split_path(path) + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="HEAD", + headers={"If-Match": etag}, + success_codes=(200, 404, 412), + ) + resp = execute_api_request(conf, req) + if resp.status in (404, 412): + return False + + # these will be cleared if not provided, there does not appear to be a PATCH method like for GCS + # https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties#remarks + headers: Dict[str, str] = {} + for src, dst in RESPONSE_HEADER_TO_REQUEST_HEADER.items(): + if src in resp.headers: + headers[dst] = resp.headers[src] + headers["x-ms-blob-content-md5"] = base64.b64encode(binascii.unhexlify(hexdigest)).decode( + "utf8" + ) + + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="PUT", + params=dict(comp="properties"), + headers={ + **headers, + # https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations + "If-Match": etag, + }, + # for a 403, we actually maybe could have updated the md5, but we don't have permission + # for a 404, this could be due to this being some anonymous access container + # for both cases this is potentially bad because it means cache_dir won't work, it might be nice to let the user + # know if there's a non-spammy way to do it + success_codes=(200, 403, 404, 412), + ) + resp = execute_api_request(conf, req) + return resp.status == 200 + + +def list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]: + params = {} + if delimiter is not None: + params["delimiter"] = delimiter + + account, container, prefix = split_path(path) + it = create_page_iterator( + conf, + url=build_url(account, "/{container}", container=container), + method="GET", + params=dict(comp="list", restype="container", prefix=prefix, **params), + ) + for result in it: + yield from _get_entries(conf, account, container, result) + + +def entry_from_dirpath(path: str) -> DirEntry: + if path.endswith("/"): + path = path[:-1] + _, _, obj = split_path(path) + name = obj.split("/")[-1] + return DirEntry(name=name, path=path, is_dir=True, is_file=False, stat=None) + + +def entry_from_path_stat(path: str, stat: Stat) -> DirEntry: + assert not path.endswith("/") + _, _, obj = split_path(path) + name = obj.split("/")[-1] + return DirEntry(name=name, path=path, is_dir=False, is_file=True, stat=stat) + + +def _get_entries( + conf: Config, account: str, container: str, result: Mapping[str, Any] +) -> Iterator[DirEntry]: + blobs = result["Blobs"] + if blobs is None: + return + if "BlobPrefix" in blobs: + for bp in blobs["BlobPrefix"]: + path = combine_path(conf, account, container, bp["Name"]) + yield entry_from_dirpath(path) + if "Blob" in blobs: + for b in blobs["Blob"]: + path = combine_path(conf, account, container, b["Name"]) + if b["Name"].endswith("/"): + yield entry_from_dirpath(path) + else: + props = b["Properties"] + yield entry_from_path_stat(path, make_stat(props)) + + +def get_url(conf: Config, path: str) -> Tuple[str, Optional[float]]: + account, container, blob = split_path(path) + url = build_url(account, "/{container}/{blob}", container=container, blob=blob) + token = sas_token_manager.get_token(conf=conf, key=(account, container)) + if token is None: + # the container has public access + return url, float("inf") + return generate_signed_url(key=token, url=url) + + +def set_mtime(conf: Config, path: str, mtime: float, version: Optional[str] = None) -> bool: + account, container, blob = split_path(path) + headers = {} + if version is not None: + headers["If-Match"] = version + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="HEAD", + params=dict(comp="metadata"), + headers=headers, + success_codes=(200, 404, 412), + ) + resp = execute_api_request(conf, req) + if resp.status == 404: + raise FileNotFoundError(f"No such file: '{path}'") + if resp.status == 412: + return False + + headers = {k: v for k, v in resp.headers.items() if k.startswith("x-ms-meta-")} + headers["x-ms-meta-blobfilemtime"] = str(mtime) + if version is not None: + headers["If-Match"] = version + req = Request( + url=build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="PUT", + params=dict(comp="metadata"), + headers=headers, + success_codes=(200, 404, 412), + ) + resp = execute_api_request(conf, req) + if resp.status == 404: + raise FileNotFoundError(f"No such file: '{path}'") + return resp.status == 200 + + +def dirname(conf: Config, path: str) -> str: + account, container, obj = split_path(path) + obj = strip_slashes(obj) + if "/" in obj: + obj = "/".join(obj.split("/")[:-1]) + return combine_path(conf, account, container, obj) + else: + return combine_path(conf, account, container, "")[:-1] + + +def remote_copy(conf: Config, src: str, dst: str, return_md5: bool) -> Optional[str]: + # https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + dst_account, dst_container, dst_blob = split_path(dst) + src_account, src_container, src_blob = split_path(src) + + def build_req() -> Request: + src_url = build_url( + src_account, "/{container}/{blob}", container=src_container, blob=src_blob + ) + if src_account != dst_account: + # the signed url can expire, so technically we should get the sas_token and build the signed url + # each time we build a new request + sas_token = sas_token_manager.get_token(conf=conf, key=(src_account, src_container)) + # if we don't get a token, it's likely we have anonymous access to the container + # if we do get a token, the container is likely private and we need to use + # a signed url as the source + if sas_token is not None: + src_url, _ = generate_signed_url(key=sas_token, url=src_url) + req = Request( + url=build_url( + dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob + ), + method="PUT", + headers={"x-ms-copy-source": src_url}, + success_codes=(202, 404, 409, INVALID_HOSTNAME_STATUS), + ) + return create_api_request( + req, auth=access_token_manager.get_token(conf=conf, key=(dst_account, dst_container)) + ) + + copy_id = None + copy_status = None + etag = None + + # start the copy, waiting for any existing copies to finish + backoff_generator = common.exponential_sleep_generator() + for backoff in backoff_generator: + resp = common.execute_request(conf, build_req) + if resp.status == 202: + copy_id = resp.headers["x-ms-copy-id"] + copy_status = resp.headers["x-ms-copy-status"] + etag = resp.headers["etag"] + break + elif resp.status == INVALID_HOSTNAME_STATUS: + raise FileNotFoundError( + f"Source container or destination container not found: src='{src}' dst='{dst}'" + ) + elif resp.status == 404: + if resp.headers["x-ms-error-code"] == "ContainerNotFound": + raise FileNotFoundError( + f"Source container or destination container not found: src='{src}' dst='{dst}'" + ) + + raise FileNotFoundError(f"Source file not found: '{src}'") + elif resp.status == 409: + result = xml.parse(resp.data) + if result["Error"]["Code"] != "PendingCopyOperation": + raise RequestFailure.create_from_request_response( + message=f"unexpected status {resp.status}", request=build_req(), response=resp + ) + # if we got a pending copy operation, continue to wait + else: + raise Error(f"unhandled status {resp.status}") + time.sleep(backoff) + + # wait for potentially async copy operation to finish + # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + # pending, success, aborted, failed + backoff_generator = common.exponential_sleep_generator() + while copy_status == "pending": + time.sleep(next(backoff_generator)) + req = Request( + url=build_url( + dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob + ), + method="GET", + ) + resp = execute_api_request(conf, req) + if resp.headers["x-ms-copy-id"] != copy_id: + raise Error("Copy id mismatch") + etag = resp.headers["etag"] + copy_status = resp.headers["x-ms-copy-status"] + if copy_status != "success": + raise Error(f"Invalid copy status: '{copy_status}'") + if return_md5: + # if the file is the same one that we just copied, return the stored MD5 + st = maybe_stat(conf, dst) + if st is not None and st.version == etag: + return st.md5 + return + + +def join_paths(conf: Config, a: str, b: str) -> str: + if not a.endswith("/"): + a += "/" + + account, container, obj = split_path(a) + obj = path_join(obj, b) + if obj.startswith("/"): + obj = obj[1:] + return combine_path(conf, account, container, obj) + + +def _put_block_from_url( + conf: Config, src: str, start: int, size: int, dst: str, block_id: str +) -> None: + src_account, src_container, src_blob = split_path(src) + dst_account, dst_container, dst_blob = split_path(dst) + + src_url = build_url(src_account, "/{container}/{blob}", container=src_container, blob=src_blob) + + dst_url = build_url(dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob) + + def build_req() -> Request: + # the signed url can expire, so technically we should get the sas_token and build the signed url + # each time we build a new request + sas_token = sas_token_manager.get_token(conf=conf, key=(src_account, src_container)) + # if we don't get a token, it's likely we have anonymous access to the container + # if we do get a token, the container is likely private and we need to use + # a signed url as the source + if sas_token is None: + copy_src_url = src_url + else: + copy_src_url, _ = generate_signed_url(key=sas_token, url=src_url) + req = Request( + url=dst_url, + method="PUT", + params=dict(comp="block", blockid=block_id), + headers={ + "Content-Length": "0", + "x-ms-copy-source": copy_src_url, + "x-ms-source-range": common.calc_range(start=start, end=start + size), + }, + success_codes=(201, 404, INVALID_HOSTNAME_STATUS), + ) + return create_api_request( + req, auth=access_token_manager.get_token(conf=conf, key=(dst_account, dst_container)) + ) + + resp = common.execute_request(conf, build_req) + if resp.status == 404: + raise FileNotFoundError( + f"Source file/container or destination container not found: src='{src}' dst='{dst}'" + ) + elif resp.status == INVALID_HOSTNAME_STATUS: + raise FileNotFoundError( + f"Source container or destination container not found: src='{src}' dst='{dst}'" + ) + + +def parallel_remote_copy( + conf: Config, + executor: concurrent.futures.Executor, + src: str, + dst: str, + return_md5: bool, + dst_version: Optional[str], +) -> Optional[str]: + # for whatever reason, put block from url is faster than copy blob when you run multiple requests in parallel + # https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url + + st = maybe_stat(conf, src) + if st is None: + raise FileNotFoundError(f"The system cannot find the path specified: '{src}'") + + md5_digest = None + if st.md5 is not None: + md5_digest = binascii.unhexlify(st.md5) + upload_id = rng.randint(0, 2**47 - 1) + block_ids = [] + min_block_size = st.size // BLOCK_COUNT_LIMIT + assert min_block_size <= MAX_BLOCK_SIZE + part_size = max(conf.azure_write_chunk_size, min_block_size) + i = 0 + start = 0 + futures = [] + while start < st.size: + block_id = _block_index_to_block_id(i, upload_id) + future = executor.submit( + _put_block_from_url, conf, src, start, min(part_size, st.size - start), dst, block_id + ) + futures.append(future) + block_ids.append(block_id) + i += 1 + start += part_size + for future in futures: + future.result() + + dst_account, dst_container, dst_blob = split_path(dst) + dst_url = build_url(dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob) + + _finalize_blob( + conf=conf, + path=dst, + url=dst_url, + block_ids=block_ids, + md5_digest=md5_digest, + version=dst_version, + ) + return ( + binascii.hexlify(md5_digest).decode("utf8") + if (return_md5 and md5_digest is not None) + else None + ) + + +access_token_manager = TokenManager(_get_access_token, "azure_access") + +sas_token_manager = TokenManager(_get_sas_token, "azure_sas") diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_context.py b/videollama2/lib/python3.10/site-packages/blobfile/_context.py new file mode 100644 index 0000000000000000000000000000000000000000..7c238432e9da1ef55ae290bbe2d7fbe89f8b98b3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_context.py @@ -0,0 +1,1518 @@ +# https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime +from __future__ import annotations + +import binascii +import collections +import concurrent.futures +import contextlib +import hashlib +import io +import itertools +import math +import multiprocessing as mp +import os +import re +import shutil +import stat as stat_module +import tempfile +import time +import urllib.parse +from functools import partial +from types import ModuleType +from typing import ( + Any, + BinaryIO, + Callable, + Iterator, + List, + Literal, + NamedTuple, + Optional, + Sequence, + TextIO, + Tuple, + Union, + cast, + overload, +) + +import filelock +import urllib3 + +from blobfile import _azure as azure +from blobfile import _common as common +from blobfile import _gcp as gcp +from blobfile._common import ( + CHUNK_SIZE, + DEFAULT_CONNECTION_POOL_MAX_SIZE, + DEFAULT_MAX_CONNECTION_POOL_COUNT, + Config, + DirEntry, + Error, + RemoteOrLocalPath, + Request, + RestartableStreamingWriteFailure, + Stat, + get_log_threshold_for_error, + path_to_str, +) + +# https://cloud.google.com/storage/docs/naming +# https://www.w3.org/TR/xml/#charsets +INVALID_CHARS = set().union(range(0x0, 0x9)).union(range(0xB, 0xE)).union(range(0xE, 0x20)) + +DEFAULT_AZURE_WRITE_CHUNK_SIZE = 8 * 2**20 +DEFAULT_GOOGLE_WRITE_CHUNK_SIZE = 8 * 2**20 +DEFAULT_RETRY_LOG_THRESHOLD = 0 +DEFAULT_RETRY_COMMON_LOG_THRESHOLD = 2 +DEFAULT_CONNECT_TIMEOUT = 10 +DEFAULT_READ_TIMEOUT = 30 +DEFAULT_BUFFER_SIZE = 8 * 2**20 + + +def _execute_fn_and_ignore_result(fn: Callable[..., object], *args: Any): + fn(*args) + + +class Context: + def __init__(self, conf: Config): + self._conf = conf + + def copy( + self, + src: RemoteOrLocalPath, + dst: RemoteOrLocalPath, + overwrite: bool = False, + parallel: bool = False, + parallel_executor: Optional[concurrent.futures.Executor] = None, + return_md5: bool = False, + dst_version: Optional[str] = None, + ) -> Optional[str]: + src = path_to_str(src) + dst = path_to_str(dst) + # it would be best to check isdir() for remote paths, but that would + # involve 2 extra network requests, so just do this test instead + if _guess_isdir(src): + raise IsADirectoryError(f"Is a directory: '{src}'") + if _guess_isdir(dst): + raise IsADirectoryError(f"Is a directory: '{dst}'") + + if not overwrite: + if self.exists(dst): + raise FileExistsError( + f"Destination '{dst}' already exists and overwrite is disabled" + ) + + if dst_version is not None: + assert _is_azure_path( + dst + ), f"Destination version was specified, but destination path {dst} does not support a version check" + + if parallel: + copy_fn = None + if (_is_azure_path(src) or _is_gcp_path(src)) and _is_local_path(dst): + copy_fn = _parallel_download + + if _is_local_path(src) and _is_azure_path(dst): + copy_fn = partial(azure.parallel_upload, dst_version=dst_version) + + if _is_local_path(src) and _is_gcp_path(dst): + copy_fn = gcp.parallel_upload + + if _is_azure_path(src) and _is_azure_path(dst): + src_account, _, _ = azure.split_path(src) + dst_account, _, _ = azure.split_path(dst) + if src_account != dst_account: + # normal remote copy is pretty fast and doesn't benefit from parallelization when used within + # a storage account + copy_fn = partial(azure.parallel_remote_copy, dst_version=dst_version) + + if copy_fn is not None: + if parallel_executor is None: + with concurrent.futures.ProcessPoolExecutor( + mp_context=mp.get_context(self._conf.multiprocessing_start_method) + ) as executor: + return copy_fn(self._conf, executor, src, dst, return_md5=return_md5) + else: + return copy_fn(self._conf, parallel_executor, src, dst, return_md5=return_md5) + + # special case cloud to cloud copy, don't download the file + if _is_gcp_path(src) and _is_gcp_path(dst): + return gcp.remote_copy(self._conf, src=src, dst=dst, return_md5=return_md5) + + if _is_azure_path(src) and _is_azure_path(dst): + # support could be added here for this but it's currently missing + assert ( + dst_version is None + ), f"Destination version was specified, but destination path {dst} does not support a version check" + return azure.remote_copy(self._conf, src=src, dst=dst, return_md5=return_md5) + + for attempt, backoff in enumerate(common.exponential_sleep_generator()): + try: + with self.BlobFile(src, "rb", streaming=True) as src_f, self.BlobFile( + dst, "wb", streaming=True, version=dst_version + ) as dst_f: + m = hashlib.md5() + while True: + block = src_f.read(CHUNK_SIZE) + if block == b"": + break + if return_md5: + m.update(block) + dst_f.write(block) + if return_md5: + return m.hexdigest() + else: + return + except RestartableStreamingWriteFailure as err: + # currently this is the only type of failure we retry, since we can re-read the source + # stream from the beginning + # if this failure occurs, the upload must be restarted from the beginning + # https://cloud.google.com/storage/docs/resumable-uploads#practices + # https://github.com/googleapis/gcs-resumable-upload/issues/15#issuecomment-249324122 + if self._conf.retry_limit is not None and attempt >= self._conf.retry_limit: + raise + + if attempt >= get_log_threshold_for_error(self._conf, str(err)): + self._conf.log_callback( + f"error {err} when executing a streaming write to {dst} attempt {attempt}, sleeping for {backoff:.1f} seconds before retrying" + ) + time.sleep(backoff) + + def exists(self, path: RemoteOrLocalPath) -> bool: + path = path_to_str(path) + if _is_local_path(path): + return os.path.exists(path) + elif _is_gcp_path(path): + st = gcp.maybe_stat(self._conf, path) + if st is not None: + return True + return self.isdir(path) + elif _is_azure_path(path): + st = azure.maybe_stat(self._conf, path) + if st is not None: + return True + return self.isdir(path) + else: + raise Error(f"Unrecognized path: '{path}'") + + def basename(self, path: RemoteOrLocalPath) -> str: + path = path_to_str(path) + if _is_gcp_path(path): + _, obj = gcp.split_path(path) + return obj.split("/")[-1] + elif _is_azure_path(path): + _, _, obj = azure.split_path(path) + return obj.split("/")[-1] + else: + return os.path.basename(path) + + def glob(self, pattern: str, parallel: bool = False) -> Iterator[str]: + if _is_local_path(pattern): + # scanglob currently does an os.stat for each matched file + # until scanglob can be implemented directly on scandir + # this code is here to avoid that + if "?" in pattern or "[" in pattern or "]" in pattern: + raise Error("Advanced glob queries are not supported") + yield from _local_glob(pattern) + else: + for entry in self.scanglob(pattern=pattern, parallel=parallel): + yield entry.path + + def scanglob( + self, pattern: str, parallel: bool = False, shard_prefix_length: int = 0 + ) -> Iterator[DirEntry]: + if "?" in pattern or "[" in pattern or "]" in pattern: + raise Error("Advanced glob queries are not supported") + + if _is_local_path(pattern): + for filepath in _local_glob(pattern): + # doing a stat call for each file isn't the most efficient + # iglob uses os.scandir internally, but doesn't expose the information from that, so we'd + # need to re-implement local glob + # we could make the behavior with remote glob more consistent though if we did that + s = os.stat(filepath) + is_dir = stat_module.S_ISDIR(s.st_mode) + yield DirEntry( + path=filepath, + name=self.basename(filepath), + is_dir=is_dir, + is_file=not is_dir, + stat=None + if is_dir + else Stat( + size=s.st_size, mtime=s.st_mtime, ctime=s.st_ctime, md5=None, version=None + ), + ) + elif _is_gcp_path(pattern) or _is_azure_path(pattern): + if "*" not in pattern: + entry = _get_entry(self._conf, pattern) + if entry is not None: + yield entry + return + + if _is_gcp_path(pattern): + bucket, blob_prefix = gcp.split_path(pattern) + if "*" in bucket: + raise Error("Wildcards cannot be used in bucket name") + root = gcp.combine_path(bucket, "") + else: + account, container, blob_prefix = azure.split_path(pattern) + if "*" in account or "*" in container: + raise Error("Wildcards cannot be used in account or container") + root = azure.combine_path(self._conf, account, container, "") + + if shard_prefix_length == 0: + initial_tasks = [_GlobTask("", _split_path(blob_prefix))] + else: + assert ( + parallel + ), "You probably want to use parallel=True if you are setting shard_prefix_length > 0" + initial_tasks = [] + valid_chars = [ + i for i in range(256) if i not in INVALID_CHARS.union([ord("/"), ord("*")]) + ] + pattern_prefix, pattern_suffix = blob_prefix.split("*", maxsplit=1) + for repeat in range(1, shard_prefix_length + 1): + for chars in itertools.product(valid_chars, repeat=repeat): + prefix = "" + for c in chars: + prefix += chr(c) + # we need to check for exact matches for shorter prefix lengths + # if we only searched for prefixes of length `shard_prefix_length` + # we would skip shorter names, for instance "a" would be skipped if we + # we had `shard_prefix_length=2` + # instead we check for an exact match for everything shorter than + # our `shard_prefix_length` + exact = repeat != shard_prefix_length + if exact: + pat = pattern_prefix + prefix + else: + pat = pattern_prefix + prefix + "*" + pattern_suffix + initial_tasks.append(_GlobTask("", _split_path(pat))) + + if parallel: + mp_ctx = mp.get_context(self._conf.multiprocessing_start_method) + tasks = mp_ctx.Queue() + for t in initial_tasks: + tasks.put(t) + tasks_enqueued = len(initial_tasks) + results = mp_ctx.Queue() + + tasks_done = 0 + with mp_ctx.Pool( + initializer=_glob_worker, initargs=(self._conf, root, tasks, results) + ): + while tasks_done < tasks_enqueued: + r = results.get() + if isinstance(r, _GlobEntry): + yield r.entry + elif isinstance(r, _GlobTask): + tasks.put(r) + tasks_enqueued += 1 + elif isinstance(r, _GlobTaskComplete): + tasks_done += 1 + else: + raise Error("Invalid result") + else: + dq: collections.deque[_GlobTask] = collections.deque() + for t in initial_tasks: + dq.append(t) + while len(dq) > 0: + t = dq.popleft() + for r in _process_glob_task(conf=self._conf, root=root, t=t): + if isinstance(r, _GlobEntry): + yield r.entry + else: + dq.append(r) + else: + raise Error(f"Unrecognized path '{pattern}'") + + def isdir(self, path: RemoteOrLocalPath) -> bool: + path = path_to_str(path) + if _is_local_path(path): + return os.path.isdir(path) + elif _is_gcp_path(path): + return gcp.isdir(self._conf, path) + elif _is_azure_path(path): + return azure.isdir(self._conf, path) + else: + raise Error(f"Unrecognized path: '{path}'") + + def listdir(self, path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[str]: + path = path_to_str(path) + for entry in self.scandir(path, shard_prefix_length=shard_prefix_length): + yield entry.name + + def scandir(self, path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[DirEntry]: + path = path_to_str(path) + if (_is_gcp_path(path) or _is_azure_path(path)) and not path.endswith("/"): + path += "/" + if not self.exists(path): + raise FileNotFoundError(f"The system cannot find the path specified: '{path}'") + if not self.isdir(path): + raise NotADirectoryError(f"The directory name is invalid: '{path}'") + if _is_local_path(path): + for de in os.scandir(path): + if de.is_dir(): + yield DirEntry( + name=de.name, + path=os.path.abspath(de.path), + is_dir=True, + is_file=False, + stat=None, + ) + else: + s = de.stat() + yield DirEntry( + name=de.name, + path=os.path.abspath(de.path), + is_dir=False, + is_file=True, + stat=Stat( + size=s.st_size, + mtime=s.st_mtime, + ctime=s.st_ctime, + md5=None, + version=None, + ), + ) + elif _is_gcp_path(path) or _is_azure_path(path): + if shard_prefix_length == 0: + yield from _list_blobs_in_dir(conf=self._conf, prefix=path, exclude_prefix=True) + else: + mp_ctx = mp.get_context(self._conf.multiprocessing_start_method) + prefixes = mp_ctx.Queue() + items = mp_ctx.Queue() + tasks_enqueued = 0 + + valid_chars = [i for i in range(256) if i not in INVALID_CHARS and i != ord("/")] + for repeat in range(1, shard_prefix_length + 1): + for chars in itertools.product(valid_chars, repeat=repeat): + prefix = "" + for c in chars: + prefix += chr(c) + # we need to check for exact matches for shorter prefix lengths + # if we only searched for prefixes of length `shard_prefix_length` + # we would skip shorter names, for instance "a" would be skipped if we + # we had `shard_prefix_length=2` + # instead we check for an exact match for everything shorter than + # our `shard_prefix_length` + exact = repeat != shard_prefix_length + prefixes.put((path, prefix, exact)) + tasks_enqueued += 1 + + tasks_done = 0 + with mp_ctx.Pool( + initializer=_sharded_listdir_worker, initargs=(self._conf, prefixes, items) + ): + while tasks_done < tasks_enqueued: + entry = items.get() + if entry is None: + tasks_done += 1 + continue + yield entry + else: + raise Error(f"Unrecognized path: '{path}'") + + def makedirs(self, path: RemoteOrLocalPath) -> None: + path = path_to_str(path) + if _is_local_path(path): + os.makedirs(path, exist_ok=True) + elif _is_gcp_path(path): + gcp.mkdirfile(self._conf, path) + elif _is_azure_path(path): + azure.mkdirfile(self._conf, path) + else: + raise Error(f"Unrecognized path: '{path}'") + + def remove(self, path: RemoteOrLocalPath) -> None: + path = path_to_str(path) + if _is_local_path(path): + os.remove(path) + elif _is_gcp_path(path): + if path.endswith("/"): + raise IsADirectoryError(f"Is a directory: '{path}'") + ok = gcp.remove(self._conf, path) + if not ok: + raise FileNotFoundError(f"The system cannot find the path specified: '{path}'") + elif _is_azure_path(path): + if path.endswith("/"): + raise IsADirectoryError(f"Is a directory: '{path}'") + ok = azure.remove(self._conf, path) + if not ok: + raise FileNotFoundError(f"The system cannot find the path specified: '{path}'") + else: + raise Error(f"Unrecognized path: '{path}'") + + def rmdir(self, path: RemoteOrLocalPath) -> None: + path = path_to_str(path) + if _is_local_path(path): + os.rmdir(path) + return + + # directories in blob storage are different from normal directories + # a directory exists if there are any blobs that have that directory as a prefix + # when the last blob with that prefix is deleted, the directory no longer exists + # except in the case when there is a blob with a name ending in a slash + # representing an empty directory + + # to make this more usable it is not an error to delete a directory that does + # not exist, but is still an error to delete a non-empty one + if not path.endswith("/"): + path += "/" + + if _is_gcp_path(path): + _, blob = gcp.split_path(path) + elif _is_azure_path(path): + _, _, blob = azure.split_path(path) + else: + raise Error(f"Unrecognized path: '{path}'") + + if blob == "": + raise Error(f"Cannot delete bucket: '{path}'") + it = self.listdir(path) + try: + next(it) + except FileNotFoundError: + # this directory does not exist + return + except StopIteration: + # this directory exists and is empty + pass + else: + # this directory exists but is not empty + raise OSError(f"The directory is not empty: '{path}'") + + if _is_gcp_path(path): + bucket, blob = gcp.split_path(path) + req = Request( + url=gcp.build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob), + method="DELETE", + success_codes=(204,), + ) + gcp.execute_api_request(self._conf, req) + elif _is_azure_path(path): + account, container, blob = azure.split_path(path) + req = Request( + url=azure.build_url(account, "/{container}/{blob}", container=container, blob=blob), + method="DELETE", + success_codes=(202,), + ) + azure.execute_api_request(self._conf, req) + else: + raise Error(f"Unrecognized path: '{path}'") + + def stat(self, path: RemoteOrLocalPath) -> Stat: + path = path_to_str(path) + if _is_local_path(path): + s = os.stat(path) + return Stat(size=s.st_size, mtime=s.st_mtime, ctime=s.st_ctime, md5=None, version=None) + elif _is_gcp_path(path): + st = gcp.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + return st + elif _is_azure_path(path): + st = azure.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + return st + else: + raise Error(f"Unrecognized path: '{path}'") + + def set_mtime( + self, path: RemoteOrLocalPath, mtime: float, version: Optional[str] = None + ) -> bool: + path = path_to_str(path) + if _is_local_path(path): + assert version is None + os.utime(path, times=(mtime, mtime)) + return True + elif _is_gcp_path(path): + return gcp.set_mtime(self._conf, path=path, mtime=mtime, version=version) + elif _is_azure_path(path): + return azure.set_mtime(self._conf, path=path, mtime=mtime, version=version) + else: + raise Error(f"Unrecognized path: '{path}'") + + def rmtree( + self, + path: RemoteOrLocalPath, + parallel: bool = False, + parallel_executor: Optional[concurrent.futures.Executor] = None, + ) -> None: + path = path_to_str(path) + if not self.isdir(path): + raise NotADirectoryError(f"The directory name is invalid: '{path}'") + + if _is_local_path(path): + shutil.rmtree(path) + elif _is_gcp_path(path) or _is_azure_path(path): + if not path.endswith("/"): + path += "/" + + if _is_gcp_path(path): + + def request_generator(): + bucket, blob = gcp.split_path(path) + for entry in gcp.list_blobs(self._conf, path): + entry_slash_path = _get_slash_path(entry) + entry_bucket, entry_blob = gcp.split_path(entry_slash_path) + assert entry_bucket == bucket and entry_blob.startswith(blob) + req = Request( + url=gcp.build_url( + "/storage/v1/b/{bucket}/o/{object}", + bucket=bucket, + object=entry_blob, + ), + method="DELETE", + # 404 is allowed in case a failed request successfully deleted the file + # before erroring out + success_codes=(204, 404), + ) + yield req + + fn = gcp.execute_api_request + + elif _is_azure_path(path): + + def request_generator(): + account, container, blob = azure.split_path(path) + for entry in azure.list_blobs(self._conf, path): + entry_slash_path = _get_slash_path(entry) + entry_account, entry_container, entry_blob = azure.split_path( + entry_slash_path + ) + assert ( + entry_account == account + and entry_container == container + and entry_blob.startswith(blob) + ) + req = Request( + url=azure.build_url( + account, "/{container}/{blob}", container=container, blob=entry_blob + ), + method="DELETE", + # 404 is allowed in case a failed request successfully deleted the file + # before erroring out + success_codes=(202, 404), + ) + yield req + + fn = azure.execute_api_request + else: + raise Error(f"Unrecognized path: '{path}'") + + if parallel: + if parallel_executor is None: + executor = concurrent.futures.ProcessPoolExecutor( + mp_context=mp.get_context(self._conf.multiprocessing_start_method) + ) + context = executor + else: + executor = parallel_executor + context = contextlib.nullcontext() + + futures = [] + with context: + for req in request_generator(): + f = executor.submit(_execute_fn_and_ignore_result, fn, self._conf, req) + futures.append(f) + for f in futures: + f.result() + else: + for req in request_generator(): + fn(self._conf, req) + else: + raise Error(f"Unrecognized path: '{path}'") + + def walk( + self, + top: RemoteOrLocalPath, + topdown: bool = True, + onerror: Optional[Callable[[OSError], None]] = None, + ) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]: + top = path_to_str(top) + if not self.isdir(top): + return + + if _is_local_path(top): + top = os.path.normpath(top) + for root, dirnames, filenames in os.walk(top=top, topdown=topdown, onerror=onerror): + assert isinstance(root, str) + if root.endswith(os.sep): + root = root[:-1] + yield (root, sorted(dirnames), sorted(filenames)) + elif _is_gcp_path(top) or _is_azure_path(top): + top = _normalize_path(self._conf, top) + if not top.endswith("/"): + top += "/" + if topdown: + dq: collections.deque[str] = collections.deque() + dq.append(top) + while len(dq) > 0: + cur = dq.popleft() + assert cur.endswith("/") + if _is_gcp_path(top): + it = gcp.list_blobs(self._conf, cur, delimiter="/") + elif _is_azure_path(top): + it = azure.list_blobs(self._conf, cur, delimiter="/") + else: + raise Error(f"Unrecognized path: '{top}'") + dirnames = [] + filenames = [] + for entry in it: + entry_path = _get_slash_path(entry) + if entry_path == cur: + continue + if entry.is_dir: + dirnames.append(entry.name) + else: + filenames.append(entry.name) + yield (_strip_slash(cur), dirnames, filenames) + dq.extend(self.join(cur, dirname) + "/" for dirname in dirnames) + else: + if _is_gcp_path(top): + it = gcp.list_blobs(self._conf, top) + elif _is_azure_path(top): + it = azure.list_blobs(self._conf, top) + else: + raise Error(f"Unrecognized path: '{top}'") + + cur = [] + dirnames_stack = [[]] + filenames_stack = [[]] + for entry in it: + entry_slash_path = _get_slash_path(entry) + if entry_slash_path == top: + continue + relpath = entry_slash_path[len(top) :] + parts = relpath.split("/") + dirpath = parts[:-1] + if dirpath != cur: + # pop directories from the current path until we match the prefix of this new path + while cur != dirpath[: len(cur)]: + yield (top + "/".join(cur), dirnames_stack.pop(), filenames_stack.pop()) + cur.pop() + # push directories from the new path until the current path matches it + while cur != dirpath: + dirname = dirpath[len(cur)] + cur.append(dirname) + filenames_stack.append([]) + # add this to child dir to the list of dirs for the parent + dirnames_stack[-1].append(dirname) + dirnames_stack.append([]) + if entry.is_file: + filenames_stack[-1].append(entry.name) + while len(cur) > 0: + yield (top + "/".join(cur), dirnames_stack.pop(), filenames_stack.pop()) + cur.pop() + yield (_strip_slash(top), dirnames_stack.pop(), filenames_stack.pop()) + assert len(dirnames_stack) == 0 and len(filenames_stack) == 0 + else: + raise Error(f"Unrecognized path: '{top}'") + + def dirname(self, path: RemoteOrLocalPath) -> str: + path = path_to_str(path) + if _is_gcp_path(path): + return gcp.dirname(self._conf, path) + elif _is_azure_path(path): + return azure.dirname(self._conf, path) + else: + return os.path.dirname(path) + + def join(self, a: RemoteOrLocalPath, *args: str) -> str: + a = path_to_str(a) + out = a + for b in args: + out = _join2(self._conf, out, b) + return out + + def get_url(self, path: RemoteOrLocalPath) -> Tuple[str, Optional[float]]: + path = path_to_str(path) + if _is_gcp_path(path): + return gcp.get_url(self._conf, path) + elif _is_azure_path(path): + return azure.get_url(self._conf, path) + elif _is_local_path(path): + return f"file://{path}", None + else: + raise Error(f"Unrecognized path: '{path}'") + + def md5(self, path: RemoteOrLocalPath) -> str: + path = path_to_str(path) + if _is_gcp_path(path): + st = gcp.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + + h = st.md5 + if h is not None: + return h + + # this is probably a composite object, calculate the md5 and store it on the file if the file has not changed + with self.BlobFile(path, "rb") as f: + result = common.block_md5(f).hex() + + assert st.version is not None + gcp.maybe_update_md5(self._conf, path, st.version, result) + return result + elif _is_azure_path(path): + st = azure.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties + h = st.md5 + if h is None: + # md5 is missing, calculate it and store it on file if the file has not changed + with self.BlobFile(path, "rb") as f: + h = common.block_md5(f).hex() + assert st.version is not None + azure.maybe_update_md5(self._conf, path, st.version, h) + return h + else: + with self.BlobFile(path, "rb") as f: + return common.block_md5(f).hex() + + def last_version_seen(self, file: TextIO | BinaryIO) -> Optional[str]: + actual: object + actual = file + if isinstance(actual, io.TextIOWrapper): + actual = actual.buffer + if isinstance(actual, (io.BufferedReader, io.BufferedWriter)): + actual = actual.raw + if not isinstance(actual, (azure.StreamingReadFile, azure.StreamingWriteFile)): + raise ValueError("File was not an Azure BlobFile opened in streaming mode") + return actual._version # pyright: ignore[reportPrivateUsage] + + def read_text(self, path: RemoteOrLocalPath) -> str: + with self.BlobFile(path, "r") as f: + return f.read() + + def read_bytes(self, path: RemoteOrLocalPath) -> bytes: + with self.BlobFile(path, "rb") as f: + return f.read() + + def write_text(self, path: RemoteOrLocalPath, text: str) -> None: + with self.BlobFile(path, "w") as f: + f.write(text) + + def write_bytes(self, path: RemoteOrLocalPath, data: bytes) -> None: + with self.BlobFile(path, "wb") as f: + f.write(data) + + @overload + def BlobFile( + self, + path: RemoteOrLocalPath, + mode: Literal["rb", "wb", "ab"], + streaming: Optional[bool] = ..., + buffer_size: Optional[int] = ..., + cache_dir: Optional[str] = ..., + file_size: Optional[int] = None, + version: Optional[str] = None, + ) -> BinaryIO: + ... + + @overload + def BlobFile( + self, + path: RemoteOrLocalPath, + mode: Literal["r", "w", "a"] = ..., + streaming: Optional[bool] = ..., + buffer_size: Optional[int] = ..., + cache_dir: Optional[str] = ..., + file_size: Optional[int] = None, + version: Optional[str] = None, + ) -> TextIO: + ... + + def BlobFile( + self, + path: RemoteOrLocalPath, + mode: Literal["r", "rb", "w", "wb", "a", "ab"] = "r", + streaming: Optional[bool] = None, + buffer_size: Optional[int] = None, + cache_dir: Optional[str] = None, + file_size: Optional[int] = None, + version: Optional[str] = None, + ): + """ + Open a local or remote file for reading or writing + + Args: + path: local or remote path + mode: one of "r", "rb", "w", "wb", "a", "ab" indicating the mode to open the file in + streaming: the default for `streaming` is `True` when `mode` is in `"r", "rb"` and `False` when `mode` is in `"w", "wb", "a", "ab"`. + * `streaming=True`: + * Reading is done without downloading the entire remote file. + * Writing is done to the remote file directly, but only in chunks of a few MB in size. `flush()` will not cause an early write. + * Appending is not implemented. + * `streaming=False`: + * Reading is done by downloading the remote file to a local file during the constructor. + * Writing is done by uploading the file on `close()` or during destruction. + * Appending is done by downloading the file during construction and uploading on `close()` or during destruction. + buffer_size: number of bytes to buffer, this can potentially make reading more efficient. + cache_dir: a directory in which to cache files for reading, only valid if `streaming=False` and `mode` is in `"r", "rb"`. You are reponsible for cleaning up the cache directory. + file_size: size of the file being opened, can be specified directly to avoid checking the file size when opening the file. While this will avoid a network request, it also means that you may get an error when first reading a file that does not exist rather than when opening it. Only valid for modes "r" and "rb". This valid will be ignored for local files. + version: a version number of the file being opened, used to prevent overwriting a file that has changed since it was opened. Only valid for modes "w", "wb", "a", "ab" + + Returns: + A file-like object + """ + path = path_to_str(path) + if _guess_isdir(path): + raise IsADirectoryError(f"Is a directory: '{path}'") + + if streaming is None: + streaming = mode in ("r", "rb") + + if file_size is not None: + assert mode in ("r", "rb"), "Can only specify file_size when reading" + + if version: + assert not _is_local_path(path), "Cannot specify version when writing to local file" + # we check for gcp later to raise a NotImplementedError instead + + if _is_local_path(path) and "w" in mode: + # local filesystems require that intermediate directories exist, but this is not required by the + # remote filesystems + # for consistency, automatically create local intermediate directories + if self.dirname(path) != "": + self.makedirs(self.dirname(path)) + + if buffer_size is None: + buffer_size = self._conf.default_buffer_size + + if streaming: + if mode not in ("w", "wb", "r", "rb"): + raise Error(f"Invalid mode for streaming file: '{mode}'") + if cache_dir is not None: + raise Error("Cannot specify cache_dir for streaming files") + if _is_local_path(path): + f = io.FileIO(path, mode=mode) + if "r" in mode: + f = io.BufferedReader(f, buffer_size=buffer_size) + else: + f = io.BufferedWriter(f, buffer_size=buffer_size) + elif _is_gcp_path(path): + if version: + raise NotImplementedError("Cannot specify version for GCP files") + if mode in ("w", "wb"): + f = gcp.StreamingWriteFile(self._conf, path) + elif mode in ("r", "rb"): + f = gcp.StreamingReadFile(self._conf, path, size=file_size) + f = io.BufferedReader(f, buffer_size=buffer_size) + else: + raise Error(f"Unsupported mode: '{mode}'") + elif _is_azure_path(path): + if mode in ("w", "wb"): + f = azure.StreamingWriteFile(self._conf, path, version) + elif mode in ("r", "rb"): + f = azure.StreamingReadFile(self._conf, path, size=file_size, version=version) + f = io.BufferedReader(f, buffer_size=buffer_size) + else: + raise Error(f"Unsupported mode: '{mode}'") + else: + raise Error(f"Unrecognized path: '{path}'") + + # this should be a protocol so we don't have to cast + # but the standard library does not seem to have a file-like protocol + binary_f = cast(BinaryIO, f) + if "b" in mode: + return binary_f + else: + text_f = io.TextIOWrapper(binary_f, encoding="utf8") + # TextIOWrapper bypasses buffering on purpose: https://bugs.python.org/issue13393 + # Example: https://gist.github.com/christopher-hesse/b4aab4f6f9bcba597d079f3363dfab2c + # + # This happens when TextIOWrapper calls f.read1(CHUNK_SIZE) + # https://github.com/python/cpython/blob/3d17c045b4c3d09b72bbd95ed78af1ae6f0d98d2/Modules/_io/textio.c#L1854 + # and BufferedReader only reads the requested size, not the buffer_size + # https://github.com/python/cpython/blob/8666356280084f0426c28a981341f72eaaacd006/Modules/_io/bufferedio.c#L945 + # + # The workaround appears to be to set the _CHUNK_SIZE property or monkey patch binary_f.read1 to call binary_f.read + if hasattr(text_f, "_CHUNK_SIZE"): + setattr(text_f, "_CHUNK_SIZE", buffer_size) + return cast(TextIO, text_f) + else: + remote_path = None + tmp_dir = None + if mode not in ("w", "wb", "r", "rb", "a", "ab"): + raise Error(f"Invalid mode: '{mode}'") + + if cache_dir is not None and mode not in ("r", "rb"): + raise Error("cache_dir only supported in read mode") + + local_filename = self.basename(path) + if local_filename == "": + local_filename = "local.tmp" + if _is_gcp_path(path) or _is_azure_path(path): + remote_path = path + if mode in ("a", "ab"): + tmp_dir = tempfile.mkdtemp() + local_path = self.join(tmp_dir, local_filename) + if self.exists(remote_path): + self.copy(remote_path, local_path) + elif mode in ("r", "rb"): + if cache_dir is None: + tmp_dir = tempfile.mkdtemp() + local_path = self.join(tmp_dir, local_filename) + self.copy(remote_path, local_path) + else: + if not _is_local_path(cache_dir): + raise Error(f"cache_dir must be a local path: '{cache_dir}'") + self.makedirs(cache_dir) + path_md5 = hashlib.md5(path.encode("utf8")).hexdigest() + lock_path = self.join(cache_dir, f"{path_md5}.lock") + tmp_path = self.join(cache_dir, f"{path_md5}.tmp") + with filelock.FileLock(lock_path): + remote_version = "" + # get some sort of consistent remote hash so we can check for a local file + if _is_gcp_path(path): + st = gcp.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + assert st.version is not None + remote_version = st.version + remote_hash = st.md5 + elif _is_azure_path(path): + # in the azure case the remote md5 may not exist + # this duplicates some of md5() because we want more control + st = azure.maybe_stat(self._conf, path) + if st is None: + raise FileNotFoundError(f"No such file: '{path}'") + assert st.version is not None + remote_version = st.version + remote_hash = st.md5 + else: + raise Error(f"Unrecognized path: '{path}'") + + perform_copy = False + if remote_hash is None: + # there is no remote md5, copy the file + # and attempt to update the md5 + perform_copy = True + else: + expected_local_path = self.join( + cache_dir, remote_hash, local_filename + ) + perform_copy = not self.exists(expected_local_path) + + if perform_copy: + local_hexdigest = self.copy( + remote_path, tmp_path, overwrite=True, return_md5=True + ) + assert local_hexdigest is not None, "failed to return md5" + # the file we downloaded may not match the remote file because + # the remote file changed while we were downloading it + # in this case make sure we don't cache it under the wrong md5 + local_path = self.join(cache_dir, local_hexdigest, local_filename) + os.makedirs(self.dirname(local_path), exist_ok=True) + if os.path.exists(local_path): + # the file is already here, nevermind + os.remove(tmp_path) + else: + os.replace(tmp_path, local_path) + + if remote_hash is None: + if _is_azure_path(path): + azure.maybe_update_md5( + self._conf, path, remote_version, local_hexdigest + ) + elif _is_gcp_path(path): + gcp.maybe_update_md5( + self._conf, path, remote_version, local_hexdigest + ) + else: + assert remote_hash is not None + local_path = self.join(cache_dir, remote_hash, local_filename) + else: + tmp_dir = tempfile.mkdtemp() + local_path = self.join(tmp_dir, local_filename) + elif _is_local_path(path): + local_path = path + else: + raise Error(f"Unrecognized path: '{path}'") + + f = _ProxyFile( + ctx=self, + local_path=local_path, + mode=mode, + tmp_dir=tmp_dir, + remote_path=remote_path, + version=version, + ) + if "r" in mode: + f = io.BufferedReader(f, buffer_size=buffer_size) + else: + f = io.BufferedWriter(f, buffer_size=buffer_size) + binary_f = cast(BinaryIO, f) + if "b" in mode: + return binary_f + else: + text_f = io.TextIOWrapper(binary_f, encoding="utf8") + return cast(TextIO, text_f) + + +def default_log_fn(msg: str) -> None: + print(f"blobfile: {msg}") + + +def _is_gcp_path(path: str) -> bool: + url = urllib.parse.urlparse(path) + return url.scheme == "gs" + + +def _is_azure_path(path: str) -> bool: + url = urllib.parse.urlparse(path) + return ( + url.scheme == "https" and url.netloc.endswith(".blob.core.windows.net") + ) or url.scheme == "az" + + +def _get_module(path: str) -> Optional[ModuleType]: + if _is_gcp_path(path): + return gcp + elif _is_azure_path(path): + return azure + else: + return None + + +def _is_local_path(path: str) -> bool: + return _get_module(path) is None + + +def _download_chunk( + conf: Config, src: str, dst: str, start: int, size: int, src_file_size: int +) -> None: + ctx = Context(conf) + with ctx.BlobFile(src, "rb", file_size=src_file_size) as src_f: + src_f.seek(start) + # open output file such that we can write directly to the correct range + with open(dst, "rb+") as dst_f: + dst_f.seek(start) + bytes_read = 0 + while True: + n = min(CHUNK_SIZE, size - bytes_read) + assert n >= 0 + block = src_f.read(n) + if block == b"": + if bytes_read != size: + raise Error( + f"read wrong number of bytes from file `{src}`, expected {size} but read {bytes_read}" + ) + break + dst_f.write(block) + bytes_read += len(block) + + +def _parallel_download( + conf: Config, executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool +) -> Optional[str]: + ctx = Context(conf=conf) + + s = ctx.stat(src) + + # pre-allocate output file + if os.path.dirname(dst) != "": + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as f: + if s.size > 0: + f.seek(s.size - 1) + f.write(b"\0") + + max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1) + part_size = max(math.ceil(s.size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE) + start = 0 + futures = [] + while start < s.size: + future = executor.submit( + _download_chunk, conf, src, dst, start, min(part_size, s.size - start), s.size + ) + futures.append(future) + start += part_size + for future in futures: + future.result() + + if return_md5: + with ctx.BlobFile(dst, "rb") as f: + return binascii.hexlify(common.block_md5(f)).decode("utf8") + + +def _string_overlap(s1: str, s2: str) -> int: + length = min(len(s1), len(s2)) + for i in range(length): + if s1[i] != s2[i]: + return i + return length + + +def _split_path(path: str) -> List[str]: + # a/b/c => a/, b/, c + # a/b/ => a/, b/ + # /a/b/c => /, a/, b/, c + parts = [] + part = "" + for c in path: + part += c + if c == "/": + parts.append(part) + part = "" + if part != "": + parts.append(part) + return parts + + +def _expand_implicit_dirs(root: str, it: Iterator[DirEntry]) -> Iterator[DirEntry]: + # blob storage does not always have definitions for each intermediate dir + # if we have a listing like + # gs://test/a/b + # gs://test/a/b/c/d + # then we emit an entry "gs://test/a/b/c" for the implicit dir "c" + # requires that iterator return objects in sorted order + if _is_gcp_path(root): + entry_from_dirpath = gcp.entry_from_dirpath + elif _is_azure_path(root): + entry_from_dirpath = azure.entry_from_dirpath + else: + raise Error(f"Unrecognized path '{root}'") + + previous_path = root + for entry in it: + # find the overlap between the previous_path and the current + entry_slash_path = _get_slash_path(entry) + offset = _string_overlap(previous_path, entry_slash_path) + relpath = entry_slash_path[offset:] + cur = entry_slash_path[:offset] + for part in _split_path(relpath)[:-1]: + cur += part + yield entry_from_dirpath(cur) + yield entry + # assert entry_slash_path.encode("utf_16_be") >= previous_path.encode("utf_16_be") + previous_path = entry_slash_path + + +def _compile_pattern(s: str, sep: str = "/"): + tokens = [t for t in re.split("([*]+)", s) if t != ""] + regexp = "" + for tok in tokens: + if tok == "*": + regexp += f"[^{sep}]*" + elif tok == "**": + regexp += ".*" + else: + regexp += re.escape(tok) + return re.compile(regexp + f"{sep}?$") + + +def _glob_full(conf: Config, pattern: str) -> Iterator[DirEntry]: + prefix, _, _ = pattern.partition("*") + + re_pattern = _compile_pattern(pattern) + + for entry in _expand_implicit_dirs(root=prefix, it=_list_blobs(conf=conf, path=prefix)): + entry_slash_path = _get_slash_path(entry) + if bool(re_pattern.match(entry_slash_path)): + if entry_slash_path == prefix and entry.is_dir: + # we matched the parent directory + continue + yield entry + + +class _GlobTask(NamedTuple): + cur: str + rem: Sequence[str] + + +class _GlobEntry(NamedTuple): + entry: DirEntry + + +class _GlobTaskComplete(NamedTuple): + pass + + +def _process_glob_task( + conf: Config, root: str, t: _GlobTask +) -> Iterator[Union[_GlobTask, _GlobEntry]]: + cur = t.cur + t.rem[0] + rem = t.rem[1:] + if "**" in cur: + for entry in _glob_full(conf, root + cur + "".join(rem)): + yield _GlobEntry(entry) + elif "*" in cur: + re_pattern = _compile_pattern(root + cur) + prefix, _, _ = cur.partition("*") + path = root + prefix + for entry in _list_blobs(conf=conf, path=path, delimiter="/"): + entry_slash_path = _get_slash_path(entry) + # in the case of dirname/* we should not return the path dirname/ + if entry_slash_path == path and entry.is_dir: + # we matched the parent directory + continue + if bool(re_pattern.match(entry_slash_path)): + if len(rem) == 0: + yield _GlobEntry(entry) + else: + assert entry_slash_path.startswith(root) + yield _GlobTask(entry_slash_path[len(root) :], rem) + else: + if len(rem) == 0: + path = root + cur + entry = _get_entry(conf, path) + if entry is not None: + yield _GlobEntry(entry) + else: + yield _GlobTask(cur, rem) + + +def _glob_worker( + conf: Config, + root: str, + tasks: mp.Queue[_GlobTask], + results: mp.Queue[Union[_GlobEntry, _GlobTask, _GlobTaskComplete]], +) -> None: + while True: + t = tasks.get() + for r in _process_glob_task(conf, root=root, t=t): + results.put(r) + results.put(_GlobTaskComplete()) + + +def _local_glob(pattern: str) -> Iterator[str]: + normalized_pattern = os.path.normpath(pattern) + if pattern.endswith("/") or pattern.endswith("\\"): + # normpath will remove a trailing separator + # but these affect the output of the glob + normalized_pattern += os.sep + + if "*" in normalized_pattern: + prefix = normalized_pattern.split("*")[0] + if prefix.endswith(os.sep): + base_dir = os.path.abspath(prefix) + if not base_dir.endswith(os.sep): + # if base_dir is the root directory it will already have a separator + base_dir += os.sep + pattern_suffix = normalized_pattern[len(prefix) :] + else: + dirpath = os.path.dirname(prefix) + base_dir = os.path.abspath(dirpath) + # prefix dirpath pattern_suffix + # /a/b /a /b + # a/c a /c + # b "" "" + # "" "" "" + if len(dirpath) == 0: + pattern_suffix = os.sep + normalized_pattern + else: + pattern_suffix = normalized_pattern[len(dirpath) :] + full_pattern = base_dir + pattern_suffix + regexp = _compile_pattern(full_pattern, sep=os.sep) + for root, dirnames, filenames in os.walk(base_dir): + paths = [os.path.join(root, dirname + os.sep) for dirname in dirnames] + paths += [os.path.join(root, filename) for filename in filenames] + for path in paths: + if re.match(regexp, path): + if path.endswith(os.sep): + path = path[:-1] + yield path + else: + path = os.path.abspath(pattern) + if os.path.exists(path): + if path.endswith(os.sep): + path = path[:-1] + yield path + + +def _strip_slash(path: str) -> str: + if path.endswith("/"): + return path[:-1] + else: + return path + + +def _guess_isdir(path: str) -> bool: + """ + Guess if a path is a directory without performing network requests + """ + if _is_local_path(path) and os.path.isdir(path): + return True + elif (_is_gcp_path(path) or _is_azure_path(path)) and path.endswith("/"): + return True + return False + + +def _list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]: + params = {} + if delimiter is not None: + params["delimiter"] = delimiter + + if _is_gcp_path(path): + yield from gcp.list_blobs(conf, path, delimiter=delimiter) + elif _is_azure_path(path): + yield from azure.list_blobs(conf, path, delimiter=delimiter) + else: + raise Error(f"Unrecognized path: '{path}'") + + +def _get_slash_path(entry: DirEntry) -> str: + return entry.path + "/" if entry.is_dir else entry.path + + +def _normalize_path(conf: Config, path: str) -> str: + # convert paths to the canonical format + if _is_azure_path(path): + return azure.combine_path(conf, *azure.split_path(path)) + return path + + +def _list_blobs_in_dir(conf: Config, prefix: str, exclude_prefix: bool) -> Iterator[DirEntry]: + # the prefix check doesn't work without normalization + normalized_prefix = _normalize_path(conf, prefix) + for entry in _list_blobs(conf=conf, path=normalized_prefix, delimiter="/"): + if exclude_prefix and _get_slash_path(entry) == normalized_prefix: + continue + yield entry + + +def _get_entry(conf: Config, path: str) -> Optional[DirEntry]: + ctx = Context(conf) + if _is_gcp_path(path): + st = gcp.maybe_stat(conf, path) + if st is not None: + if path.endswith("/"): + return gcp.entry_from_dirpath(path) + else: + return gcp.entry_from_path_stat(path, st) + if ctx.isdir(path): + return gcp.entry_from_dirpath(path) + elif _is_azure_path(path): + st = azure.maybe_stat(conf, path) + if st is not None: + if path.endswith("/"): + return azure.entry_from_dirpath(path) + else: + return azure.entry_from_path_stat(path, st) + if ctx.isdir(path): + return azure.entry_from_dirpath(path) + else: + raise Error(f"Unrecognized path: '{path}'") + + return None + + +def _sharded_listdir_worker( + conf: Config, prefixes: mp.Queue[Tuple[str, str, bool]], items: mp.Queue[Optional[DirEntry]] +) -> None: + while True: + base, prefix, exact = prefixes.get(True) + if exact: + path = base + prefix + entry = _get_entry(conf, path) + if entry is not None: + items.put(entry) + else: + it = _list_blobs_in_dir(conf, base + prefix, exclude_prefix=False) + for entry in it: + items.put(entry) + items.put(None) # indicate that we have finished this path + + +def _join2(conf: Config, a: str, b: str) -> str: + if _is_local_path(a): + return os.path.join(a, b) + elif _is_gcp_path(a): + return gcp.join_paths(conf, a, b) + elif _is_azure_path(a): + return azure.join_paths(conf, a, b) + else: + raise Error(f"Unrecognized path: '{a}'") + + +class _ProxyFile(io.FileIO): + def __init__( + self, + ctx: Context, + local_path: str, + mode: Literal["r", "rb", "w", "wb", "a", "ab"], + tmp_dir: Optional[str], + remote_path: Optional[str], + version: Optional[str], + ) -> None: + super().__init__(local_path, mode=mode) + self._ctx = ctx + self._mode = mode + self._tmp_dir = tmp_dir + self._local_path = local_path + self._remote_path = remote_path + self._closed = False + self._version = version + + def close(self) -> None: + if not hasattr(self, "_closed") or self._closed: + return + + super().close() + try: + if self._remote_path is not None and self._mode in ("w", "wb", "a", "ab"): + self._ctx.copy( + self._local_path, self._remote_path, overwrite=True, dst_version=self._version + ) + finally: + # if the copy fails, still cleanup our local temp file so it is not leaked + if self._tmp_dir is not None: + os.remove(self._local_path) + os.rmdir(self._tmp_dir) + self._closed = True + + +def create_context( + *, + log_callback: Callable[[str], None] = default_log_fn, + connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE, + max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT, + # https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs + # the chunk size determines the maximum size of an individual blob + azure_write_chunk_size: int = DEFAULT_AZURE_WRITE_CHUNK_SIZE, + google_write_chunk_size: int = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE, + retry_log_threshold: int = DEFAULT_RETRY_LOG_THRESHOLD, + retry_common_log_threshold: int = DEFAULT_RETRY_COMMON_LOG_THRESHOLD, + retry_limit: Optional[int] = None, + connect_timeout: Optional[int] = DEFAULT_CONNECT_TIMEOUT, + read_timeout: Optional[int] = DEFAULT_READ_TIMEOUT, + output_az_paths: bool = True, + use_azure_storage_account_key_fallback: bool = False, + get_http_pool: Optional[Callable[[], urllib3.PoolManager]] = None, + use_streaming_read: bool = False, + default_buffer_size: int = DEFAULT_BUFFER_SIZE, + get_deadline: Optional[Callable[[], float]] = None, + save_access_token_to_disk: bool = True, + multiprocessing_start_method: str = "spawn", +): + """ + Same argument as configure(), but returns a Context object that has all the blobfile methods on it. + """ + conf = Config( + log_callback=log_callback, + connection_pool_max_size=connection_pool_max_size, + max_connection_pool_count=max_connection_pool_count, + azure_write_chunk_size=azure_write_chunk_size, + retry_log_threshold=retry_log_threshold, + retry_common_log_threshold=retry_common_log_threshold, + retry_limit=retry_limit, + google_write_chunk_size=google_write_chunk_size, + connect_timeout=connect_timeout, + read_timeout=read_timeout, + output_az_paths=output_az_paths, + use_azure_storage_account_key_fallback=use_azure_storage_account_key_fallback, + get_http_pool=get_http_pool, + use_streaming_read=use_streaming_read, + default_buffer_size=default_buffer_size, + get_deadline=get_deadline, + save_access_token_to_disk=save_access_token_to_disk, + multiprocessing_start_method=multiprocessing_start_method, + ) + return Context(conf=conf) diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_gcp.py b/videollama2/lib/python3.10/site-packages/blobfile/_gcp.py new file mode 100644 index 0000000000000000000000000000000000000000..9839a3bec6c80db82743740f60ffa6fa1cdecf34 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_gcp.py @@ -0,0 +1,786 @@ +import base64 +import binascii +import concurrent.futures +import datetime +import hashlib +import json +import math +import os +import platform +import socket +import time +import urllib.parse +from typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple + +import urllib3 + +from blobfile import _common as common +from blobfile._common import ( + GCP_BASE_URL, + BaseStreamingReadFile, + BaseStreamingWriteFile, + Config, + DirEntry, + Error, + FileBody, + Request, + RequestFailure, + RestartableStreamingWriteFailure, + Stat, + TokenManager, + path_join, + strip_slashes, +) + +MAX_EXPIRATION = 7 * 24 * 60 * 60 +OAUTH_TOKEN = "oauth_token" +ANONYMOUS = "anonymous" + + +def _is_gce_instance() -> bool: + try: + socket.getaddrinfo("metadata.google.internal", 80) + except socket.gaierror: + return False + return True + + +def _b64encode(s: bytes) -> bytes: + return base64.urlsafe_b64encode(s) + + +def _sign(private_key: str, msg: bytes) -> bytes: + from Cryptodome.Hash import SHA256 + from Cryptodome.PublicKey import RSA + from Cryptodome.Signature import pkcs1_15 + + key = RSA.import_key(private_key) + h = SHA256.new(msg) + return pkcs1_15.new(key).sign(h) + + +def _create_jwt(private_key: str, data: Mapping[str, Any]) -> bytes: + header_b64 = _b64encode(json.dumps({"alg": "RS256", "typ": "JWT"}).encode("utf8")) + body_b64 = _b64encode(json.dumps(data).encode("utf8")) + to_sign = header_b64 + b"." + body_b64 + signature_b64 = _b64encode(_sign(private_key, to_sign)) + return header_b64 + b"." + body_b64 + b"." + signature_b64 + + +def _create_token_request(client_email: str, private_key: str, scopes: List[str]) -> Request: + # https://developers.google.com/identity/protocols/OAuth2ServiceAccount + now = time.time() + claim_set = { + "iss": client_email, + "scope": " ".join(scopes), + "aud": "https://www.googleapis.com/oauth2/v4/token", + "exp": now + 60 * 60, + "iat": now, + } + data = { + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": _create_jwt(private_key, claim_set), + } + return Request( + url="https://www.googleapis.com/oauth2/v4/token", + method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data=urllib.parse.urlencode(data).encode("utf8"), + ) + + +def _refresh_access_token_request( + client_id: str, client_secret: str, refresh_token: str +) -> Request: + # https://developers.google.com/identity/protocols/OAuth2WebServer#offline + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "client_id": client_id, + "client_secret": client_secret, + } + return Request( + url="https://www.googleapis.com/oauth2/v4/token", + method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data=urllib.parse.urlencode(data).encode("utf8"), + ) + + +def _load_credentials() -> Dict[str, Any]: + if "GOOGLE_APPLICATION_CREDENTIALS" in os.environ: + creds_path = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] + if not os.path.exists(creds_path): + raise Error( + f"credentials not found at {creds_path} specified by environment variable 'GOOGLE_APPLICATION_CREDENTIALS'" + ) + with open(creds_path) as f: + return json.load(f) + if platform.system() == "Windows": + # https://www.jhanley.com/google-cloud-application-default-credentials/ + default_creds_path = os.path.join( + os.environ["APPDATA"], "gcloud/application_default_credentials.json" + ) + else: + default_creds_path = os.path.join( + os.environ["HOME"], ".config/gcloud/application_default_credentials.json" + ) + + if os.path.exists(default_creds_path): + with open(default_creds_path) as f: + return json.load(f) + return {} + + +def _create_access_token_request(creds: Dict[str, Any], scopes: List[str]) -> Request: + if "private_key" in creds: + # looks like GCS does not support the no-oauth flow https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth + return _create_token_request(creds["client_email"], creds["private_key"], scopes) + elif "refresh_token" in creds: + return _refresh_access_token_request( + refresh_token=creds["refresh_token"], + client_id=creds["client_id"], + client_secret=creds["client_secret"], + ) + else: + raise Error("Credentials not recognized") + + +def build_url(template: str, **data: str) -> str: + return common.build_url(GCP_BASE_URL, template, **data) + + +def create_api_request(req: Request, auth: Tuple[str, str]) -> Request: + if req.headers is None: + headers = {} + else: + headers = dict(req.headers).copy() + + if req.params is None: + params = {} + else: + params = dict(req.params).copy() + + kind, token = auth + if kind == OAUTH_TOKEN: + headers["Authorization"] = f"Bearer {token}" + elif kind == ANONYMOUS: + pass + else: + raise Error(f"unrecognized auth kind `{kind}`") + + data = req.data + if data is not None and isinstance(data, dict): + data = json.dumps(data).encode("utf8") + assert "Content-Type" not in headers + headers["Content-Type"] = "application/json" + return Request( + method=req.method, + url=req.url, + params=params, + headers=headers, + data=data, + preload_content=req.preload_content, + success_codes=tuple(req.success_codes), + retry_codes=tuple(req.retry_codes), + ) + + +def generate_signed_url( + bucket: str, + name: str, + expiration: float, + method: str = "GET", + params: Optional[Mapping[str, str]] = None, + headers: Optional[Mapping[str, str]] = None, +) -> Tuple[str, Optional[float]]: + if params is None: + p = {} + else: + p = dict(params).copy() + + if headers is None: + h = {} + else: + h = dict(headers).copy() + + # https://cloud.google.com/storage/docs/access-control/signing-urls-manually + creds = _load_credentials() + if "private_key" not in creds: + raise Error( + "Private key not found in credentials. Please set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to a JSON key for a service account to use this call" + ) + + if expiration > MAX_EXPIRATION: + raise Error(f"Expiration can't be longer than {MAX_EXPIRATION} seconds.") + + escaped_object_name = urllib.parse.quote(name, safe="") + canonical_uri = f"/{bucket}/{escaped_object_name}" + + datetime_now = datetime.datetime.now(tz=datetime.timezone.utc) + request_timestamp = datetime_now.strftime("%Y%m%dT%H%M%SZ") + datestamp = datetime_now.strftime("%Y%m%d") + + credential_scope = f"{datestamp}/auto/storage/goog4_request" + credential = f"{creds['client_email']}/{credential_scope}" + h["host"] = "storage.googleapis.com" + + canonical_headers = "" + ordered_headers = sorted(h.items()) + for k, v in ordered_headers: + lower_k = str(k).lower() + strip_v = str(v).lower() + canonical_headers += f"{lower_k}:{strip_v}\n" + + signed_headers_parts = [] + for k, _ in ordered_headers: + lower_k = str(k).lower() + signed_headers_parts.append(lower_k) + signed_headers = ";".join(signed_headers_parts) + + p["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256" + p["X-Goog-Credential"] = credential + p["X-Goog-Date"] = request_timestamp + p["X-Goog-Expires"] = str(expiration) + p["X-Goog-SignedHeaders"] = signed_headers + + canonical_query_string_parts = [] + ordered_params = sorted(p.items()) + for k, v in ordered_params: + encoded_k = urllib.parse.quote(str(k), safe="") + encoded_v = urllib.parse.quote(str(v), safe="") + canonical_query_string_parts.append(f"{encoded_k}={encoded_v}") + canonical_query_string = "&".join(canonical_query_string_parts) + + canonical_request = "\n".join( + [ + method, + canonical_uri, + canonical_query_string, + canonical_headers, + signed_headers, + "UNSIGNED-PAYLOAD", + ] + ) + + canonical_request_hash = hashlib.sha256(canonical_request.encode()).hexdigest() + + string_to_sign = "\n".join( + ["GOOG4-RSA-SHA256", request_timestamp, credential_scope, canonical_request_hash] + ) + + signature = binascii.hexlify(_sign(creds["private_key"], string_to_sign.encode("utf8"))).decode( + "utf8" + ) + host_name = "https://storage.googleapis.com" + signed_url = f"{host_name}{canonical_uri}?{canonical_query_string}&X-Goog-Signature={signature}" + return signed_url, expiration + + +def isdir(conf: Config, path: str) -> bool: + if not path.endswith("/"): + path += "/" + bucket, blob = split_path(path) + if blob == "": + req = Request( + url=build_url("/storage/v1/b/{bucket}", bucket=bucket), + method="GET", + success_codes=(200, 404), + ) + resp = execute_api_request(conf, req) + return resp.status == 200 + else: + req = Request( + url=build_url("/storage/v1/b/{bucket}/o", bucket=bucket), + method="GET", + params=dict(prefix=blob, delimiter="/", maxResults="1"), + success_codes=(200, 404), + ) + resp = execute_api_request(conf, req) + if resp.status == 404: + return False + result = json.loads(resp.data) + return "items" in result or "prefixes" in result + + +def mkdirfile(conf: Config, path: str) -> None: + if not path.endswith("/"): + path += "/" + bucket, blob = split_path(path) + req = Request( + url=build_url("/upload/storage/v1/b/{bucket}/o", bucket=bucket), + method="POST", + params=dict(uploadType="media", name=blob), + success_codes=(200, 400), + ) + resp = execute_api_request(conf, req) + if resp.status == 400: + raise Error(f"Unable to create directory, bucket does not exist: '{path}'") + + +def split_path(path: str) -> Tuple[str, str]: + if not path.startswith("gs://"): + raise Error(f"Invalid path: '{path}'") + path = path[len("gs://") :] + bucket, _, obj = path.partition("/") + if bucket == "": + raise Error(f"Invalid path: '{path}'") + return bucket, obj + + +def combine_path(bucket: str, obj: str) -> str: + return f"gs://{bucket}/{obj}" + + +def get_md5(metadata: Mapping[str, Any]) -> Optional[str]: + if "md5Hash" in metadata: + return base64.b64decode(metadata["md5Hash"]).hex() + + if "metadata" in metadata and "md5" in metadata["metadata"]: + # fallback to our custom hash if this is a composite object that is lacking the md5Hash field + return metadata["metadata"]["md5"] + + return None + + +def _parse_timestamp(text: str) -> float: + return datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f%z").timestamp() + + +def make_stat(item: Mapping[str, Any]) -> Stat: + if "metadata" in item and "blobfile-mtime" in item["metadata"]: + mtime = float(item["metadata"]["blobfile-mtime"]) + else: + mtime = _parse_timestamp(item["updated"]) + return Stat( + size=int(item["size"]), + mtime=mtime, + ctime=_parse_timestamp(item["timeCreated"]), + md5=get_md5(item), + version=item["generation"], + ) + + +def _get_access_token(conf: Config, key: Any) -> Tuple[Any, float]: + if os.environ.get("BLOBFILE_FORCE_GOOGLE_ANONYMOUS_AUTH", "0") == "1": + return (ANONYMOUS, ""), float("inf") + + now = time.time() + + # https://github.com/googleapis/google-auth-library-java/blob/master/README.md#application-default-credentials + creds = _load_credentials() + if len(creds) > 0: + + def build_req() -> Request: + req = _create_access_token_request( + creds=creds, scopes=["https://www.googleapis.com/auth/devstorage.full_control"] + ) + req.success_codes = (200, 400) + return req + + resp = common.execute_request(conf, build_req) + result = json.loads(resp.data) + if resp.status == 400: + error = result["error"] + description = result.get("error_description", "") + msg = f"Error with google credentials: [{error}] {description}" + if error == "invalid_grant": + if description.startswith("Invalid JWT:"): + msg += "\nPlease verify that your system clock is correct." + elif description == "Bad Request": + msg += "\nYour credentials may be expired, please run the following commands: `gcloud auth application-default revoke` (this may fail but ignore the error) then `gcloud auth application-default login`" + raise Error(msg) + assert resp.status == 200 + return (OAUTH_TOKEN, result["access_token"]), now + float(result["expires_in"]) + elif os.environ.get("NO_GCE_CHECK", "false").lower() != "true" and _is_gce_instance(): + # see if the metadata server has a token for us + def build_req() -> Request: + return Request( + method="GET", + url="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token", + headers={"Metadata-Flavor": "Google"}, + ) + + resp = common.execute_request(conf, build_req) + result = json.loads(resp.data) + return (OAUTH_TOKEN, result["access_token"]), now + float(result["expires_in"]) + else: + return (ANONYMOUS, ""), float("inf") + + +def execute_api_request(conf: Config, req: Request) -> "urllib3.BaseHTTPResponse": + def build_req() -> Request: + return create_api_request(req, auth=access_token_manager.get_token(conf, key="")) + + return common.execute_request(conf, build_req) + + +class StreamingReadFile(BaseStreamingReadFile): + def __init__(self, conf: Config, path: str, size: Optional[int]) -> None: + if size is None: + st = maybe_stat(conf, path) + if st is None: + raise FileNotFoundError(f"No such file or bucket: '{path}'") + size = st.size + super().__init__(conf=conf, path=path, size=size) + + def _request_chunk( + self, streaming: bool, start: int, end: Optional[int] = None + ) -> "urllib3.BaseHTTPResponse": + bucket, name = split_path(self._path) + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{name}", bucket=bucket, name=name), + method="GET", + params=dict(alt="media"), + headers={"Range": common.calc_range(start=start, end=end)}, + success_codes=(206, 416), + # if we are streaming the data, make + # sure we don't preload it + preload_content=not streaming, + ) + return execute_api_request(self._conf, req) + + +class StreamingWriteFile(BaseStreamingWriteFile): + def __init__(self, conf: Config, path: str) -> None: + bucket, name = split_path(path) + req = Request( + url=build_url("/upload/storage/v1/b/{bucket}/o?uploadType=resumable", bucket=bucket), + method="POST", + data=dict(name=name), + success_codes=(200, 400, 404), + ) + resp = execute_api_request(conf, req) + if resp.status in (400, 404): + raise FileNotFoundError(f"No such file or bucket: '{path}'") + self._upload_url = resp.headers["Location"] + # https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload + assert conf.google_write_chunk_size % (256 * 1024) == 0 + super().__init__(conf=conf, chunk_size=conf.google_write_chunk_size) + + def _upload_chunk(self, chunk: memoryview, finalize: bool) -> None: + offset = self._offset + + if len(chunk) == 0 and finalize: + self._upload_piece(offset, chunk, finalize) + return + + start = 0 + while start < len(chunk): + end = start + self._conf.google_write_chunk_size + last_piece = end >= len(chunk) + piece = chunk[start:end] + self._upload_piece(offset, piece, finalize and last_piece) + start = end + offset += len(piece) + + def _upload_piece(self, offset: int, piece: memoryview, finalize: bool) -> None: + start = offset + end = offset + len(piece) - 1 + + total_size = "*" + if finalize: + total_size = offset + len(piece) + + headers = { + "Content-Type": "application/octet-stream", + "Content-Range": f"bytes {start}-{end}/{total_size}", + } + if len(piece) == 0 and finalize: + # this is not mentioned in the docs but appears to be allowed + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range + headers["Content-Range"] = f"bytes */{total_size}" + + req = Request( + url=self._upload_url, + data=piece, + headers=headers, + method="PUT", + success_codes=(200, 201) if finalize else (308,), + ) + + try: + execute_api_request(self._conf, req) + except RequestFailure as e: + # https://cloud.google.com/storage/docs/resumable-uploads#practices + if e.response_status in (404, 410): + raise RestartableStreamingWriteFailure( + message=e.message, + request_string=e.request_string, + response_status=e.response_status, + error=e.error, + error_description=e.error_description, + ) + else: + raise + + +def maybe_stat(conf: Config, path: str) -> Optional[Stat]: + bucket, blob = split_path(path) + if blob == "": + return None + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob), + method="GET", + success_codes=(200, 404), + ) + resp = execute_api_request(conf, req) + if resp.status != 200: + return None + return make_stat(json.loads(resp.data)) + + +def remove(conf: Config, path: str) -> bool: + bucket, blob = split_path(path) + if blob == "": + raise FileNotFoundError(f"The system cannot find the path specified: '{path}'") + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob), + method="DELETE", + success_codes=(204, 404), + ) + resp = execute_api_request(conf, req) + return resp.status == 204 + + +def maybe_update_md5(conf: Config, path: str, generation: str, hexdigest: str) -> bool: + bucket, blob = split_path(path) + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob), + method="PATCH", + params=dict(ifGenerationMatch=generation), + # it looks like we can't set the underlying md5Hash, only the metadata fields + data=dict(metadata={"md5": hexdigest}), + success_codes=(200, 404, 412), + ) + + resp = execute_api_request(conf, req) + return resp.status == 200 + + +def _upload_part(conf: Config, path: str, start: int, size: int, dst: str) -> str: + bucket, blob = split_path(dst) + req = Request( + url=build_url("/upload/storage/v1/b/{bucket}/o", bucket=bucket), + method="POST", + params=dict(uploadType="media", name=blob), + data=FileBody(path, start=start, end=start + size), + success_codes=(200,), + ) + resp = execute_api_request(conf, req) + metadata = json.loads(resp.data) + return metadata["generation"] + + +def _delete_part(conf: Config, bucket: str, name: str) -> None: + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=name), + method="DELETE", + success_codes=(204, 404), + ) + execute_api_request(conf, req) + + +def parallel_upload( + conf: Config, executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool +) -> Optional[str]: + with open(src, "rb") as f: + md5_digest = common.block_md5(f) + + hexdigest = binascii.hexlify(md5_digest).decode("utf8") + + s = os.stat(src) + if s.st_size == 0: + # write an empty file, the normal upload requires at least one part + with StreamingWriteFile(conf, dst) as f: + pass + return hexdigest if return_md5 else None + + dstbucket, dstname = split_path(dst) + source_objects = [] + object_names = [] + max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1) + part_size = max(math.ceil(s.st_size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE) + i = 0 + start = 0 + futures = [] + while start < s.st_size: + suffix = f".part.{i}" + future = executor.submit( + _upload_part, conf, src, start, min(part_size, s.st_size - start), dst + suffix + ) + futures.append(future) + object_names.append(dstname + suffix) + i += 1 + start += part_size + for name, future in zip(object_names, futures): + generation = future.result() + source_objects.append( + { + "name": name, + "generation": generation, + "objectPreconditions": {"ifGenerationMatch": generation}, + } + ) + + req = Request( + url=build_url( + "/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose", + destinationBucket=dstbucket, + destinationObject=dstname, + ), + method="POST", + data={"sourceObjects": source_objects}, + success_codes=(200,), + ) + resp = execute_api_request(conf, req) + metadata = json.loads(resp.data) + maybe_update_md5(conf, dst, metadata["generation"], hexdigest) + + # delete parts in parallel + delete_futures = [] + for name in object_names: + future = executor.submit(_delete_part, conf, dstbucket, name) + delete_futures.append(future) + for future in delete_futures: + future.result() + + return hexdigest if return_md5 else None + + +def _create_page_iterator( + conf: Config, url: str, method: str, params: Mapping[str, str] +) -> Iterator[Dict[str, Any]]: + p = dict(params).copy() + + while True: + req = Request(url=url, method=method, params=p, success_codes=(200, 404)) + resp = execute_api_request(conf, req) + if resp.status == 404: + return + result = json.loads(resp.data) + yield result + if "nextPageToken" not in result: + break + p["pageToken"] = result["nextPageToken"] + + +def list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]: + params = {} + if delimiter is not None: + params["delimiter"] = delimiter + + bucket, prefix = split_path(path) + it = _create_page_iterator( + conf=conf, + url=build_url("/storage/v1/b/{bucket}/o", bucket=bucket), + method="GET", + params=dict(prefix=prefix, **params), + ) + for result in it: + yield from _get_entries(bucket, result) + + +def _get_entries(bucket: str, result: Mapping[str, Any]) -> Iterator[DirEntry]: + if "prefixes" in result: + for p in result["prefixes"]: + path = combine_path(bucket, p) + yield entry_from_dirpath(path) + if "items" in result: + for item in result["items"]: + path = combine_path(bucket, item["name"]) + if item["name"].endswith("/"): + yield entry_from_dirpath(path) + else: + yield entry_from_path_stat(path, make_stat(item)) + + +def entry_from_dirpath(path: str) -> DirEntry: + if path.endswith("/"): + path = path[:-1] + _, obj = split_path(path) + name = obj.split("/")[-1] + return DirEntry(name=name, path=path, is_dir=True, is_file=False, stat=None) + + +def entry_from_path_stat(path: str, stat: Stat) -> DirEntry: + assert not path.endswith("/") + _, obj = split_path(path) + name = obj.split("/")[-1] + return DirEntry(name=name, path=path, is_dir=False, is_file=True, stat=stat) + + +def get_url(conf: Config, path: str) -> Tuple[str, Optional[float]]: + bucket, blob = split_path(path) + return generate_signed_url(bucket, blob, expiration=MAX_EXPIRATION) + + +def set_mtime(conf: Config, path: str, mtime: float, version: Optional[str] = None) -> bool: + bucket, blob = split_path(path) + params = None + if version is not None: + params = dict(ifGenerationMatch=version) + req = Request( + url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob), + method="PATCH", + params=params, + data=dict(metadata={"blobfile-mtime": str(mtime)}), + success_codes=(200, 404, 412), + ) + resp = execute_api_request(conf, req) + if resp.status == 404: + raise FileNotFoundError(f"No such file: '{path}'") + return resp.status == 200 + + +def dirname(conf: Config, path: str) -> str: + bucket, obj = split_path(path) + obj = strip_slashes(obj) + if "/" in obj: + obj = "/".join(obj.split("/")[:-1]) + return combine_path(bucket, obj) + else: + return combine_path(bucket, "")[:-1] + + +def remote_copy(conf: Config, src: str, dst: str, return_md5: bool) -> Optional[str]: + srcbucket, srcname = split_path(src) + dstbucket, dstname = split_path(dst) + params = {} + while True: + req = Request( + url=build_url( + "/storage/v1/b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}", + sourceBucket=srcbucket, + sourceObject=srcname, + destinationBucket=dstbucket, + destinationObject=dstname, + ), + method="POST", + params=params, + success_codes=(200, 404), + ) + resp = execute_api_request(conf, req) + if resp.status == 404: + raise FileNotFoundError(f"Source file not found: '{src}'") + result = json.loads(resp.data) + if result["done"]: + if return_md5: + return get_md5(result["resource"]) + else: + return + params["rewriteToken"] = result["rewriteToken"] + + +def join_paths(conf: Config, a: str, b: str) -> str: + if not a.endswith("/"): + a += "/" + + bucket, obj = split_path(a) + obj = path_join(obj, b) + if obj.startswith("/"): + obj = obj[1:] + return combine_path(bucket, obj) + + +access_token_manager = TokenManager(_get_access_token, "gcp") diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_ops.py b/videollama2/lib/python3.10/site-packages/blobfile/_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..dafee1465a72d25ef7281d0a2ad52abf11a125f5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_ops.py @@ -0,0 +1,401 @@ +# https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime +from __future__ import annotations + +import concurrent.futures +from typing import ( + BinaryIO, + Callable, + Iterator, + Literal, + Optional, + Sequence, + TextIO, + Tuple, + overload, +) + +import urllib3 + +from blobfile._common import DirEntry, RemoteOrLocalPath, Stat +from blobfile._context import ( + DEFAULT_AZURE_WRITE_CHUNK_SIZE, + DEFAULT_BUFFER_SIZE, + DEFAULT_CONNECT_TIMEOUT, + DEFAULT_CONNECTION_POOL_MAX_SIZE, + DEFAULT_GOOGLE_WRITE_CHUNK_SIZE, + DEFAULT_MAX_CONNECTION_POOL_COUNT, + DEFAULT_READ_TIMEOUT, + DEFAULT_RETRY_COMMON_LOG_THRESHOLD, + DEFAULT_RETRY_LOG_THRESHOLD, + create_context, + default_log_fn, +) + +default_context = create_context() + + +def configure( + *, + log_callback: Callable[[str], None] = default_log_fn, + connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE, + max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT, + # https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs + # the chunk size determines the maximum size of an individual blob + azure_write_chunk_size: int = DEFAULT_AZURE_WRITE_CHUNK_SIZE, + google_write_chunk_size: int = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE, + retry_log_threshold: int = DEFAULT_RETRY_LOG_THRESHOLD, + retry_common_log_threshold: int = DEFAULT_RETRY_COMMON_LOG_THRESHOLD, + retry_limit: Optional[int] = None, + connect_timeout: Optional[int] = DEFAULT_CONNECT_TIMEOUT, + read_timeout: Optional[int] = DEFAULT_READ_TIMEOUT, + output_az_paths: bool = True, + use_azure_storage_account_key_fallback: bool = False, + get_http_pool: Optional[Callable[[], urllib3.PoolManager]] = None, + use_streaming_read: bool = False, + default_buffer_size: int = DEFAULT_BUFFER_SIZE, + save_access_token_to_disk: bool = True, + multiprocessing_start_method: str = "spawn", +) -> None: + """ + log_callback: a log callback function `log(msg: string)` to use instead of printing to stdout + connection_pool_max_size: the max size for each per-host connection pool + max_connection_pool_count: the maximum count of per-host connection pools + azure_write_chunk_size: the size of blocks to write to Azure Storage blobs, can be set to a maximum of 100MB + google_write_chunk_size: the size of blocks to write to Google Cloud Storage blobs in bytes, this only determines the unit of request retries + retry_log_threshold: set a retry count threshold above which to log failures to the log callback function + connect_timeout: the maximum amount of time (in seconds) to wait for a connection attempt to a server to succeed, set to None to wait forever + read_timeout: the maximum amount of time (in seconds) to wait between consecutive read operations for a response from the server, set to None to wait forever + output_az_paths: output `az://` paths instead of using the `https://` for azure + use_azure_storage_account_key_fallback: fallback to storage account keys for azure containers, having this enabled requires listing your subscriptions and may run into 429 errors if you hit the low azure quotas for subscription listing + get_http_pool: a function that returns a `urllib3.PoolManager` to be used for requests + use_streaming_read: if set to `True`, use a single read per file instead of reading a chunk at a time (not recommended for azure) + default_buffer_size: the default buffer size to use for reading files (and writing local files) + save_access_token_to_disk: set to `True` to save access tokens to disk so that other processes can read the access tokens to avoid the small amount of time it usually takes to get a token (if the token is still valid). + multiprocessing_start_method: the start method to use when creating processes for parallel work + """ + global default_context + default_context = create_context( + log_callback=log_callback, + connection_pool_max_size=connection_pool_max_size, + max_connection_pool_count=max_connection_pool_count, + azure_write_chunk_size=azure_write_chunk_size, + retry_log_threshold=retry_log_threshold, + retry_common_log_threshold=retry_common_log_threshold, + retry_limit=retry_limit, + google_write_chunk_size=google_write_chunk_size, + connect_timeout=connect_timeout, + read_timeout=read_timeout, + output_az_paths=output_az_paths, + use_azure_storage_account_key_fallback=use_azure_storage_account_key_fallback, + get_http_pool=get_http_pool, + use_streaming_read=use_streaming_read, + default_buffer_size=default_buffer_size, + save_access_token_to_disk=save_access_token_to_disk, + multiprocessing_start_method=multiprocessing_start_method, + ) + + +def copy( + src: RemoteOrLocalPath, + dst: RemoteOrLocalPath, + overwrite: bool = False, + parallel: bool = False, + parallel_executor: Optional[concurrent.futures.Executor] = None, + return_md5: bool = False, + dst_version: Optional[str] = None, +) -> Optional[str]: + """ + Copy a file from one path to another + + If both paths are on the same blob storage, this will perform a remote copy operation without downloading + the contents locally. + + If `overwrite` is `False` (the default), an exception will be raised if the destination + path exists. + + If `parallel` is `True`, use multiple processes to dowload or upload the file. For this to work, one path must be on blob storage and the other path must be local. This can be faster on cloud machines but is not in general guaranteed to be faster than using serial copy. The default is `False`. + + If `parallel_executor` is set to a `concurrent.futures.Executor` and `parallel` is set to `True`, the provided executor will be used instead of creating a new one for each call to `copy()`. + + If `return_md5` is set to `True`, an md5 will be calculated during the copy and returned if available, + or else None will be returned. + + If `dst_version` is set to a version string, the copy will fail if the destination path does not have this version (versions can be retrieved with `stat()`) + """ + return default_context.copy( + src=src, + dst=dst, + overwrite=overwrite, + parallel=parallel, + parallel_executor=parallel_executor, + return_md5=return_md5, + dst_version=dst_version, + ) + + +def exists(path: RemoteOrLocalPath) -> bool: + """ + Return true if that path exists (either as a file or a directory) + """ + return default_context.exists(path=path) + + +def basename(path: RemoteOrLocalPath) -> str: + """ + Get the filename component of the path + + For GCS, this is the part after the bucket + """ + return default_context.basename(path=path) + + +def glob(pattern: str, parallel: bool = False) -> Iterator[str]: + """ + Find files and directories matching a pattern. Supports * and ** + + For local paths, this function uses glob.glob() which has special handling for * and ** + that is not quite the same as remote paths. See https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames#different-behavior-for-dot-files-in-local-file-system_1 for more information. + + Globs can have confusing performance, see https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames#efficiency-consideration:-using-wildcards-over-many-objects for more information. + + You can set `parallel=True` to use multiple processes to perform the glob. It's likely + that the results will no longer be in order. + """ + return default_context.glob(pattern=pattern, parallel=parallel) + + +def scanglob( + pattern: str, parallel: bool = False, shard_prefix_length: int = 0 +) -> Iterator[DirEntry]: + """ + Same as `glob`, but returns `DirEntry` objects instead of strings + """ + return default_context.scanglob( + pattern=pattern, parallel=parallel, shard_prefix_length=shard_prefix_length + ) + + +def isdir(path: RemoteOrLocalPath) -> bool: + """ + Return true if a path is an existing directory + """ + return default_context.isdir(path=path) + + +def listdir(path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[str]: + """ + Returns an iterator of the contents of the directory at `path` + + If your filenames are uniformly distributed (like hashes) then you can use `shard_prefix_length` + to query them more quickly. `shard_prefix_length` will do multiple queries in parallel, + querying each possible prefix independently. + + Using `shard_prefix_length` will only consider prefixes that are not unusual characters + (mostly these are ascii values < 0x20) some of these could technically show up in a path. + """ + return default_context.listdir(path=path, shard_prefix_length=shard_prefix_length) + + +def scandir(path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[DirEntry]: + """ + Same as `listdir`, but returns `DirEntry` objects instead of strings + """ + return default_context.scandir(path=path, shard_prefix_length=shard_prefix_length) + + +def makedirs(path: RemoteOrLocalPath) -> None: + """ + Make any directories necessary to ensure that path is a directory + """ + return default_context.makedirs(path=path) + + +def remove(path: RemoteOrLocalPath) -> None: + """ + Remove a file at the given path + """ + return default_context.remove(path=path) + + +def rmdir(path: RemoteOrLocalPath) -> None: + """ + Remove an empty directory at the given path + """ + return default_context.rmdir(path=path) + + +def stat(path: RemoteOrLocalPath) -> Stat: + """ + Stat a file or object representing a directory, returns a Stat object + """ + return default_context.stat(path=path) + + +def set_mtime(path: RemoteOrLocalPath, mtime: float, version: Optional[str] = None) -> bool: + """ + Set the mtime for a path, returns True on success + + A version can be specified (as returned by `stat()`) to only update the mtime if the + version matches + """ + return default_context.set_mtime(path=path, mtime=mtime, version=version) + + +def rmtree( + path: RemoteOrLocalPath, + parallel: bool = False, + parallel_executor: Optional[concurrent.futures.Executor] = None, +) -> None: + """ + Delete a directory tree + """ + return default_context.rmtree(path=path, parallel=parallel, parallel_executor=parallel_executor) + + +def walk( + top: RemoteOrLocalPath, + topdown: bool = True, + onerror: Optional[Callable[[OSError], None]] = None, +) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]: + """ + Walk a directory tree in a similar manner to os.walk + """ + return default_context.walk(top=top, topdown=topdown, onerror=onerror) + + +def dirname(path: RemoteOrLocalPath) -> str: + """ + Get the directory name of the path + + On GCS, the root directory is gs:/// + On Azure Storage, the root directory is https://.blob.core.windows.net// + """ + return default_context.dirname(path=path) + + +def join(a: RemoteOrLocalPath, *args: str) -> str: + """ + Join file paths, if a path is an absolute path, it will replace the entire path component of previous paths + """ + return default_context.join(a, *args) + + +def get_url(path: RemoteOrLocalPath) -> Tuple[str, Optional[float]]: + """ + Get a URL for the given path that a browser could open + """ + return default_context.get_url(path=path) + + +def md5(path: RemoteOrLocalPath) -> str: + """ + Get the MD5 hash for a file in hexdigest format. + + For GCS this will look up the MD5 in the blob's metadata, unless it's a composite object, in which case + it must be calculated by downloading the file. + For Azure this can look up the MD5 if it's available, otherwise it must calculate it. + For local paths, this must always calculate the MD5. + """ + return default_context.md5(path=path) + + +def last_version_seen(file: TextIO | BinaryIO) -> Optional[str]: + """ + Get the last seen version of a file opened with `BlobFile` + """ + return default_context.last_version_seen(file=file) + + +def read_text(path: RemoteOrLocalPath) -> str: + """ + Read the contents of a file as text + """ + return default_context.read_text(path=path) + + +def read_bytes(path: RemoteOrLocalPath) -> bytes: + """ + Read the contents of a file as bytes + """ + return default_context.read_bytes(path=path) + + +def write_text(path: RemoteOrLocalPath, text: str) -> None: + """ + Write text to a file + """ + return default_context.write_text(path=path, text=text) + + +def write_bytes(path: RemoteOrLocalPath, data: bytes) -> None: + """ + Write bytes to a file + """ + return default_context.write_bytes(path=path, data=data) + + +@overload +def BlobFile( + path: RemoteOrLocalPath, + mode: Literal["rb", "wb", "ab"], + streaming: Optional[bool] = ..., + buffer_size: int = ..., + cache_dir: Optional[str] = ..., + file_size: Optional[int] = None, + version: Optional[str] = None, +) -> BinaryIO: + ... + + +@overload +def BlobFile( + path: RemoteOrLocalPath, + mode: Literal["r", "w", "a"] = ..., + streaming: Optional[bool] = ..., + buffer_size: int = ..., + cache_dir: Optional[str] = ..., + file_size: Optional[int] = None, + version: Optional[str] = None, +) -> TextIO: + ... + + +def BlobFile( + path: RemoteOrLocalPath, + mode: Literal["r", "rb", "w", "wb", "a", "ab"] = "r", + streaming: Optional[bool] = None, + buffer_size: Optional[int] = None, + cache_dir: Optional[str] = None, + file_size: Optional[int] = None, + version: Optional[str] = None, +): + """ + Open a local or remote file for reading or writing + + Args: + path local or remote path + mode: one of "r", "rb", "w", "wb", "a", "ab" indicating the mode to open the file in + streaming: the default for `streaming` is `True` when `mode` is in `"r", "rb"` and `False` when `mode` is in `"w", "wb", "a", "ab"`. + * `streaming=True`: + * Reading is done without downloading the entire remote file. + * Writing is done to the remote file directly, but only in chunks of a few MB in size. `flush()` will not cause an early write. + * Appending is not implemented. + * `streaming=False`: + * Reading is done by downloading the remote file to a local file during the constructor. + * Writing is done by uploading the file on `close()` or during destruction. + * Appending is done by downloading the file during construction and uploading on `close()` or during destruction. + buffer_size: number of bytes to buffer, this can potentially make reading more efficient. + cache_dir: a directory in which to cache files for reading, only valid if `streaming=False` and `mode` is in `"r", "rb"`. You are reponsible for cleaning up the cache directory. + + Returns: + A file-like object + """ + return default_context.BlobFile( + path=path, + mode=mode, + streaming=streaming, + buffer_size=buffer_size, + cache_dir=cache_dir, + file_size=file_size, + version=version, + ) diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_ops_test.py b/videollama2/lib/python3.10/site-packages/blobfile/_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fd25c2b60312c749cfcdcd11196b828f51c27de8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_ops_test.py @@ -0,0 +1,1675 @@ +# https://github.com/tensorflow/tensorflow/issues/27023 +import datetime +import warnings + +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=FutureWarning) + +import random +import string +import tempfile +import os +import contextlib +import json +import urllib.request +import hashlib +import time +import subprocess as sp +import multiprocessing as mp +import platform +import pickle +import zipfile +import re +import unittest.mock + +import pytest +import numpy as np + +import blobfile as bf +from blobfile import _ops as ops, _azure as azure, _common as common + +GCS_TEST_BUCKET = os.getenv("GCS_TEST_BUCKET", "csh-test-3") +AS_TEST_ACCOUNT = os.getenv("AS_TEST_ACCOUNT", "cshteststorage2") +AS_TEST_ACCOUNT2 = os.getenv("AS_TEST_ACCOUNT2", "cshteststorage3") +AS_TEST_CONTAINER = os.getenv("AS_TEST_CONTAINER", "testcontainer2") +AS_TEST_CONTAINER2 = os.getenv("AS_TEST_CONTAINER2", "testcontainer3") +AS_INVALID_ACCOUNT = f"{AS_TEST_ACCOUNT}-does-not-exist" +AS_EXTERNAL_ACCOUNT = "cshteststorage4" + +AZURE_VALID_CONTAINER = f"az://{AS_TEST_ACCOUNT}/{AS_TEST_CONTAINER}" +AZURE_INVALID_CONTAINER = f"az://{AS_TEST_ACCOUNT}/{AS_TEST_CONTAINER}-does-not-exist" +AZURE_INVALID_CONTAINER_NO_ACCOUNT = f"az://{AS_INVALID_ACCOUNT}/{AS_TEST_CONTAINER}" +GCS_VALID_BUCKET = f"gs://{GCS_TEST_BUCKET}" +GCS_INVALID_BUCKET = f"gs://{GCS_TEST_BUCKET}-does-not-exist" + +AZURE_PUBLIC_URL = ( + f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png" +) +AZURE_PUBLIC_URL_HEADER = b"\x89PNG" + + +@pytest.fixture(scope="session", autouse=True) +def setup_gcloud_auth(): + # only run this for our docker tests, this tells gcloud to use the credentials supplied by the + # test running script + if platform.system() == "Linux" and "GOOGLE_APPLICATION_CREDENTIALS" in os.environ: + sp.run( + [ + "gcloud", + "auth", + "activate-service-account", + f"--key-file={os.environ['GOOGLE_APPLICATION_CREDENTIALS']}", + ] + ) + yield + + +@contextlib.contextmanager +def chdir(path): + original_path = os.getcwd() + os.chdir(path) + yield + os.chdir(original_path) + + +@contextlib.contextmanager +def _get_temp_local_path(): + with tempfile.TemporaryDirectory() as tmpdir: + assert isinstance(tmpdir, str) + path = os.path.join(tmpdir, "file.name") + yield path + + +@contextlib.contextmanager +def _get_temp_gcs_path(): + try: + from tensorflow.io import gfile + except ImportError: + pytest.skip("tensorflow not installed") + + path = f"gs://{GCS_TEST_BUCKET}/" + "".join( + random.choice(string.ascii_lowercase) for i in range(16) + ) + gfile.mkdir(path) + yield path + "/file.name" + gfile.rmtree(path) + + +@contextlib.contextmanager +def _get_temp_as_path(account=AS_TEST_ACCOUNT, container=AS_TEST_CONTAINER): + random_id = "".join(random.choice(string.ascii_lowercase) for i in range(16)) + path = f"https://{account}.blob.core.windows.net/{container}/" + random_id + yield path + "/file.name" + cmd = [ + "az", + "storage", + "blob", + "delete-batch", + "--account-name", + account, + "--source", + container, + "--pattern", + f"{random_id}/*", + "--auth-mode", + "login", + ] + sp.run(cmd, check=True, shell=platform.system() == "Windows", timeout=30) + + +def _write_contents(path, contents): + if ".blob.core.windows.net" in path or path.startswith("az://"): + with tempfile.TemporaryDirectory() as tmpdir: + assert isinstance(tmpdir, str) + account, container, blob = azure.split_path(path) + filepath = os.path.join(tmpdir, "tmp") + with open(filepath, "wb") as f: + f.write(contents) + cmd = [ + "az", + "storage", + "blob", + "upload", + "--overwrite", + "--account-name", + account, + "--container-name", + container, + "--name", + blob, + "--file", + filepath, + "--auth-mode", + "login", + ] + sp.run( + cmd, + check=True, + shell=platform.system() == "Windows", + stdout=sp.DEVNULL, + stderr=sp.DEVNULL, + timeout=30, + ) + else: + try: + from tensorflow.io import gfile + except ImportError: + pytest.skip("tensorflow not installed") + + with gfile.GFile(path, "wb") as f: + f.write(contents) + + +def _read_contents(path): + if ".blob.core.windows.net" in path: + with tempfile.TemporaryDirectory() as tmpdir: + assert isinstance(tmpdir, str) + account, container, blob = azure.split_path(path) + filepath = os.path.join(tmpdir, "tmp") + cmd = [ + "az", + "storage", + "blob", + "download", + "--account-name", + account, + "--container-name", + container, + "--name", + blob, + "--file", + filepath, + "--auth-mode", + "login", + ] + sp.run( + cmd, + check=True, + shell=platform.system() == "Windows", + stdout=sp.DEVNULL, + stderr=sp.DEVNULL, + timeout=30, + ) + with open(filepath, "rb") as f: + return f.read() + else: + from tensorflow.io import gfile + + with gfile.GFile(path, "rb") as f: + return f.read() + + +def test_basename(): + testcases = [ + ("/", ""), + ("a/", ""), + ("a", "a"), + ("a/b", "b"), + ("", ""), + ("gs://a", ""), + ("gs://a/", ""), + ("gs://a/b/", ""), + ("gs://a/b", "b"), + ("gs://a/b/c/test.filename", "test.filename"), + ("https://a.blob.core.windows.net/b", ""), + ("https://a.blob.core.windows.net/b/", ""), + ("https://a.blob.core.windows.net/b/c/", ""), + ("https://a.blob.core.windows.net/b/c", "c"), + ("https://a.blob.core.windows.net/b/c/test.filename", "test.filename"), + ] + for input_, desired_output in testcases: + actual_output = bf.basename(input_) + assert desired_output == actual_output + + +def test_dirname(): + b = bf.create_context(output_az_paths=False) + testcases = [ + ("a", ""), + ("a/b", "a"), + ("a/b/c", "a/b"), + ("a/b/c/", "a/b/c"), + ("a/b/c/////", "a/b/c"), + ("", ""), + ("gs://a", "gs://a"), + ("gs://a/", "gs://a"), + ("gs://a/////", "gs://a"), + ("gs://a/b", "gs://a"), + ("gs://a/b/c/test.filename", "gs://a/b/c"), + ("gs://a/b/c/", "gs://a/b"), + ("gs://a/b/c/////", "gs://a/b"), + ("https://a.blob.core.windows.net/container", "https://a.blob.core.windows.net/container"), + ("https://a.blob.core.windows.net/container/", "https://a.blob.core.windows.net/container"), + ( + "https://a.blob.core.windows.net/container/////", + "https://a.blob.core.windows.net/container", + ), + ( + "https://a.blob.core.windows.net/container/b", + "https://a.blob.core.windows.net/container", + ), + ( + "https://a.blob.core.windows.net/container/b/c/test.filename", + "https://a.blob.core.windows.net/container/b/c", + ), + ( + "https://a.blob.core.windows.net/container/b/c/", + "https://a.blob.core.windows.net/container/b", + ), + ( + "https://a.blob.core.windows.net/container/b/c//////", + "https://a.blob.core.windows.net/container/b", + ), + ] + for input_, desired_output in testcases: + actual_output = b.dirname(input_) + assert desired_output == actual_output, f"{input_}" + + +def test_join(): + b = bf.create_context(output_az_paths=False) + testcases = [ + ("a", "b", "a/b"), + ("a/b", "c", "a/b/c"), + ("a/b/", "c", "a/b/c"), + ("a/b/", "c/", "a/b/c/"), + ("a/b/", "/c/", "/c/"), + ("", "", ""), + ("gs://a/b/c", "d0123456789-._~!$&'()*+,:=@;", "gs://a/b/c/d0123456789-._~!$&'()*+,:=@;"), + ("gs://a", "b", "gs://a/b"), + ("gs://a/b", "c", "gs://a/b/c"), + ("gs://a/b/", "c", "gs://a/b/c"), + ("gs://a/b/", "c/", "gs://a/b/c/"), + ("gs://a/b/", "/c/", "gs://a/c/"), + ("gs://a/b/", "../c", "gs://a/c"), + ("gs://a/b/", "../c/", "gs://a/c/"), + ("gs://a/b/", "../../c/", "gs://a/c/"), + ( + "https://a.blob.core.windows.net/container", + "b", + "https://a.blob.core.windows.net/container/b", + ), + ( + "https://a.blob.core.windows.net/container/b", + "c", + "https://a.blob.core.windows.net/container/b/c", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "c", + "https://a.blob.core.windows.net/container/b/c", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "c/", + "https://a.blob.core.windows.net/container/b/c/", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "/c/", + "https://a.blob.core.windows.net/container/c/", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "../c", + "https://a.blob.core.windows.net/container/c", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "../c/", + "https://a.blob.core.windows.net/container/c/", + ), + ( + "https://a.blob.core.windows.net/container/b/", + "../../c/", + "https://a.blob.core.windows.net/container/c/", + ), + ("gs://test/a/b", "c:d", "gs://test/a/b/c:d"), + ("gs://test/a/b", "c:d;", "gs://test/a/b/c:d;"), + ] + for input_a, input_b, desired_output in testcases: + actual_output = b.join(input_a, input_b) + assert desired_output == actual_output, f"{input_a} {input_b}" + # also make sure az:// urls work + if "blob.core.windows.net" in input_a: + az_input_a = _convert_https_to_az(input_a) + actual_output = b.join(az_input_a, input_b) + assert desired_output == actual_output, f"{az_input_a} {input_b}" + + +def _convert_https_to_az(path): + return path.replace("https://", "az://").replace(".blob.core.windows.net", "") + + +def _convert_az_to_https(path): + return re.sub(r"^az://(.*?)/", r"https://\1.blob.core.windows.net/", path) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_get_url(ctx): + contents = b"meow!" + with ctx() as path: + _write_contents(path, contents) + url, _ = bf.get_url(path) + assert urllib.request.urlopen(url).read() == contents + + +def test_azure_public_get_url(): + contents = urllib.request.urlopen(AZURE_PUBLIC_URL).read() + assert contents.startswith(AZURE_PUBLIC_URL_HEADER) + url, _ = bf.get_url(AZURE_PUBLIC_URL) + assert urllib.request.urlopen(url).read() == contents + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +@pytest.mark.parametrize("streaming", [True, False]) +def test_read_write(ctx, streaming): + contents = b"meow!\npurr\n" + with ctx() as path: + path = bf.join(path, "a folder", "a.file") + bf.makedirs(bf.dirname(path)) + with bf.BlobFile(path, "wb", streaming=streaming) as w: + w.write(contents) + assert w.tell() == len(contents) + with bf.BlobFile(path, "rb", streaming=streaming) as r: + assert r.read() == contents + assert r.tell() == len(contents) + with bf.BlobFile(path, "rb", streaming=streaming) as r: + lines = list(r) + assert b"".join(lines) == contents + + +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_zipfile(ctx): + contents = b"meow!\npurr\n" + with ctx() as path: + with bf.BlobFile(path, "wb", streaming=True) as f: + with zipfile.ZipFile(f, "w") as zf: + with zf.open("eggs.txt", "w") as myfile: + myfile.write(contents) + + with bf.BlobFile(path, "rb", streaming=True) as f: + with zipfile.ZipFile(f, "r") as zf: + with zf.open("eggs.txt", "r") as myfile: + assert myfile.read() == contents + + +def test_az_path(): + contents = b"meow!\npurr\n" + with _get_temp_as_path() as path: + path = _convert_https_to_az(path) + path = bf.join(path, "a folder", "a.file") + path = _convert_https_to_az(path) + bf.makedirs(_convert_https_to_az(bf.dirname(path))) + with bf.BlobFile(path, "wb") as w: + w.write(contents) + with bf.BlobFile(path, "rb") as r: + assert r.read() == contents + with bf.BlobFile(path, "rb") as r: + lines = list(r) + assert b"".join(lines) == contents + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_append(ctx): + contents = b"meow!\n" + additional_contents = b"purr\n" + with ctx() as path: + with bf.BlobFile(path, "ab", streaming=False) as w: + w.write(contents) + with bf.BlobFile(path, "ab", streaming=False) as w: + w.write(additional_contents) + with bf.BlobFile(path, "rb") as r: + assert r.read() == contents + additional_contents + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_stat(ctx): + contents = b"meow!" + with ctx() as path: + _write_contents(path, contents) + s = bf.stat(path) + assert s.size == len(contents) + assert abs(time.time() - s.mtime) <= 30 + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_set_mtime(ctx): + contents = b"meow!" + with ctx() as path: + _write_contents(path, contents) + s = bf.stat(path) + assert abs(time.time() - s.mtime) <= 30 + new_mtime = 1 + assert bf.set_mtime(path, new_mtime) + assert bf.stat(path).mtime == new_mtime + + +@pytest.mark.parametrize("ctx", [_get_temp_as_path]) +def test_azure_metadata(ctx): + # make sure metadata is preserved when opening a file for writing + # which clears uncommitted blocks + contents = b"meow!" + + with ctx() as path: + with bf.BlobFile(path, "wb") as f: + f.write(contents) + + bf.set_mtime(path, 1) + time.sleep(5) + with bf.BlobFile(path, "wb", streaming=True) as f: + st = bf.stat(path) + assert st.mtime == 1 + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_remove(ctx): + contents = b"meow!" + with ctx() as path: + _write_contents(path, contents) + assert bf.exists(path) + bf.remove(path) + assert not bf.exists(path) + + +@pytest.mark.parametrize( + # don't test local path because that has slightly different behavior + "ctx", + [_get_temp_gcs_path, _get_temp_as_path], +) +def test_rmdir(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + # this is an error for a local path but not for a blob path + bf.rmdir(bf.join(dirpath, "fakedirname")) + new_dirpath = bf.join(dirpath, "dirname") + bf.makedirs(new_dirpath) + assert bf.exists(new_dirpath) + bf.rmdir(new_dirpath) + assert not bf.exists(new_dirpath) + + # double delete is fine + bf.rmdir(new_dirpath) + + # implicit dir + new_filepath = bf.join(dirpath, "dirname", "name") + _write_contents(new_filepath, contents) + with pytest.raises(OSError): + # not empty dir + bf.rmdir(new_dirpath) + bf.remove(new_filepath) + bf.rmdir(new_dirpath) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_makedirs(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.join(path, "x", "x", "x") + bf.makedirs(dirpath) + assert bf.exists(dirpath) + _write_contents(bf.join(dirpath, "testfile"), contents) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_isdir(ctx): + contents = b"meow!" + with ctx() as path: + assert not bf.isdir(path) + _write_contents(path, contents) + assert not bf.isdir(path) + + dirpath = path + ".dir" + bf.makedirs(dirpath) + assert bf.isdir(dirpath) + assert not bf.isdir(dirpath[:-1]) + + filepath = bf.join(path + ".otherdir", "subdir", "file.name") + if "://" not in path: + # implicit directory + bf.makedirs(bf.dirname(filepath)) + dirpath = bf.dirname(bf.dirname(filepath)) + _write_contents(filepath, contents) + assert bf.isdir(dirpath) + assert not bf.isdir(dirpath[:-1]) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_listdir(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + bf.makedirs(dirpath) + a_path = bf.join(dirpath, "a") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + b_path = bf.join(dirpath, "b") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + bf.makedirs(bf.join(dirpath, "c")) + expected = ["a", "b", "c"] + assert sorted(list(bf.listdir(dirpath))) == expected + dirpath = _convert_https_to_az(dirpath) + assert sorted(list(bf.listdir(dirpath))) == expected + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_scandir(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + a_path = bf.join(dirpath, "a") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + b_path = bf.join(dirpath, "b") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + bf.makedirs(bf.join(dirpath, "c")) + entries = sorted(list(bf.scandir(dirpath))) + assert [e.name for e in entries] == ["a", "b", "c"] + assert [e.path for e in entries] == [bf.join(dirpath, name) for name in ["a", "b", "c"]] + assert [e.is_dir for e in entries] == [False, False, True] + assert [e.is_file for e in entries] == [True, True, False] + assert entries[0].stat.size == len(contents) + assert entries[1].stat.size == len(contents) + assert entries[2].stat is None + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_listdir_sharded(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + with bf.BlobFile(bf.join(dirpath, "a"), "wb") as w: + w.write(contents) + with bf.BlobFile(bf.join(dirpath, "aa"), "wb") as w: + w.write(contents) + with bf.BlobFile(bf.join(dirpath, "b"), "wb") as w: + w.write(contents) + with bf.BlobFile(bf.join(dirpath, "ca"), "wb") as w: + w.write(contents) + bf.makedirs(bf.join(dirpath, "c")) + with bf.BlobFile(bf.join(dirpath, "c/a"), "wb") as w: + w.write(contents) + # this should also test shard_prefix_length=2 but that takes too long + assert sorted(list(bf.listdir(dirpath, shard_prefix_length=1))) == [ + "a", + "aa", + "b", + "c", + "ca", + ] + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +@pytest.mark.parametrize("topdown", [False, True]) +def test_walk(ctx, topdown): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + a_path = bf.join(dirpath, "a") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + bf.makedirs(bf.join(dirpath, "c/d")) + b_path = bf.join(dirpath, "c/d/b") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + expected = [ + (dirpath, ["c"], ["a"]), + (bf.join(dirpath, "c"), ["d"], []), + (bf.join(dirpath, "c", "d"), [], ["b"]), + ] + if not topdown: + expected = list(reversed(expected)) + assert list(bf.walk(dirpath, topdown=topdown)) == expected + dirpath = _convert_https_to_az(dirpath) + assert list(bf.walk(dirpath, topdown=topdown)) == expected + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path]) +def test_local_glob(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + a_path = bf.join(dirpath, "ab") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + b_path = bf.join(dirpath, "bb") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + + def assert_listing_equal(path, desired): + desired = sorted([bf.join(dirpath, p) for p in desired]) + actual = sorted(list(bf.glob(path))) + assert actual == desired, f"{actual} != {desired}" + + # example patterns (didn't add tests for all these) + # /a/b*c + # /a/*b + # /a/c* + # /a/* + # /a/*/ + # /a/b*c/d + # a/b*c + # a/*b + # a/c* + # a/b*c/d + # b*c + # *c + # b* + # * + # */ + # */a + with chdir(dirpath): + assert_listing_equal("ab", ["ab"]) + assert_listing_equal("*b", ["ab", "bb"]) + assert_listing_equal("a*", ["ab"]) + assert_listing_equal("ab*", ["ab"]) + assert_listing_equal("*", ["ab", "bb"]) + assert_listing_equal("bb", ["bb"]) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +@pytest.mark.parametrize("parallel", [False, True]) +def test_glob(ctx, parallel): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + a_path = bf.join(dirpath, "ab") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + b_path = bf.join(dirpath, "bb") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + + def assert_listing_equal(path, desired): + desired = sorted([bf.join(dirpath, p) for p in desired]) + actual = sorted(list(bf.glob(path, parallel=parallel))) + assert actual == desired, f"{actual} != {desired}" + + assert_listing_equal(bf.join(dirpath, "*b"), ["ab", "bb"]) + assert_listing_equal(bf.join(dirpath, "a*"), ["ab"]) + assert_listing_equal(bf.join(dirpath, "ab*"), ["ab"]) + assert_listing_equal(bf.join(dirpath, "*"), ["ab", "bb"]) + assert_listing_equal(bf.join(dirpath, "bb"), ["bb"]) + + path = bf.join(dirpath, "test.txt") + with bf.BlobFile(path, "wb") as w: + w.write(contents) + path = bf.join(dirpath, "subdir", "test.txt") + bf.makedirs(bf.dirname(path)) + with bf.BlobFile(path, "wb") as f: + f.write(contents) + path = bf.join(dirpath, "subdir", "subsubdir", "test.txt") + if "://" not in path: + # implicit directory + bf.makedirs(bf.dirname(path)) + with bf.BlobFile(path, "wb") as f: + f.write(contents) + + assert_listing_equal(bf.join(dirpath, "*/test.txt"), ["subdir/test.txt"]) + assert_listing_equal(bf.join(dirpath, "*/*.txt"), ["subdir/test.txt"]) + assert_listing_equal( + bf.join(dirpath, "**.txt"), ["test.txt", "subdir/test.txt", "subdir/subsubdir/test.txt"] + ) + assert_listing_equal( + bf.join(dirpath, "sub**.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"] + ) + assert_listing_equal( + bf.join(dirpath, "subdir/**.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"] + ) + assert_listing_equal( + bf.join(dirpath, "**/*.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"] + ) + + assert_listing_equal(bf.join(dirpath, "*/test"), []) + assert_listing_equal(bf.join(dirpath, "subdir/test.txt"), ["subdir/test.txt"]) + + # directories + assert_listing_equal(bf.join(dirpath, "*"), ["ab", "bb", "subdir", "test.txt"]) + assert_listing_equal(bf.join(dirpath, "subdir"), ["subdir"]) + assert_listing_equal(bf.join(dirpath, "subdir/"), ["subdir"]) + assert_listing_equal(bf.join(dirpath, "*/"), ["subdir"]) + assert_listing_equal(bf.join(dirpath, "*dir"), ["subdir"]) + assert_listing_equal(bf.join(dirpath, "subdir/*dir"), ["subdir/subsubdir"]) + assert_listing_equal(bf.join(dirpath, "subdir/*dir/"), ["subdir/subsubdir"]) + assert_listing_equal(bf.join(dirpath, "su*ir/*dir/"), ["subdir/subsubdir"]) + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_scanglob(ctx): + contents = b"meow!" + with ctx() as path: + dirpath = bf.dirname(path) + a_path = bf.join(dirpath, "ab") + with bf.BlobFile(a_path, "wb") as w: + w.write(contents) + b_path = bf.join(dirpath, "bb") + with bf.BlobFile(b_path, "wb") as w: + w.write(contents) + path = bf.join(dirpath, "test.txt") + with bf.BlobFile(path, "wb") as w: + w.write(contents) + path = bf.join(dirpath, "subdir", "test.txt") + bf.makedirs(bf.dirname(path)) + with bf.BlobFile(path, "wb") as f: + f.write(contents) + + entries = sorted(list(bf.scanglob(bf.join(dirpath, "*b*")))) + assert entries[0].name == "ab" and entries[0].is_file + assert entries[1].name == "bb" and entries[1].is_file + assert entries[2].name == "subdir" and entries[2].is_dir + + for shard_prefix_length in [0, 1]: + for pattern in ["*b", "b*", "**", "b**", "**t", "*b*"]: + normal_entries = sorted(list(bf.scanglob(bf.join(dirpath, pattern)))) + parallel_entries = sorted( + list( + bf.scanglob( + bf.join(dirpath, pattern), + parallel=True, + shard_prefix_length=shard_prefix_length, + ) + ) + ) + assert parallel_entries == normal_entries + + if "://" in path: + # ** behaves a bit differently on local paths, so don't check those + entries = sorted(list(bf.scanglob(bf.join(dirpath, "**")))) + assert entries[0].name == "ab" and entries[0].is_file + assert entries[1].name == "bb" and entries[1].is_file + assert entries[2].name == "subdir" and entries[2].is_dir + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +@pytest.mark.parametrize("parallel", [False, True]) +def test_rmtree(ctx, parallel): + contents = b"meow!" + with ctx() as path: + root = bf.dirname(path) + destroy_path = bf.join(root, "destroy") + bf.makedirs(destroy_path) + save_path = bf.join(root, "save") + bf.makedirs(save_path) + + # implicit dir + if "://" not in path: + bf.makedirs(bf.join(destroy_path, "adir")) + with bf.BlobFile(bf.join(destroy_path, "adir/b"), "wb") as w: + w.write(contents) + + # explicit dir + bf.makedirs(bf.join(destroy_path, "bdir")) + with bf.BlobFile(bf.join(destroy_path, "bdir/b"), "wb") as w: + w.write(contents) + + bf.makedirs(bf.join(save_path, "somedir")) + with bf.BlobFile(bf.join(save_path, "somefile"), "wb") as w: + w.write(contents) + + def assert_listing_equal(path, desired): + actual = list(bf.walk(path)) + # ordering of os walk is weird, only compare sorted order + assert sorted(actual) == sorted(desired), f"{actual} != {desired}" + + assert_listing_equal( + root, + [ + (root, ["destroy", "save"], []), + (destroy_path, ["adir", "bdir"], []), + (bf.join(destroy_path, "adir"), [], ["b"]), + (bf.join(destroy_path, "bdir"), [], ["b"]), + (save_path, ["somedir"], ["somefile"]), + (bf.join(save_path, "somedir"), [], []), + ], + ) + + bf.rmtree(destroy_path, parallel=parallel) + + assert_listing_equal( + root, + [ + (root, ["save"], []), + (save_path, ["somedir"], ["somefile"]), + (bf.join(save_path, "somedir"), [], []), + ], + ) + + +@pytest.mark.parametrize("parallel", [False, True]) +def test_copy(parallel): + for contents in [b"", b"meow!", b"meow!" * (2 * 2**20)]: + with _get_temp_local_path() as local_path1, _get_temp_local_path() as local_path2, _get_temp_local_path() as local_path3, _get_temp_gcs_path() as gcs_path1, _get_temp_gcs_path() as gcs_path2, _get_temp_as_path() as as_path1, _get_temp_as_path() as as_path2, _get_temp_as_path( + account=AS_TEST_ACCOUNT2, container=AS_TEST_CONTAINER2 + ) as as_path3, _get_temp_as_path() as as_path4: + with pytest.raises(FileNotFoundError): + bf.copy(gcs_path1, gcs_path2, parallel=parallel) + with pytest.raises(FileNotFoundError): + bf.copy(as_path1, as_path2, parallel=parallel) + + _write_contents(local_path1, contents) + + testcases = [ + (local_path1, local_path2), + (local_path1, gcs_path1), + (gcs_path1, gcs_path2), + (gcs_path2, as_path1), + (as_path1, as_path2), + (as_path2, as_path3), + (as_path3, local_path3), + (local_path3, as_path4), + ] + + for src, dst in testcases: + h = bf.copy(src, dst, return_md5=True, parallel=parallel) + assert h == hashlib.md5(contents).hexdigest() + assert _read_contents(dst) == contents + with pytest.raises(FileExistsError): + bf.copy(src, dst, parallel=parallel) + bf.copy(src, dst, overwrite=True, parallel=parallel) + assert _read_contents(dst) == contents + + +@pytest.mark.parametrize("parallel", [False, True]) +def test_copy_invalid(parallel): + for contents in [b"", b"meow!", b"meow!" * (2 * 2**20)]: + with _get_temp_local_path() as local_path, _get_temp_as_path() as as_path1, _get_temp_as_path() as as_path2: + invalid_container_as_path = _convert_az_to_https( + bf.join(AZURE_INVALID_CONTAINER, "file.bin") + ) + invalid_account_as_path = _convert_az_to_https( + bf.join(AZURE_INVALID_CONTAINER_NO_ACCOUNT, "file.bin") + ) + + _write_contents(local_path, contents) + bf.copy(local_path, as_path1, parallel=parallel) + with pytest.raises(FileNotFoundError, match=invalid_container_as_path): + bf.copy(local_path, invalid_container_as_path, parallel=parallel) + with pytest.raises(FileNotFoundError, match=invalid_account_as_path): + bf.copy(local_path, invalid_account_as_path, parallel=parallel) + + with pytest.raises(FileNotFoundError, match=invalid_container_as_path): + bf.copy(as_path1, invalid_container_as_path, parallel=parallel) + with pytest.raises(FileNotFoundError, match=invalid_account_as_path): + bf.copy(as_path1, invalid_account_as_path, parallel=parallel) + + with pytest.raises(FileNotFoundError, match=invalid_container_as_path): + bf.copy(invalid_container_as_path, as_path2, parallel=parallel) + + # this fails with a RequestFailure to get the sas token + # with pytest.raises(FileNotFoundError, match=invalid_account_as_path): + # bf.copy(invalid_account_as_path, as_path2, parallel=parallel) + + +# the tests already take awhile and this adds like a minute +@pytest.mark.slow +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_parallel_copy_large_file(ctx): + contents = b"meow!" * common.PARALLEL_COPY_MINIMUM_PART_SIZE + b"meow???" + with ctx() as remote_path: + with tempfile.TemporaryDirectory() as tmpdir: + local_path = os.path.join(tmpdir, "test.txt") + with open(local_path, "wb") as f: + f.write(contents) + bf.copy(local_path, remote_path, parallel=True) + + assert _read_contents(remote_path) == contents + + with tempfile.TemporaryDirectory() as tmpdir: + local_path = os.path.join(tmpdir, "test.txt") + bf.copy(remote_path, local_path, parallel=True) + assert _read_contents(local_path) == contents + + +def test_copy_azure_public(): + with _get_temp_as_path() as dst: + bf.copy(AZURE_PUBLIC_URL, dst) + assert _read_contents(dst)[:4] == AZURE_PUBLIC_URL_HEADER + + +def test_gcs_public(): + filepath = "gs://tfds-data/datasets/mnist/3.0.1/dataset_info.json" + assert bf.exists(filepath) + assert len(bf.BlobFile(filepath, "rb").read()) > 0 + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_exists(ctx): + contents = b"meow!" + with ctx() as path: + assert not bf.exists(path) + _write_contents(path, contents) + assert bf.exists(path) + + +def test_concurrent_write_gcs(): + with _get_temp_gcs_path() as path: + outer_contents = b"miso" * (2**20 + 1) + inner_contents = b"momo" * (2**20 + 1) + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(outer_contents) + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(inner_contents) + + # the outer write will finish last and overwrite the inner one + # the last writer to finish wins with this setup + with bf.BlobFile(path, "rb") as f: + assert f.read() == outer_contents + + +def test_concurrent_write_as(): + with _get_temp_as_path() as path: + b = bf.create_context(azure_write_chunk_size=2**20) + outer_contents = b"miso" * (2**20 + 1) + inner_contents = b"momo" * (2**20 + 1) + # the inner write will invalidate the outer one, the last writer + # to start wins with this setup + with pytest.raises(bf.ConcurrentWriteFailure): + with b.BlobFile(path, "wb", streaming=True) as f: + f.write(outer_contents) + with b.BlobFile(path, "wb", streaming=True) as f: + f.write(inner_contents) + + # the outer write will finish last and overwrite the inner one + with b.BlobFile(path, "rb") as f: + assert f.read() == inner_contents + + +@contextlib.contextmanager +def environ_context(): + env = os.environ.copy() + yield + os.environ = env + + +def test_more_exists(): + testcases = [ + (AZURE_INVALID_CONTAINER, False), + (AZURE_INVALID_CONTAINER + "/", False), + (AZURE_INVALID_CONTAINER + "//", False), + (AZURE_INVALID_CONTAINER + "/invalid.file", False), + (GCS_INVALID_BUCKET, False), + (GCS_INVALID_BUCKET + "/", False), + (GCS_INVALID_BUCKET + "//", False), + (GCS_INVALID_BUCKET + "/invalid.file", False), + (AZURE_INVALID_CONTAINER_NO_ACCOUNT, False), + (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "/", False), + (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "//", False), + (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "/invalid.file", False), + (AZURE_VALID_CONTAINER, True), + (AZURE_VALID_CONTAINER + "/", True), + (AZURE_VALID_CONTAINER + "//", False), + (AZURE_VALID_CONTAINER + "/invalid.file", False), + (GCS_VALID_BUCKET, True), + (GCS_VALID_BUCKET + "/", True), + (GCS_VALID_BUCKET + "//", False), + (GCS_VALID_BUCKET + "/invalid.file", False), + ("/does-not-exist", False), + ("/", True), + ] + for path, should_exist in testcases: + assert bf.exists(path) == should_exist + + +@pytest.mark.parametrize( + "base_path", [AZURE_INVALID_CONTAINER_NO_ACCOUNT, AZURE_INVALID_CONTAINER, GCS_INVALID_BUCKET] +) +def test_invalid_paths(base_path): + for suffix in ["", "/", "//", "/invalid.file", "/invalid/dir/"]: + path = base_path + suffix + print(path) + if path.endswith("/"): + expected_error = IsADirectoryError + else: + expected_error = FileNotFoundError + list(bf.glob(path)) + if suffix == "": + for pattern in ["*", "**"]: + try: + list(bf.glob(path + pattern)) + except bf.Error as e: + assert "Wildcards cannot be used" in e.message + else: + for pattern in ["*", "**"]: + list(bf.glob(path + pattern)) + with pytest.raises(FileNotFoundError): + list(bf.listdir(path)) + assert not bf.exists(path) + assert not bf.isdir(path) + with pytest.raises(expected_error): + bf.remove(path) + if suffix in ("", "/"): + try: + bf.rmdir(path) + except bf.Error as e: + assert "Cannot delete bucket" in e.message + else: + bf.rmdir(path) + with pytest.raises(NotADirectoryError): + bf.rmtree(path) + with pytest.raises(FileNotFoundError): + bf.stat(path) + + if base_path == AZURE_INVALID_CONTAINER_NO_ACCOUNT: + with pytest.raises(bf.Error): + bf.get_url(path) + else: + bf.get_url(path) + + with pytest.raises(FileNotFoundError): + bf.md5(path) + with pytest.raises(bf.Error): + bf.makedirs(path) + list(bf.walk(path)) + with tempfile.TemporaryDirectory() as tmpdir: + local_path = os.path.join(tmpdir, "test.txt") + with pytest.raises(expected_error): + bf.copy(path, local_path) + with open(local_path, "w") as f: + f.write("meow") + with pytest.raises(expected_error): + bf.copy(local_path, path) + for streaming in [False, True]: + with pytest.raises(expected_error): + with bf.BlobFile(path, "rb", streaming=streaming) as f: + f.read() + with pytest.raises(expected_error): + with bf.BlobFile(path, "wb", streaming=streaming) as f: + f.write(b"meow") + + +@pytest.mark.parametrize("buffer_size", [1, 100]) +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_read_stats(buffer_size, ctx): + with ctx() as path: + contents = b"meow!" + + with bf.BlobFile(path, "wb") as w: + w.write(contents) + + with bf.BlobFile(path, "rb", buffer_size=buffer_size) as r: + r.read(1) + + if buffer_size == 1: + assert r.raw.bytes_read == 1 # type: ignore + else: + assert r.raw.bytes_read == len(contents) # type: ignore + + with bf.BlobFile(path, "rb", buffer_size=buffer_size) as r: + r.read(1) + r.seek(4) + r.read(1) + r.seek(1000000) + assert r.read(1) == b"" + + if buffer_size == 1: + assert r.raw.requests == 2 # type: ignore + assert r.raw.bytes_read == 2 # type: ignore + else: + assert r.raw.requests == 1 # type: ignore + assert r.raw.bytes_read == len(contents) # type: ignore + + +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_cache_dir(ctx): + cache_dir = tempfile.mkdtemp() + contents = b"meow!" + alternative_contents = b"purr!" + with ctx() as path: + with bf.BlobFile(path, mode="wb") as f: + f.write(contents) + with bf.BlobFile(path, mode="rb", streaming=False, cache_dir=cache_dir) as f: + assert f.read() == contents + content_hash = hashlib.md5(contents).hexdigest() + cache_path = bf.join(cache_dir, content_hash, bf.basename(path)) + with open(cache_path, "rb") as f: + assert f.read() == contents + # alter the cached file to make sure we are not re-reading the remote file + with open(cache_path, "wb") as f: + f.write(alternative_contents) + with bf.BlobFile(path, mode="rb", streaming=False, cache_dir=cache_dir) as f: + assert f.read() == alternative_contents + with bf.BlobFile( + f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat_no_md5.png", + mode="rb", + streaming=False, + cache_dir=cache_dir, + ) as f: + assert len(f.read()) > 0 + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +@pytest.mark.parametrize("use_random", [False, True]) +def test_change_file_size(ctx, use_random): + chunk_size = 8 * 2**20 + long_contents = b"\x00" * chunk_size * 3 + short_contents = b"\xFF" * chunk_size * 2 + if use_random: + long_contents = os.urandom(len(long_contents)) + short_contents = os.urandom(len(short_contents)) + with ctx() as path: + # make file shorter + with bf.BlobFile(path, "wb") as f: + f.write(long_contents) + with bf.BlobFile(path, "rb") as f: + read_contents = f.read(chunk_size) + with bf.BlobFile(path, "wb") as f2: + f2.write(short_contents) + # close underlying connection + f.raw._f = None # type: ignore + read_contents += f.read() + assert len(f.read()) == 0 + assert read_contents == long_contents[:chunk_size] + short_contents[chunk_size:] + + # make file longer + with bf.BlobFile(path, "wb") as f: + f.write(short_contents) + with bf.BlobFile(path, "rb") as f: + read_contents = f.read(chunk_size) + with bf.BlobFile(path, "wb") as f2: + f2.write(long_contents) + # close underlying connection + f.raw._f = None # type: ignore + read_contents += f.read() + assert len(f.read()) == 0 + expected = short_contents[:chunk_size] + long_contents[chunk_size : chunk_size * 2] + # local files behave differently and read the new contents until the + # end of the new file size + if not path.startswith("gs://") and not path.startswith("https://"): + expected = short_contents[:chunk_size] + long_contents[chunk_size:] + assert read_contents == expected + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_overwrite_while_reading(ctx): + chunk_size = 8 * 2**20 + contents = b"\x00" * chunk_size * 2 + alternative_contents = b"\xFF" * chunk_size * 4 + with ctx() as path: + with bf.BlobFile(path, "wb") as f: + f.write(contents) + with bf.BlobFile(path, "rb") as f: + read_contents = f.read(chunk_size) + with bf.BlobFile(path, "wb") as f2: + f2.write(alternative_contents) + # close underlying connection + f.raw._f = None # type: ignore + read_contents += f.read(chunk_size) + assert ( + read_contents + == contents[:chunk_size] + alternative_contents[chunk_size : chunk_size * 2] + ) + + +def test_create_local_intermediate_dirs(): + contents = b"meow" + with _get_temp_local_path() as path: + dirpath = bf.dirname(path) + with chdir(dirpath): + for filepath in [ + bf.join(dirpath, "dirname", "file.name"), + bf.join("..", bf.basename(dirpath), "file.name"), + "./file.name", + "file.name", + ]: + with bf.BlobFile(filepath, "wb") as f: + f.write(contents) + + +@pytest.mark.parametrize("binary", [True, False]) +@pytest.mark.parametrize("streaming", [True, False]) +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_more_read_write(binary, streaming, ctx): + rng = np.random.RandomState(0) + + with ctx() as path: + if binary: + read_mode = "rb" + write_mode = "wb" + else: + read_mode = "r" + write_mode = "w" + + with bf.BlobFile(path, write_mode, streaming=streaming) as w: + pass + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + assert len(r.read()) == 0 + + contents = b"meow!" + if not binary: + contents = contents.decode("utf8") + + with bf.BlobFile(path, write_mode, streaming=streaming) as w: + w.write(contents) + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + assert r.read(1) == contents[:1] + assert r.read() == contents[1:] + assert len(r.read()) == 0 + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + for i in range(len(contents)): + assert r.read(1) == contents[i : i + 1] + assert len(r.read()) == 0 + assert len(r.read()) == 0 + + contents = b"meow!\n\nmew!\n" + lines = [b"meow!\n", b"\n", b"mew!\n"] + if not binary: + contents = contents.decode("utf8") + lines = [line.decode("utf8") for line in lines] + + with bf.BlobFile(path, write_mode, streaming=streaming) as w: + w.write(contents) + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + assert r.readlines() == lines + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + assert [line for line in r] == lines + + if binary: + for size in [2 * 2**20, 12_345_678]: + contents = rng.randint(0, 256, size=size, dtype=np.uint8).tobytes() + + with bf.BlobFile(path, write_mode, streaming=streaming) as w: + w.write(contents) + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + size = rng.randint(0, 1_000_000) + buf = b"" + while True: + b = r.read(size) + if b == b"": + break + buf += b + assert buf == contents + else: + obj = {"a": 1} + + with bf.BlobFile(path, write_mode, streaming=streaming) as w: + json.dump(obj, w) + + with bf.BlobFile(path, read_mode, streaming=streaming) as r: + assert json.load(r) == obj + + +@pytest.mark.parametrize("streaming", [True, False]) +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_video(streaming, ctx): + try: + import av + import imageio + except ImportError: + pytest.skip("av and imageio are required for this test") + + rng = np.random.RandomState(0) + shape = (256, 64, 64, 3) + video_data = rng.randint(0, 256, size=np.prod(shape), dtype=np.uint8).reshape(shape) + + with ctx() as path: + with bf.BlobFile(path, mode="wb", streaming=streaming) as wf: + with imageio.get_writer( + wf, + format="ffmpeg", + quality=None, + codec="libx264rgb", + pixelformat="bgr24", + output_params=["-f", "mp4", "-crf", "0"], + ) as w: + for frame in video_data: + w.append_data(frame) + + with bf.BlobFile(path, mode="rb", streaming=streaming) as rf: + with imageio.get_reader(rf, format="ffmpeg", input_params=["-f", "mp4"]) as r: + for idx, frame in enumerate(r): + assert np.array_equal(frame, video_data[idx]) + + with bf.BlobFile(path, mode="rb", streaming=streaming) as rf: + container = av.open(rf) + stream = container.streams.video[0] + for idx, frame in enumerate(container.decode(stream)): + assert np.array_equal(frame.to_image(), video_data[idx]) + + +# this is pretty slow and docker will often run out of memory +@pytest.mark.slow +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_large_file(ctx): + contents = b"0" * 2**32 + with ctx() as path: + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(contents) + with bf.BlobFile(path, "rb", streaming=True) as f: + assert contents == f.read() + + +def test_composite_objects(): + with _get_temp_gcs_path() as remote_path: + with _get_temp_local_path() as local_path: + contents = b"0" * 2 * 2**20 + with open(local_path, "wb") as f: + f.write(contents) + + def create_composite_file(): + sp.run( + [ + "gsutil", + "-o", + "GSUtil:parallel_composite_upload_threshold=1M", + "cp", + local_path, + remote_path, + ], + check=True, + ) + + local_md5 = hashlib.md5(contents).hexdigest() + create_composite_file() + assert bf.stat(remote_path).md5 is None + assert local_md5 == bf.md5(remote_path) + assert bf.stat(remote_path).md5 == local_md5 + assert local_md5 == bf.md5(remote_path) + + bf.remove(remote_path) + create_composite_file() + assert bf.stat(remote_path).md5 is None + + with tempfile.TemporaryDirectory() as tmpdir: + with bf.BlobFile(remote_path, "rb", cache_dir=tmpdir, streaming=False) as f: + assert f.read() == contents + assert bf.stat(remote_path).md5 == local_md5 + + +@pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path]) +def test_md5(ctx): + contents = b"meow!" + meow_hash = hashlib.md5(contents).hexdigest() + + with ctx() as path: + _write_contents(path, contents) + assert bf.md5(path) == meow_hash + with bf.BlobFile(path, "wb") as f: + f.write(contents) + assert bf.md5(path) == meow_hash + with bf.BlobFile(path, "wb") as f: + f.write(contents) + assert bf.md5(path) == meow_hash + + +@pytest.mark.parametrize("ctx", [_get_temp_as_path]) +def test_azure_maybe_update_md5(ctx): + contents = b"meow!" + meow_hash = hashlib.md5(contents).hexdigest() + alternative_contents = b"purr" + purr_hash = hashlib.md5(alternative_contents).hexdigest() + + with ctx() as path: + _write_contents(path, contents) + st = azure.maybe_stat(ops.default_context._conf, path) + assert azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash) + _write_contents(path, alternative_contents) + assert not azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash) + st = azure.maybe_stat(ops.default_context._conf, path) + assert st.md5 == purr_hash + bf.remove(path) + assert not azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash) + + +@pytest.mark.parametrize("ctx", [_get_temp_as_path]) +def test_azure_etags(ctx): + contents = b"bark!" + alternative_contents = b"ruff" + + with ctx() as path: + bf.BlobFile(path, "wb").write(contents) + version = bf.stat(path).version + + # test can write a bunch of times on correct version + with bf.BlobFile(path, "wb", version=version) as f: + # first time should work + for _ in range(1000): + f.write(alternative_contents) + + version = bf.stat(path).version + with bf.BlobFile(path, "wb", version=version) as f: + # overwrite it again to match with later in test + f.write(alternative_contents) + + new_version = bf.stat(path).version + assert new_version != version + with pytest.raises(bf.VersionMismatch): + with bf.BlobFile(path, "wb", version=version) as f: + # second time should fail + f.write(contents) + + assert bf.BlobFile(path, "rb").read() == alternative_contents + + bf.remove(path) + + +@pytest.mark.parametrize("ctx", [_get_temp_as_path]) +def test_azure_etags_last_version(ctx): + part1 = b"hello" + part2 = b" world" + + with ctx() as path: + try: + bf.remove(path) + except FileNotFoundError: + pass + + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(part1) + # This is None if the file did not previously exist. + assert bf.last_version_seen(f) is None + f.write(part2) + written_version = bf.last_version_seen(f) + with bf.BlobFile(path, "rb", streaming=True) as f: + assert f.read(len(part1)) == part1 + partial_read_version = bf.last_version_seen(f) + assert partial_read_version is not None + assert f.read() == part2 + read_version = bf.last_version_seen(f) + assert partial_read_version == read_version + assert written_version == read_version + + bf.remove(path) + + data1 = b"hi there" + data2 = b"overwrite" + + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(data1) + with bf.BlobFile(path, "wb", streaming=True) as f2: + f2.write(data2) + version1 = bf.last_version_seen(f) + version2 = bf.last_version_seen(f2) + assert version1 != version2 + + with pytest.raises(bf.VersionMismatch): + with bf.BlobFile(path, "rb", streaming=True, version=version1) as f: + assert f.read() == data1 + + with bf.BlobFile(path, "rb", streaming=True) as f: + assert f.read() == data2 + read_version = bf.last_version_seen(f) + assert read_version == version2 + + bf.remove(path) + + with bf.BlobFile(path, "wb", streaming=True) as f: + f.write(b"abcdefgh" * 1024) + with bf.BlobFile(path, "rb", streaming=True, buffer_size=16) as f: + assert f.read(16) == b"abcdefgh" * 2 + with bf.BlobFile(path, "wb", streaming=True) as g: + g.write(b"ijklmnop" * 1024) + with pytest.raises(bf.VersionMismatch): + f.read(16) + + bf.remove(path) + + +@pytest.mark.parametrize("ctx", [_get_temp_as_path]) +def test_azure_buffer_error_finally(ctx): + # Avoid BufferError: Existing exports of data: object cannot be re-sized + # See https://github.com/blobfile/blobfile/pull/230 + @contextlib.contextmanager + def trailer_file(fn: str): + bfc = bf.create_context(azure_write_chunk_size=1024) + with bfc.BlobFile(fn, "wb", streaming=True) as f: + try: + yield f + finally: + f.write(b"asdf" * 1024) + + with ctx() as path: + with trailer_file(path) as f: + with unittest.mock.patch("blobfile._azure.execute_api_request") as mock: + mock.side_effect = RuntimeError("asdf") + f.write(b"asdf") + with pytest.raises(RuntimeError): + f.write(b"asdf" * 1024 * 2) + assert mock.call_count == 1 + + +def test_azure_timestamp_parsing(): + timestamp = "Sun, 27 Sep 2009 18:41:57 GMT" + + def ref_parse_timestamp(text: str) -> float: + return datetime.datetime.strptime( + text.replace("GMT", "Z"), "%a, %d %b %Y %H:%M:%S %z" + ).timestamp() + + assert ref_parse_timestamp(timestamp) == azure._parse_timestamp(timestamp) + + +def _get_http_pool_id(q): + q.put(id(ops.default_context._conf.get_http_pool())) + + +def test_fork(): + q = mp.Queue() + # this reference should keep the old http client alive in the child process + # to ensure that a new one does not recycle the memory address + http1 = ops.default_context._conf.get_http_pool() + parent1 = id(http1) + p = mp.Process(target=_get_http_pool_id, args=(q,)) + p.start() + p.join() + http2 = ops.default_context._conf.get_http_pool() + parent2 = id(http2) + + child = q.get() + assert parent1 == parent2 + assert child != parent1 + + +def test_azure_public_container(): + for error, path in [ + (None, f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png"), + ( + bf.Error, + f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/private/test_cat.png", + ), # an account that exists but with a non-public container + ( + FileNotFoundError, + f"https://{AS_INVALID_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png", + ), # account that does not exist + ]: + ctx = contextlib.nullcontext() + if error is not None: + ctx = pytest.raises(error) + with ctx: + with bf.BlobFile(path, "rb") as f: + contents = f.read() + assert contents.startswith(AZURE_PUBLIC_URL_HEADER) + + +def test_scandir_error(): + for error, path in [ + (None, AZURE_VALID_CONTAINER), + (FileNotFoundError, AZURE_INVALID_CONTAINER), + (FileNotFoundError, AZURE_INVALID_CONTAINER_NO_ACCOUNT), + (bf.Error, f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/private"), + ]: + ctx = contextlib.nullcontext() + if error is not None: + ctx = pytest.raises(error) + with ctx: + print(path) + list(bf.scandir(path)) + + +def test_windowed_file(): + with _get_temp_local_path() as path: + with open(path, "wb") as f: + f.write(b"meow") + + with open(path, "rb") as f: + f2 = common.WindowedFile(f, start=1, end=3) + assert f2.read() == b"eo" + + f2.seek(0) + assert f2.read(1) + f2.read(1) + f2.read(1) == b"eo" + + with pytest.raises(AssertionError): + f2.seek(-1) + + with pytest.raises(AssertionError): + f2.seek(2) + + +class Deadline: + def __init__(self): + self._deadline = None + + def set_deadline(self, deadline: float) -> None: + self._deadline = deadline + + def get_deadline(self) -> float: + return self._deadline + + +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_deadline(ctx): + contents = b"meow" + with ctx() as path: + _write_contents(path, contents) + deadline = Deadline() + bf_ctx = bf.create_context(get_deadline=deadline.get_deadline) + deadline.set_deadline(time.time() + 5) + with bf_ctx.BlobFile(path, "rb") as f: + f.read() + time.sleep(5) + with pytest.raises(bf.DeadlineExceeded): + with bf_ctx.BlobFile(path, "rb") as f: + f.read() + deadline.set_deadline(None) + with bf_ctx.BlobFile(path, "rb") as f: + f.read() + + +def test_pickle_config(): + ctx = ops.create_context() + c = ctx._conf + pickle.dumps(c) + c.get_http_pool() + c2 = pickle.loads(pickle.dumps(c)) + c2.get_http_pool() + + +@pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path]) +def test_read_with_size(ctx): + contents = b"meow!\npurr\n" + with ctx() as path: + path = bf.join(path, "a folder", "a.file") + bf.makedirs(bf.dirname(path)) + with bf.BlobFile(path, "wb") as w: + w.write(contents) + with bf.BlobFile(path, "rb", file_size=1) as r: + assert r.read() == contents[:1] + assert r.tell() == 1 diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_xml.py b/videollama2/lib/python3.10/site-packages/blobfile/_xml.py new file mode 100644 index 0000000000000000000000000000000000000000..a237f2546a5685a4f2d2f6d9e705706d23124946 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_xml.py @@ -0,0 +1,78 @@ +""" +Slightly faster replacement for xmltodict +""" + +from typing import Optional, Any, Set, Union, Dict +from lxml import etree + + +Element = etree._Element # type: ignore + + +def parse(document: bytes, repeated_tags: Optional[Set[str]] = None) -> Dict[str, Any]: + """ + Convert an XML document to a dictionary, like xmltodict.parse but with lxml + """ + if repeated_tags is None: + repeated_tags = set() + root = etree.fromstring(document) + children = _recursive_dict(root, repeated_tags=repeated_tags) + return {root.tag: children} + + +def _recursive_dict(elem: Element, repeated_tags: Set[str]) -> Union[Dict[str, Any], Optional[str]]: + if len(elem) == 0: + return elem.text + else: + seen_tags = set() + result = {} + for child in elem: + if child.tag in repeated_tags: + child_list = result.setdefault(child.tag, []) + child_list.append(_recursive_dict(child, repeated_tags)) + else: + assert ( + child.tag not in seen_tags + ), f"Found repeated tag that was not in repeated_tags set: {child.tag}" + seen_tags.add(child.tag) + result[child.tag] = _recursive_dict(child, repeated_tags) + return result + + +def unparse(data: Dict[str, Any]) -> bytes: + """ + Convert a dictionary into an XML document, like xmltodict.unparse but with lxml + """ + root_keys = list(data.keys()) + assert len(root_keys) == 1, f"Must be only one root element, found {root_keys}" + root = _create_tree(root_keys[0], data[root_keys[0]]) + # xml_declaration=True doesn't work for some reason, it seems + # to use single quotes that azure doesn't like + return b'\n' + etree.tostring(root, encoding="utf8") + + +def _create_tree(name: str, data: Dict[str, Any]) -> Element: + elem = etree.Element(name) + for k, v in data.items(): + if isinstance(v, dict): + elem.append(_create_tree(k, v)) + elif isinstance(v, list): + for item in v: + if isinstance(item, str): + se = etree.Element(k) + se.text = item + elem.append(se) + elif isinstance(item, dict): + elem.append(_create_tree(k, item)) + else: + assert False, f"Invalid value item type: {type(item)}" + else: + assert isinstance(v, str) or v is None + se = etree.Element(k) + if v is None: + # match xmltodict's behavior and use instead of + se.text = "" + else: + se.text = v + elem.append(se) + return elem diff --git a/videollama2/lib/python3.10/site-packages/blobfile/_xml_test.py b/videollama2/lib/python3.10/site-packages/blobfile/_xml_test.py new file mode 100644 index 0000000000000000000000000000000000000000..91ad5f2e369001d32852a4d861eca72efbecb7c6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/blobfile/_xml_test.py @@ -0,0 +1,163 @@ +import json +import time +from typing import Any, Dict +import xmltodict +from blobfile import _xml as xml + +resp = b"""\ + + + 4 + + + blob1.txt + https://myaccount.blob.core.windows.net/mycontainer/blob1.txt + + Sun, 27 Sep 2009 18:41:57 GMT + 0x8CAE7D55D050B8B + 8 + text/html + + en-US + + no-cache + BlockBlob + unlocked + + + + blob2.txt + https://myaccount.blob.core.windows.net/mycontainer/blob2.txt + + Sun, 27 Sep 2009 12:18:50 GMT + 0x8CAE7D55CF6C339 + 100 + text/html + + en-US + + no-cache + BlockBlob + unlocked + + + + myfolder/ + + + newblob1.txt + https://myaccount.blob.core.windows.net/mycontainer/newblob1.txt + + Sun, 27 Sep 2009 16:31:57 GMT + 0x8CAE7D55CF6C339 + 25 + text/html + + en-US + + no-cache + BlockBlob + unlocked + + + + myfolder2/ + + + newblob2.txt + +""" + + +def remove_attributes(d: Dict[str, Any]) -> Dict[str, Any]: + result = {} + for k, v in d.items(): + if k.startswith("@"): + continue + if isinstance(v, dict): + v = remove_attributes(v) + result[k] = v + return result + + +def xmltodict_parse(data: bytes) -> Dict[str, Any]: + parsed = xmltodict.parse(data.decode("utf8")) + # we don't support attributes in our parser since we don't use them anyway + return remove_attributes(parsed) + + +def xmltodict_unparse(d: Dict[str, Any]) -> bytes: + return xmltodict.unparse(d).encode("utf8") + + +def test_parse(): + ref = xmltodict_parse(resp) + actual = xml.parse(resp, repeated_tags={"Blob", "BlobPrefix"}) + json_ref = json.dumps(ref, sort_keys=True, indent=" ") + json_actual = json.dumps(actual, sort_keys=True, indent=" ") + print(json_ref) + print(json_actual) + assert json_ref == json_actual + + +def test_unparse(): + body = {"BlockList": {"Latest": [str(i) for i in range(100)]}} + ref = xmltodict_unparse(body) + actual = xml.unparse(body) + print(ref) + print(actual) + assert ref == actual + + +def test_roundtrip(): + ref_parsed = xmltodict_parse(resp) + ref_unparsed = xmltodict_unparse(ref_parsed) + + actual_parsed = xml.parse(ref_unparsed, repeated_tags={"Blob", "BlobPrefix"}) + assert ref_parsed == actual_parsed + + actual_unparsed = xml.unparse(ref_parsed) + print() + print(ref_unparsed) + print(actual_unparsed) + assert ref_unparsed == actual_unparsed + + assert ref_unparsed == xml.unparse( + xml.parse(xml.unparse(ref_parsed), repeated_tags={"Blob", "BlobPrefix"}) + ) + + +def main(): + # benchmarking + doc = xmltodict_parse(resp) + doc2 = doc.copy() + doc2["EnumerationResults"]["Blobs"]["Blob"] = doc2["EnumerationResults"]["Blobs"]["Blob"] * 300 + expanded_resp_utf8 = xmltodict_unparse(doc2) + + start = time.perf_counter() + for _ in range(100): + xmltodict.parse(expanded_resp) + end = time.perf_counter() + print(f"xmltodict parse elapsed {end - start}") + + start = time.perf_counter() + for _ in range(100): + lxml_parse(expanded_resp_utf8, repeated_tags={"Blob", "BlobPrefix"}) + end = time.perf_counter() + print(f"lxml parse elapsed {end - start}") + + start = time.perf_counter() + for _ in range(100): + xmltodict.unparse(doc2) + end = time.perf_counter() + print(f"xmltodict unparse elapsed {end - start}") + + start = time.perf_counter() + for _ in range(100): + lxml_unparse(doc2) + end = time.perf_counter() + print(f"lxml unparse elapsed {end - start}") + + +if __name__ == "__main__": + main() diff --git a/videollama2/lib/python3.10/site-packages/blobfile/py.typed b/videollama2/lib/python3.10/site-packages/blobfile/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/LICENSE.txt b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a87ef73560336d713e8cdfdd40f0eb1d05a76e4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/LICENSE.txt @@ -0,0 +1,59 @@ +This implementation of Markdown is licensed under the MIT License: + + The MIT License + + Copyright (c) 2012 Trent Mick + Copyright (c) 2010 ActiveState Software Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. + + +All files in a *source package* of markdown2 (i.e. those available on +pypi.python.org and the Google Code project "downloads" page) are under the +MIT license. However, in the *subversion repository* there are some files +(used for performance and testing purposes) that are under different licenses +as follows: + +- perf/recipes.pprint + + Python License. This file includes a number of real-world examples of + Markdown from the ActiveState Python Cookbook, used for doing some + performance testing of markdown2.py. + +- test/php-markdown-cases/... + test/php-markdown-extra-cases/... + + GPL. These are from the MDTest package announced here: + http://six.pairlist.net/pipermail/markdown-discuss/2007-July/000674.html + +- test/markdown.py + + GPL 2 or BSD. A copy (currently old) of Python-Markdown -- the other + Python Markdown implementation. + +- test/markdown.php + + BSD-style. This is PHP Markdown + (http://michelf.com/projects/php-markdown/). + +- test/Markdown.pl: BSD-style + + A copy of Perl Markdown (http://daringfireball.net/projects/markdown/). + diff --git a/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/RECORD b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..def60b4615246118d2b491c815c1fa96540d8d19 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/RECORD @@ -0,0 +1,11 @@ +../../../bin/markdown2,sha256=KkVDAWQ4bONPZiGBj3XK7q4noHU4G6Jgs0pp8GZyZ68,225 +__pycache__/markdown2.cpython-310.pyc,, +markdown2-2.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +markdown2-2.5.0.dist-info/LICENSE.txt,sha256=-MfE1VRAnPYhuNZT2__7cZdF_Tb1xJuDBSWGSbQD75w,2313 +markdown2-2.5.0.dist-info/METADATA,sha256=77fAG1WWkQYNiTeYHpP1qUGmL0vsCds5OJf7IfCFAz8,2168 +markdown2-2.5.0.dist-info/RECORD,, +markdown2-2.5.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +markdown2-2.5.0.dist-info/WHEEL,sha256=WzZ8cwjh8l0jtULNjYq1Hpr-WCqCRgPr--TX4P5I1Wo,110 +markdown2-2.5.0.dist-info/entry_points.txt,sha256=ZAfeiSjZzwRSLJYMNAPOV-cMgZhEAVdrjG_E3wF0kz4,46 +markdown2-2.5.0.dist-info/top_level.txt,sha256=fDjZIsBNbTniMxzHsMuRyzfmvWbBOoUklf6ycVKreNc,10 +markdown2.py,sha256=dPE0ONPHXlpGpAa66RUqH8Rmis0OcmRZ8a5LhOBH3m0,157356 diff --git a/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/REQUESTED b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/entry_points.txt b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..ecf203da0d54554dd5e4bc7e0bb30020f0914bd2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +markdown2 = markdown2:main + diff --git a/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/top_level.txt b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5d9211aa222f6463313073ee4cbbc1a6a58e086 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/top_level.txt @@ -0,0 +1 @@ +markdown2 diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ace49c07fc31280fe407408200ede2b37fb0553a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Edinburgh Genome Foundry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..69edf2dc3c55d010579897d1408353fab18437e9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA @@ -0,0 +1,34 @@ +Metadata-Version: 2.1 +Name: proglog +Version: 0.1.10 +Summary: Log and progress bar manager for console, notebooks, web... +Author: Zulko +License: MIT +Keywords: logger log progress bar +Platform: UNKNOWN +License-File: LICENSE +Requires-Dist: tqdm + +Proglog +======= + +Proglog is a progress logging system for Python. It allows to build complex +libraries while giving the user control on the management of logs, callbacks and progress bars. + + +Infos +----- + +**PIP installation:** + +.. code:: bash + + pip install proglog + +**Github Page** + +``_ + +**License:** MIT, Copyright Edinburgh Genome Foundry + + diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0d7de0bfa9d9f41541109c17a65e4f0b44325a69 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD @@ -0,0 +1,13 @@ +proglog-0.1.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +proglog-0.1.10.dist-info/LICENSE,sha256=akVjFR4jDJtNakzf3avomKdfddMyA9WHJ5aVV08efxY,1081 +proglog-0.1.10.dist-info/METADATA,sha256=7HqXAeqQ_WotmBFY28nag6MAHWRdXYCY0x1Xmv49hKI,639 +proglog-0.1.10.dist-info/RECORD,, +proglog-0.1.10.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +proglog-0.1.10.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +proglog-0.1.10.dist-info/top_level.txt,sha256=KeCzTcuXoZxru4GWsCpIwgVBfHdDrI0ujnDKu61sFXE,8 +proglog/__init__.py,sha256=m68k-TnqoChy0FjkHWqSfPuEiQgl69Cfs-N4Kp7k-tU,302 +proglog/__pycache__/__init__.cpython-310.pyc,, +proglog/__pycache__/proglog.cpython-310.pyc,, +proglog/__pycache__/version.cpython-310.pyc,, +proglog/proglog.py,sha256=qWQSpWM-pR_pyh5vrrlVBU094bkatfj9prbz5PJpK7U,13250 +proglog/version.py,sha256=z0zCHFTcKSR0tJ6h5qrpNmRVP21QIPP8N0p7quCnnm0,23 diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..efd532dc5ccb3387b750cf39032ea8c9780072c4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt @@ -0,0 +1 @@ +proglog diff --git a/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/INSTALLER b/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/METADATA b/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..03c48b95c51d989c1aa40bc6aa2db9f9846ee5a2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/METADATA @@ -0,0 +1,87 @@ +Metadata-Version: 2.1 +Name: pyarrow +Version: 17.0.0 +Summary: Python library for Apache Arrow +Maintainer-email: Apache Arrow Developers +License: Apache Software License +Project-URL: Homepage, https://arrow.apache.org/ +Project-URL: Documentation, https://arrow.apache.org/docs/python +Project-URL: Repository, https://github.com/apache/arrow +Project-URL: Issues, https://github.com/apache/arrow/issues +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: ../LICENSE.txt +License-File: ../NOTICE.txt +Requires-Dist: numpy >=1.16.6 +Provides-Extra: test +Requires-Dist: pytest ; extra == 'test' +Requires-Dist: hypothesis ; extra == 'test' +Requires-Dist: cffi ; extra == 'test' +Requires-Dist: pytz ; extra == 'test' +Requires-Dist: pandas ; extra == 'test' + + + +## Python library for Apache Arrow + +[![pypi](https://img.shields.io/pypi/v/pyarrow.svg)](https://pypi.org/project/pyarrow/) [![conda-forge](https://img.shields.io/conda/vn/conda-forge/pyarrow.svg)](https://anaconda.org/conda-forge/pyarrow) + +This library provides a Python API for functionality provided by the Arrow C++ +libraries, along with tools for Arrow integration and interoperability with +pandas, NumPy, and other software in the Python ecosystem. + +## Installing + +Across platforms, you can install a recent version of pyarrow with the conda +package manager: + +```shell +conda install pyarrow -c conda-forge +``` + +On Linux, macOS, and Windows, you can also install binary wheels from PyPI with +pip: + +```shell +pip install pyarrow +``` + +If you encounter any issues importing the pip wheels on Windows, you may need +to install the [Visual C++ Redistributable for Visual Studio 2015][6]. + +## Development + +See [Python Development][2] in the documentation subproject. + +### Building the documentation + +See [documentation build instructions][1] in the documentation subproject. + +[1]: https://github.com/apache/arrow/blob/main/docs/source/developers/documentation.rst +[2]: https://github.com/apache/arrow/blob/main/docs/source/developers/python.rst +[3]: https://github.com/pandas-dev/pandas +[5]: https://arrow.apache.org/docs/latest/python/benchmarks.html +[6]: https://www.microsoft.com/en-us/download/details.aspx?id=48145 diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bbbc7f1182bf77748a8284d2c97bf4409f9a3ee Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/animate.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/animate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db1eb74456f9a690ff890dcfa8f38dd2442a2bd Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/animate.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/base.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb14280877c770d8d2a67128a1320a1b62247c2c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/base.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/container.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/container.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f154b52c12c634be46250e8891bb320aaf6f6aca Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/container.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/drawing.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/drawing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a0e3ad6ad793f25af00fb564a3236f205002a85 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/drawing.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/elementfactory.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/elementfactory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0480ec24774ce9df97a2820896d77b3a22dcf91f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/elementfactory.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/filters.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/filters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4853e691bf44ee81881e38fca5988897c7987974 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/filters.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/masking.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/masking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fd7e54dfdd43ee4b1518ec8b6964ca2c3268401 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/masking.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/mixins.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/mixins.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74103e63d3f2cb6fc82ee94b24aa28f95271da0f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/mixins.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/params.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/params.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65ff8b4efa73c8197e869f90cdd098cfadf69847 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/params.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/path.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca2299c75c5a8d2772be45fb6db3f9a23a95a7ca Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/path.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/pattern.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/pattern.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7690b25c1e67c4c765de2605ad029352a6a2e592 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/pattern.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/shapes.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/shapes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1e023a9cb1897dbda601e28e7f6b9cdb8cc271b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/shapes.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/utils.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab02b9ec19d9287ae590774920c01f60ba29aef4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/utils.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/validator2.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/validator2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d247536b7d3a80b8b7fdfd4881203b3c56457f78 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/validator2.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/version.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b23881bf7984a7dfe312248fb7301c5b667ccaa1 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/version.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/animate.py b/videollama2/lib/python3.10/site-packages/svgwrite/animate.py new file mode 100644 index 0000000000000000000000000000000000000000..5908ec1cb65cd894f8f34aacf98ab009071a3d4a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/animate.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: animate elements +# Created: 31.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.base import BaseElement +from svgwrite.mixins import XLink +from svgwrite.utils import strlist, is_string + + +class Set(BaseElement, XLink): + """ The **set** element provides a simple means of just setting the value + of an attribute for a specified duration. It supports all attribute types, + including those that cannot reasonably be interpolated, such as string + and boolean values. The **set** element is non-additive. The additive and + accumulate attributes are not allowed, and will be ignored if specified. + """ + elementname = 'set' + + def __init__(self, href=None, **extra): + """ Set constructor. + + :param href: target svg element, if **href** is not `None`; else + the target SVG Element is the parent SVG Element. + """ + super(Set, self).__init__(**extra) + if href is not None: + self.set_href(href) + + def get_xml(self): + self.update_id() # if href is an object - 'id' - attribute may be changed! + return super(Set, self).get_xml() + + def set_target(self, attributeName, attributeType=None): + """ + Set animation attributes :ref:`attributeName` and :ref:`attributeType`. + """ + self['attributeName'] = attributeName + if attributeType is not None: + self['attributeType'] = attributeType + + + def set_event(self, onbegin=None, onend=None, onrepeat=None, onload=None): + """ + Set animation attributes :ref:`onbegin`, :ref:`onend`, :ref:`onrepeat` + and :ref:`onload`. + """ + if onbegin is not None: + self['onbegin'] = onbegin + if onend is not None: + self['onend'] = onend + if onrepeat is not None: + self['onrepeat'] = onrepeat + if onload is not None: + self['onload'] = onload + + def set_timing(self, begin=None, end=None, dur=None, min=None, max=None, + restart=None, repeatCount=None, repeatDur=None): + """ + Set animation attributes :ref:`begin`, :ref:`end`, :ref:`dur`, + :ref:`min`, :ref:`max`, :ref:`restart`, :ref:`repeatCount` and + :ref:`repeatDur`. + """ + if begin is not None: + self['begin'] = begin + if end is not None: + self['end'] = end + if dur is not None: + self['dur'] = dur + if min is not None: + self['min'] = min + if max is not None: + self['max'] = max + if restart is not None: + self['restart'] = restart + if repeatCount is not None: + self['repeatCount'] = repeatCount + if repeatDur is not None: + self['repeatDur'] = repeatDur + + def freeze(self): + """ Freeze the animation effect. (see also :ref:`fill `) + """ + self['fill'] = 'freeze' + +class AnimateMotion(Set): + """ The **animateMotion** element causes a referenced element to move + along a motion path. + """ + elementname = 'animateMotion' + + def __init__(self, path=None, href=None, **extra): + """ + :param path: the motion path + :param href: target svg element, if **href** is not `None`; else + the target SVG Element is the parent SVG Element. + """ + super(AnimateMotion, self).__init__(href=href, **extra) + if path is not None: + self['path'] = path + + def set_value(self, path=None, calcMode=None, keyPoints=None, rotate=None): + """ + Set animation attributes `path`, `calcMode`, `keyPoints` and `rotate`. + """ + if path is not None: + self['path'] = path + if calcMode is not None: + self['calcMode'] = calcMode + if keyPoints is not None: + self['keyPoints'] = keyPoints + if rotate is not None: + self['rotate'] = rotate + + +class Animate(Set): + """ The **animate** element allows scalar attributes and properties to be + assigned different values over time . + """ + elementname = 'animate' + + def __init__(self, attributeName=None, values=None, href=None, **extra): + """ + :param attributeName: name of the SVG Attribute to animate + :param values: interpolation values, `string` as `` or a python `list` + :param href: target svg element, if **href** is not `None`; else + the target SVG Element is the parent SVG Element. + """ + super(Animate, self).__init__(href=href, **extra) + if values is not None: + self.set_value(values) + if attributeName is not None: + self.set_target(attributeName) + + def set_value(self, values, calcMode=None, keyTimes=None, keySplines=None, + from_=None, to=None, by=None): + """ + Set animation attributes :ref:`values`, :ref:`calcMode`, :ref:`keyTimes`, + :ref:`keySplines`, :ref:`from`, :ref:`to` and :ref:`by`. + """ + if values is not None: + if not is_string(values): + values = strlist(values, ';') + self['values'] = values + + if calcMode is not None: + self['calcMode'] = calcMode + if keyTimes is not None: + self['keyTimes'] = keyTimes + if keySplines is not None: + self['keySplines'] = keySplines + if from_ is not None: + self['from'] = from_ + if to is not None: + self['to'] = to + if by is not None: + self['by'] = by + + +class AnimateColor(Animate): + """ The **animateColor** element specifies a color transformation over + time. + """ + elementname = 'animateColor' + + +class AnimateTransform(Animate): + """ The **animateTransform** element animates a transformation attribute + on a target element, thereby allowing animations to control translation, + scaling, rotation and/or skewing. + """ + elementname = 'animateTransform' + def __init__(self, transform, element=None, **extra): + """ + :param element: target svg element, if element is not `None`; else + the target svg element is the parent svg element. + :param string transform: ``'translate | scale | rotate | skewX | skewY'`` + """ + super(AnimateTransform, self).__init__(element, **extra) + self['type'] = transform diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/base.py b/videollama2/lib/python3.10/site-packages/svgwrite/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f38cb38b587ea14257719a0d26778cdad18dccfc --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/base.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman +# Purpose: svg base element +# Created: 08.09.2010 +# Copyright (c) 2010-2020, Manfred Moitzi +# License: MIT License +""" +The **BaseElement** is the root for all SVG elements. +""" + +from svgwrite.etree import etree + +import copy + +from svgwrite.params import Parameter +from svgwrite.utils import AutoID + + +class BaseElement(object): + """ + The **BaseElement** is the root for all SVG elements. The SVG attributes + are stored in **attribs**, and the SVG subelements are stored in + **elements**. + + """ + elementname = 'baseElement' + + def __init__(self, **extra): + """ + :param extra: extra SVG attributes (keyword arguments) + + * add trailing '_' to reserved keywords: ``'class_'``, ``'from_'`` + * replace inner '-' by '_': ``'stroke_width'`` + + + SVG attribute names will be checked, if **debug** is `True`. + + workaround for removed **attribs** parameter in Version 0.2.2:: + + # replace + element = BaseElement(attribs=adict) + + #by + element = BaseElement() + element.update(adict) + + """ + # the keyword 'factory' specifies the object creator + factory = extra.pop('factory', None) + if factory is not None: + # take parameter from 'factory' + self._parameter = factory._parameter + else: + # default parameter debug=True profile='full' + self._parameter = Parameter() + + # override debug setting + debug = extra.pop('debug', None) + if debug is not None: + self._parameter.debug = debug + + # override profile setting + profile = extra.pop('profile', None) + if profile is not None: + self._parameter.profile = profile + + self.attribs = dict() + self.update(extra) + self.elements = list() + + def update(self, attribs): + """ Update SVG Attributes from `dict` attribs. + + Rules for keys: + + 1. trailing '_' will be removed (``'class_'`` -> ``'class'``) + 2. inner '_' will be replaced by '-' (``'stroke_width'`` -> ``'stroke-width'``) + + """ + for key, value in attribs.items(): + # remove trailing underscores + # and replace inner underscores + key = key.rstrip('_').replace('_', '-') + self.__setitem__(key, value) + + def copy(self): + newobj = copy.copy(self) # shallow copy of object + newobj.attribs = copy.copy(self.attribs) # shallow copy of attributes + newobj.elements = copy.copy(self.elements) # shallow copy of subelements + if 'id' in newobj.attribs: # create a new 'id' + newobj['id'] = newobj.next_id() + return newobj + + @property + def debug(self): + return self._parameter.debug + + @property + def profile(self): + return self._parameter.profile + + @property + def validator(self): + return self._parameter.validator + + @validator.setter + def validator(self, value): + self._parameter.validator = value + + @property + def version(self): + return self._parameter.get_version() + + def set_parameter(self, parameter): + self._parameter = parameter + + def next_id(self, value=None): + return AutoID.next_id(value) + + def get_id(self): + """ Get the object `id` string, if the object does not have an `id`, + a new `id` will be created. + + :returns: `string` + """ + if 'id' not in self.attribs: + self.attribs['id'] = self.next_id() + return self.attribs['id'] + + def get_iri(self): + """ + Get the `IRI` reference string of the object. (i.e., ``'#id'``). + + :returns: `string` + """ + return "#%s" % self.get_id() + + def get_funciri(self): + """ + Get the `FuncIRI` reference string of the object. (i.e. ``'url(#id)'``). + + :returns: `string` + """ + return "url(%s)" % self.get_iri() + + def __getitem__(self, key): + """ Get SVG attribute by `key`. + + :param string key: SVG attribute name + :return: SVG attribute value + + """ + return self.attribs[key] + + def __setitem__(self, key, value): + """ Set SVG attribute by `key` to `value`. + + :param string key: SVG attribute name + :param object value: SVG attribute value + + """ + # Attribute checking is only done by using the __setitem__() method or + # by self['attribute'] = value + if self.debug: + self.validator.check_svg_attribute_value(self.elementname, key, value) + self.attribs[key] = value + + def add(self, element): + """ Add an SVG element as subelement. + + :param element: append this SVG element + :returns: the added element + + """ + if self.debug: + self.validator.check_valid_children(self.elementname, element.elementname) + self.elements.append(element) + return element + + def tostring(self): + """ Get the XML representation as unicode `string`. + + :return: unicode XML string of this object and all its subelements + + """ + xml = self.get_xml() + # required for Python 2 support + xml_utf8_str = etree.tostring(xml, encoding='utf-8') + return xml_utf8_str.decode('utf-8') + # just Python 3: return etree.tostring(xml, encoding='unicode') + + def _repr_svg_(self): + """ Show SVG in IPython, Jupyter Notebook, and Jupyter Lab + + :return: unicode XML string of this object and all its subelements + + """ + return self.tostring() + + def get_xml(self): + """ Get the XML representation as `ElementTree` object. + + :return: XML `ElementTree` of this object and all its subelements + + """ + xml = etree.Element(self.elementname) + if self.debug: + self.validator.check_all_svg_attribute_values(self.elementname, self.attribs) + for attribute, value in sorted(self.attribs.items()): + # filter 'None' values + if value is not None: + value = self.value_to_string(value) + if value: # just add not empty attributes + xml.set(attribute, value) + + for element in self.elements: + xml.append(element.get_xml()) + return xml + + def value_to_string(self, value): + """ + Converts *value* into a includes a value check, depending + on :attr:`self.debug` and :attr:`self.profile`. + + """ + if isinstance(value, (int, float)): + if self.debug: + self.validator.check_svg_type(value, 'number') + if isinstance(value, float) and self.profile == 'tiny': + value = round(value, 4) + return str(value) + + def set_desc(self, title=None, desc=None): + """ Insert a **title** and/or a **desc** element as first subelement. + """ + if desc is not None: + self.elements.insert(0, Desc(desc)) + if title is not None: + self.elements.insert(0, Title(title)) + + def set_metadata(self, xmldata): + """ + :param xmldata: an xml.etree.ElementTree - Element() object. + """ + metadata = Metadata(xmldata) + if len(self.elements) == 0: + self.elements.append(metadata) + else: + pos = 0 + while self.elements[pos].elementname in ('title', 'desc'): + pos += 1 + if pos == len(self.elements): + self.elements.append(metadata) + return + if self.elements[pos].elementname == 'metadata': + self.elements[pos].xml.append(xmldata) + else: + self.elements.insert(pos, metadata) + + +class Title(object): + elementname = 'title' + + def __init__(self, text): + self.xml = etree.Element(self.elementname) + self.xml.text = str(text) + + def get_xml(self): + return self.xml + + +class Desc(Title): + elementname = 'desc' + + +class Metadata(Title): + elementname = 'metadata' + + def __init__(self, xmldata): + """ + :param xmldata: an xml.etree.ElementTree - Element() object. + """ + self.xml = etree.Element('metadata') + self.xml.append(xmldata) diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__init__.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c2b93bd350d785ea51e544055b35505c8cb66bd Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/colors.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/colors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89b9c646f76798736c3541ccc56d2ea0a5cd240c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/colors.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/full11.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/full11.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e11595415ff457164caefba721d6ec82777430ee Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/full11.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/pattern.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/pattern.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6244e3e28bf04ca6719c3ab4a81e00da3d909245 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/pattern.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/tiny12.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/tiny12.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2605cdb17abfdcf1d12ad1449fd98871674e9f1 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/tiny12.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/typechecker.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/typechecker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5ceae1e3910ca5927e794609d90d574a014f2a4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/typechecker.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/types.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec3844f9995e865f5fe8e0936febe93d1d84b108 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/types.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/colors.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..7672194e308a9a22e230da36960ea96669af9b65 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/colors.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: colornames +# Created: 06.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +colornames = frozenset([ + 'aliceblue', + 'antiquewhite', + 'aqua', + 'aquamarine', + 'azure', + 'beige', + 'bisque', + 'black', + 'blanchedalmond', + 'blue', + 'blueviolet', + 'brown', + 'burlywood', + 'cadetblue', + 'chartreuse', + 'chocolate', + 'coral', + 'cornflowerblue', + 'cornsilk', + 'crimson', + 'cyan', + 'darkblue', + 'darkcyan', + 'darkgoldenrod', + 'darkgray', + 'darkgreen', + 'darkgrey', + 'darkkhaki', + 'darkmagenta', + 'darkolivegreen', + 'darkorange', + 'darkorchid', + 'darkred', + 'darksalmon', + 'darkseagreen', + 'darkslateblue', + 'darkslategray', + 'darkslategrey', + 'darkturquoise', + 'darkviolet', + 'deeppink', + 'deepskyblue', + 'dimgray', + 'dimgrey', + 'dodgerblue', + 'firebrick', + 'floralwhite', + 'forestgreen', + 'fuchsia', + 'gainsboro', + 'ghostwhite', + 'gold', + 'goldenrod', + 'gray', + 'green', + 'greenyellow', + 'grey', + 'honeydew', + 'hotpink', + 'indianred', + 'indigo', + 'ivory', + 'khaki', + 'lavender', + 'lavenderblush', + 'lawngreen', + 'lemonchiffon', + 'lightblue', + 'lightcoral', + 'lightcyan', + 'lightgoldenrodyellow', + 'lightgray', + 'lightgreen', + 'lightgrey', + 'lightpink', + 'lightsalmon', + 'lightseagreen', + 'lightskyblue', + 'lightslategray', + 'lightslategrey', + 'lightsteelblue', + 'lightyellow', + 'lime', + 'limegreen', + 'linen', + 'magenta', + 'maroon', + 'mediumaquamarine', + 'mediumblue', + 'mediumorchid', + 'mediumpurple', + 'mediumseagreen', + 'mediumslateblue', + 'mediumspringgreen', + 'mediumturquoise', + 'mediumvioletred', + 'midnightblue', + 'mintcream', + 'mistyrose', + 'moccasin', + 'navajowhite', + 'navy', + 'oldlace', + 'olive', + 'olivedrab', + 'orange', + 'orangered', + 'orchid', + 'palegoldenrod', + 'palegreen', + 'paleturquoise', + 'palevioletred', + 'papayawhip', + 'peachpuff', + 'peru', + 'pink', + 'plum', + 'powderblue', + 'purple', + 'red', + 'rosybrown', + 'royalblue', + 'saddlebrown', + 'salmon', + 'sandybrown', + 'seagreen', + 'seashell', + 'sienna', + 'silver', + 'skyblue', + 'slateblue', + 'slategray', + 'slategrey', + 'snow', + 'springgreen', + 'steelblue', + 'tan', + 'teal', + 'thistle', + 'tomato', + 'turquoise', + 'violet', + 'wheat', + 'white', + 'whitesmoke', + 'yellow', + 'yellowgreen',]) diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/full11.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/full11.py new file mode 100644 index 0000000000000000000000000000000000000000..fe07995aa4c141027e196f2575544455a6411a24 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/full11.py @@ -0,0 +1,1405 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: full11 data +# Created: 15.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.data.types import SVGAttribute, SVGMultiAttribute +from svgwrite.data.types import SVGElement +from svgwrite.data.typechecker import Full11TypeChecker as TypeChecker + +empty_list = [] + +attributes = { +'accent-height': SVGAttribute('accent-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'accumulate': SVGAttribute('accumulate', anim=False, + types=empty_list, + const=frozenset(['none', 'sum'])), +'additive': SVGAttribute('additive', anim=False, + types=empty_list, + const=frozenset(['sum', 'replace'])), +'alignment-baseline': SVGAttribute('alignment-baseline', anim=True, + types=empty_list, + const=frozenset(['mathematical', 'before-edge', 'central', 'baseline', + 'auto', 'hanging', 'ideographic', 'inherit', 'middle', + 'alphabetic', 'text-before-edge', 'text-after-edge', + 'after-edge'])), +'alphabetic': SVGAttribute('alphabetic', anim=False, + types=frozenset(['number']), + const=empty_list), +'amplitude': SVGAttribute('amplitude', anim=True, + types=frozenset(['number']), + const=empty_list), +'arabic-form': SVGAttribute('arabic-form', anim=False, + types=empty_list, + const=frozenset(['terminal', 'initial', 'isolated', 'medial'])), +'ascent': SVGAttribute('ascent', anim=False, + types=frozenset(['number']), + const=empty_list), +'attributeName': SVGAttribute('attributeName', anim=False, + types=frozenset(['name']), + const=empty_list), +'attributeType': SVGAttribute('attributeType', anim=False, + types=empty_list, + const=frozenset(['XML', 'auto', 'CSS'])), +'azimuth': SVGAttribute('azimuth', anim=True, + types=frozenset(['number']), + const=empty_list), +'baseFrequency': SVGAttribute('baseFrequency', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'baseline-shift': SVGAttribute('baseline-shift', anim=True, + types=frozenset(['percentage', 'length']), + const=frozenset(['super', 'baseline', 'inherit', 'sub'])), +'baseProfile': SVGAttribute('baseProfile', anim=False, + types=empty_list, + const=frozenset(['full', 'tiny', 'basic', 'none'])), +'bbox': SVGAttribute('bbox', anim=False, + types=frozenset(['string']), + const=empty_list), +'begin': SVGAttribute('begin', anim=True, + types=frozenset(['timing-value-list']), + const=frozenset(['indefinite'])), +'bias': SVGAttribute('bias', anim=True, + types=frozenset(['number']), + const=empty_list), +'by': SVGAttribute('by', anim=False, + types=frozenset(['string']), + const=empty_list), +'calcMode': SVGAttribute('calcMode', anim=False, + types=empty_list, + const=frozenset(['discrete', 'linear', 'paced', 'spline'])), +'cap-height': SVGAttribute('cap-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'class': SVGAttribute('class', anim=True, + types=frozenset(['list-of-name']), + const=empty_list), +'clip': SVGAttribute('clip', anim=True, + types=frozenset(['shape']), + const=frozenset(['auto', 'inherit'])), +'clip-path': SVGAttribute('clip-path', anim=True, + types=frozenset(['IRI']), + const=frozenset(['none', 'inherit'])), +'clip-rule': SVGAttribute('clip-rule', anim=True, + types=empty_list, + const=frozenset(['nonzero', 'evenodd', 'inherit'])), +'clipPathUnits': SVGAttribute('clipPathUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'color': SVGAttribute('color', anim=True, + types=frozenset(['color']), + const=frozenset(['inherit'])), +'color-interpolation': SVGAttribute('color-interpolation', anim=True, + types=empty_list, + const=frozenset(['auto', 'sRGB', 'inherit', 'linearRGB'])), +'color-interpolation-filters': SVGAttribute('color-interpolation-filters', anim=True, + types=empty_list, + const=frozenset(['auto', 'sRGB', 'inherit', 'linearRGB'])), +'color-profile': SVGAttribute('color-profile', anim=True, + types=frozenset(['FuncIRI', 'name']), + const=frozenset(['auto', 'sRGB', 'inherit'])), +'color-rendering': SVGAttribute('color-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeQuality', 'optimizeSpeed', 'inherit'])), +'contentScriptType': SVGAttribute('contentScriptType', anim=True, + types=frozenset(['string']), + const=empty_list), +'contentStyleType': SVGAttribute('contentStyleType', anim=True, + types=frozenset(['string']), + const=empty_list), +'cursor': SVGAttribute('cursor', anim=True, + types=frozenset(['list-of-FuncIRI']), + const=frozenset(['sw-resize', 'n-resize', 'help', 'text', 'move', 'auto', + 'w-resize', 'pointer', 'wait', 's-resize', 'e-resize', + 'default', 'inherit', 'nw-resize', 'ne-resize', + 'crosshair', 'se-resize'])), +'cx': SVGAttribute('cx', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'cy': SVGAttribute('cy', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'d': SVGMultiAttribute({ + '* path': SVGAttribute( # '*' means default attribute + 'd', anim=True, + types=frozenset(['path-data']), + const=empty_list + ), + 'glyph missing-glyph': SVGAttribute( + 'd', anim=False, + types=frozenset(['path-data']), + const=empty_list + ), + }), +'descent': SVGAttribute('descent', anim=False, + types=frozenset(['number']), + const=empty_list), +'diffuseConstant': SVGAttribute('diffuseConstant', anim=True, + types=frozenset(['number']), + const=empty_list), +'direction': SVGAttribute('direction', anim=False, + types=empty_list, + const=frozenset(['ltr', 'inherit', 'rtl'])), +'display': SVGAttribute('display', anim=True, + types=empty_list, + const=frozenset(['inline-table', 'table-header-group', 'table-footer-group', + 'none', 'table-row', 'table-caption', 'table-column', + 'marker', 'table', 'compact', 'table-row-group', 'run-in', + 'inherit', 'list-item', 'table-cell', 'inline', + 'block', 'table-column-group'])), +'divisor': SVGAttribute('divisor', anim=True, + types=frozenset(['number']), + const=empty_list), +'dominant-baseline': SVGAttribute('dominant-baseline', anim=True, + types=empty_list, + const=frozenset(['mathematical', 'use-script', 'ideographic', 'central', + 'reset-size', 'auto', 'hanging', 'inherit', 'middle', + 'alphabetic', 'text-before-edge', 'text-after-edge', + 'no-change'])), +'dur': SVGAttribute('dur', anim=True, + types=frozenset(['time']), + const=frozenset(['media', 'indefinite'])), +'dx': SVGMultiAttribute({ + '* altGlyph text tref tspan': SVGAttribute( + 'dx', anim=True, + types=frozenset(['list-of-length']), + const=empty_list), + 'feOffset': SVGAttribute( + 'dx', anim=True, + types=frozenset(['number']), + const=empty_list), + 'glyphRef': SVGAttribute( + 'dx', anim=False, + types=frozenset(['number']), + const=empty_list), + }), +'dy': SVGMultiAttribute({ + '* altGlyph text tref tspan': SVGAttribute( + 'dy', anim=True, + types=frozenset(['list-of-length']), + const=empty_list), + 'feOffset': SVGAttribute( + 'dy', anim=True, + types=frozenset(['number']), + const=empty_list), + 'glyphRef': SVGAttribute( + 'dy', anim=False, + types=frozenset(['number']), + const=empty_list), + }), +'edgeMode': SVGAttribute('edgeMode', anim=True, + types=empty_list, + const=frozenset(['wrap', 'duplicate', 'none'])), +'elevation': SVGAttribute('elevation', anim=True, + types=frozenset(['number']), + const=empty_list), +'enable-background': SVGAttribute('enable-background', anim=True, + types=frozenset(['string']), + const=frozenset(['accummulate', 'new', 'inherit'])), +'end': SVGAttribute('end', anim=False, + types=frozenset(['timing-value-list']), + const=frozenset(['indefinite'])), +'exponent': SVGAttribute('exponent', anim=True, + types=frozenset(['number']), + const=empty_list), +'externalResourcesRequired': SVGAttribute('externalResourcesRequired', anim=True, + types=empty_list, + const=frozenset(['true', 'false'])), +'fill': SVGMultiAttribute({ + '*': SVGAttribute( + 'fill', anim=True, + types=frozenset(['paint']), + const=empty_list), + 'set animateMotion animate animateColor animateTransform': SVGAttribute( + 'fill', anim=False, + types=empty_list, + const=frozenset(['freeze', 'remove'])) + }), +'fill-opacity': SVGAttribute('fill-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'fill-rule': SVGAttribute('fill-rule', anim=True, + types=empty_list, + const=frozenset(['nonzero', 'evenodd', 'inherit'])), +'filter': SVGAttribute('filter', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'filterRes': SVGAttribute('filterRes', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'filterUnits': SVGAttribute('filterUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'flood-color': SVGAttribute('flood-color', anim=True, + types=frozenset(['color', 'icccolor']), + const=frozenset(['currentColor', 'inherit'])), +'flood-opacity': SVGAttribute('flood-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'font': SVGAttribute('font', anim=True, + types=frozenset(['string']), + const=empty_list), +'font-family': SVGAttribute('font-family', anim=False, + types=frozenset(['string']), + const=empty_list), +'font-size': SVGAttribute('font-size', anim=False, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'font-size-adjust': SVGAttribute('font-size-adjust', anim=True, + types=frozenset(['number']), + const=frozenset(['none', 'inherit'])), +'font-stretch': SVGAttribute('font-stretch', anim=False, + types=empty_list, + const=frozenset(['condensed', 'normal', 'ultra-condensed', 'expanded', + 'narrower', 'inherit', 'semi-condensed', 'extra-condensed', + 'ultra-expanded', 'wider', 'semi-expanded', 'extra-expanded'])), +'font-style': SVGAttribute('font-style', anim=False, + types=empty_list, + const=frozenset(['oblique', 'inherit', 'italic', 'normal'])), +'font-variant': SVGAttribute('font-variant', anim=False, + types=empty_list, + const=frozenset(['small-caps', 'inherit', 'normal'])), +'font-weight': SVGAttribute('font-weight', anim=False, + types=empty_list, + const=frozenset(['200', '900', 'bold', 'bolder', 'normal', '300', '700', + 'inherit', 'lighter', '400', '100', '800', '500', '600'])), +'format': SVGAttribute('format', anim=False, + types=frozenset(['string']), + const=empty_list), +'from': SVGAttribute('from', anim=False, + types=frozenset(['string']), + const=empty_list), +'fx': SVGAttribute('fx', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'fy': SVGAttribute('fy', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'g1': SVGAttribute('g1', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'g2': SVGAttribute('g2', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'glyph-name': SVGAttribute('glyph-name', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'glyph-orientation-horizontal': SVGAttribute('glyph-orientation-horizontal', anim=True, + types=frozenset(['angle']), + const=frozenset(['inherit'])), +'glyph-orientation-vertical': SVGAttribute('glyph-orientation-vertical', anim=True, + types=frozenset(['angle']), + const=frozenset(['auto', 'inherit'])), +'glyphRef': SVGAttribute('glyphRef', anim=False, + types=frozenset(['string']), + const=empty_list), +'gradientTransform': SVGAttribute('gradientTransform', anim=True, + types=frozenset(['transform-list']), + const=empty_list), +'gradientUnits': SVGAttribute('gradientUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'hanging': SVGAttribute('hanging', anim=False, + types=frozenset(['number']), + const=empty_list), +'height': SVGAttribute('height', anim=True, + types=frozenset(['length']), + const=empty_list), +'horiz-adv-x': SVGAttribute('horiz-adv-x', anim=False, + types=frozenset(['number']), + const=empty_list), +'horiz-origin-x': SVGAttribute('horiz-origin-x', anim=False, + types=frozenset(['number']), + const=empty_list), +'horiz-origin-y': SVGAttribute('horiz-origin-y', anim=False, + types=frozenset(['number']), + const=empty_list), +'id': SVGAttribute('id', anim=False, + types=frozenset(['name']), + const=empty_list), +'ideographic': SVGAttribute('ideographic', anim=False, + types=frozenset(['number']), + const=empty_list), +'image-rendering': SVGAttribute('image-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeQuality', 'optimizeSpeed', 'inherit'])), +'in': SVGAttribute('in', anim=True, + types=frozenset(['name']), + const=frozenset(['SourceAlpha', 'SourceGraphic', 'BackgroundAlpha', + 'BackgroundImage', 'StrokePaint', 'FillPaint'])), +'in2': SVGAttribute('in2', anim=True, + types=frozenset(['name']), + const=frozenset(['SourceAlpha', 'SourceGraphic', 'BackgroundAlpha', + 'BackgroundImage', 'StrokePaint', 'FillPaint'])), +'intercept': SVGAttribute('intercept', anim=True, + types=frozenset(['number']), + const=empty_list), +'k': SVGAttribute('k', anim=False, + types=frozenset(['number']), + const=empty_list), +'k1': SVGAttribute('k1', anim=True, + types=frozenset(['number']), + const=empty_list), +'k2': SVGAttribute('k2', anim=True, + types=frozenset(['number']), + const=empty_list), +'k3': SVGAttribute('k3', anim=True, + types=frozenset(['number']), + const=empty_list), +'k4': SVGAttribute('k4', anim=True, + types=frozenset(['number']), + const=empty_list), +'kernelMatrix': SVGAttribute('kernelMatrix', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), +'kernelUnitLength': SVGAttribute('kernelUnitLength', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'kerning': SVGAttribute('kerning', anim=True, + types=frozenset(['length']), + const=frozenset(['auto', 'inherit'])), +'keyPoints': SVGAttribute('keyPoints', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'keySplines': SVGAttribute('keySplines', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'keyTimes': SVGAttribute('keyTimes', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'lang': SVGAttribute('lang', anim=False, + types=frozenset(['name']), + const=empty_list), +'lengthAdjust': SVGAttribute('lengthAdjust', anim=True, + types=empty_list, + const=frozenset(['spacingAndGlyphs', 'spacing'])), +'letter-spacing': SVGAttribute('letter-spacing', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit', 'normal'])), +'lighting-color': SVGAttribute('lighting-color', anim=True, + types=frozenset(['color', 'icccolor']), + const=frozenset(['currentColor', 'inherit'])), +'limitingConeAngle': SVGAttribute('limitingConeAngle', anim=True, + types=frozenset(['number']), + const=empty_list), +'local': SVGAttribute('local', anim=True, + types=frozenset(['string']), + const=empty_list), +'marker': SVGAttribute('marker', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'marker-end': SVGAttribute('marker-end', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'marker-mid': SVGAttribute('marker-mid', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'marker-start': SVGAttribute('marker-start', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'markerHeight': SVGAttribute('markerHeight', anim=True, + types=frozenset(['length']), + const=empty_list), +'markerUnits': SVGAttribute('markerUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'strokeWidth'])), +'markerWidth': SVGAttribute('markerWidth', anim=True, + types=frozenset(['length']), + const=empty_list), +'mask': SVGAttribute('mask', anim=True, + types=frozenset(['FuncIRI']), + const=frozenset(['none', 'inherit'])), +'maskContentUnits': SVGAttribute('maskContentUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'maskUnits': SVGAttribute('maskUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'mathematical': SVGAttribute('mathematical', anim=False, + types=frozenset(['number']), + const=empty_list), +'max': SVGAttribute('max', anim=False, + types=frozenset(['time']), + const=frozenset(['media'])), +'media': SVGAttribute('media', anim=False, + types=empty_list, + const=frozenset(['all', 'aureal', 'braille', 'embossed', 'handheld', 'print', + 'projection', 'screen', 'tty', 'tv'])), +'method': SVGAttribute('method', anim=True, + types=empty_list, + const=frozenset(['stretch', 'align'])), +'min': SVGAttribute('min', anim=False, + types=frozenset(['time']), + const=frozenset(['media'])), +'mode': SVGAttribute('mode', anim=True, + types=empty_list, + const=frozenset(['multiply', 'screen', 'darken', 'lighten', 'normal'])), +'name': SVGMultiAttribute({ + '* font-face-name': SVGAttribute( + 'name', anim=False, + types=frozenset(['anything']), + const=empty_list), + 'color-profile': SVGAttribute( + 'name', anim=False, + types=frozenset(['name']), + const=empty_list), + }), +'numOctaves': SVGAttribute('numOctaves', anim=True, + types=frozenset(['integer']), + const=empty_list), +'offset': SVGMultiAttribute({ + '*': SVGAttribute( + 'offset', anim=True, + types=frozenset(['number']), + const=empty_list), + 'stop': SVGAttribute( + 'offset', anim=True, + types=frozenset(['number', 'percentage']), + const=empty_list), + }), +'onabort': SVGAttribute('onabort', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onactivate': SVGAttribute('onactivate', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onbegin': SVGAttribute('onbegin', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onclick': SVGAttribute('onclick', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onend': SVGAttribute('onend', anim=True, + types=frozenset(['anything']), + const=empty_list), +'onerror': SVGAttribute('onerror', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onfocusin': SVGAttribute('onfocusin', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onfocusout': SVGAttribute('onfocusout', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onload': SVGAttribute('onload', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onmousedown': SVGAttribute('onmousedown', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onmousemove': SVGAttribute('onmousemove', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onmouseout': SVGAttribute('onmouseout', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onmouseover': SVGAttribute('onmouseover', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onmouseup': SVGAttribute('onmouseup', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onrepeat': SVGAttribute('onrepeat', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onresize': SVGAttribute('onresize', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onscroll': SVGAttribute('onscroll', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onunload': SVGAttribute('onunload', anim=False, + types=frozenset(['anything']), + const=empty_list), +'onzoom': SVGAttribute('onzoom', anim=False, + types=frozenset(['anything']), + const=empty_list), +'opacity': SVGAttribute('opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'operator': SVGMultiAttribute({ + '* feComposite': SVGAttribute( + 'operator', anim=True, + types=empty_list, + const=frozenset(['xor', 'in', 'over', 'atop', 'arithmetic', 'out'])), + 'feMorphology': SVGAttribute( + 'operator', anim=True, + types=empty_list, + const=frozenset(['erode', 'dilate'])), + }), +'order': SVGAttribute('order', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'orient': SVGAttribute('orient', anim=True, + types=frozenset(['angle']), + const=frozenset(['auto'])), +'orientation': SVGAttribute('orientation', anim=False, + types=empty_list, + const=frozenset(['h', 'v'])), +'origin': SVGAttribute('origin', anim=False, + types=empty_list, + const=frozenset(['default'])), +'overflow': SVGAttribute('overflow', anim=True, + types=empty_list, + const=frozenset(['visible', 'hidden', 'scroll', 'inherit', 'auto'])), +'overline-position': SVGAttribute('overline-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'overline-thickness': SVGAttribute('overline-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'panose-1': SVGAttribute('panose-1', anim=False, + types=frozenset(['list-of-integer']), + const=empty_list), +'path': SVGAttribute('path', anim=False, + types=frozenset(['path-data']), + const=empty_list), +'pathLength': SVGAttribute('pathLength', anim=True, + types=frozenset(['number']), + const=empty_list), +'patternContentUnits': SVGAttribute('patternContentUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'patternTransform': SVGAttribute('patternTransform', anim=True, + types=frozenset(['transform-list']), + const=empty_list), +'patternUnits': SVGAttribute('patternUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'pointer-events': SVGAttribute('pointer-events', anim=True, + types=empty_list, + const=frozenset(['all', 'visibleStroke', 'painted', 'none', 'visibleFill', + 'visible', 'stroke', 'inherit', 'visiblePainted', 'fill'])), +'points': SVGAttribute('points', anim=True, + types=frozenset(['list-of-points']), + const=empty_list), +'pointsAtX': SVGAttribute('pointsAtX', anim=True, + types=frozenset(['number']), + const=empty_list), +'pointsAtY': SVGAttribute('pointsAtY', anim=True, + types=frozenset(['number']), + const=empty_list), +'pointsAtZ': SVGAttribute('pointsAtZ', anim=True, + types=frozenset(['number']), + const=empty_list), +'preserveAlpha': SVGAttribute('preserveAlpha', anim=True, + types=empty_list, + const=frozenset(['true', 'false'])), +'preserveAspectRatio': SVGAttribute('preserveAspectRatio', anim=True, + types=frozenset('string'), + const=empty_list), +'primitiveUnits': SVGAttribute('primitiveUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'r': SVGAttribute('r', anim=True, + types=frozenset(['length']), + const=empty_list), +'radius': SVGAttribute('radius', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'refX': SVGAttribute('refX', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'refY': SVGAttribute('refY', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'rendering-intent': SVGAttribute('rendering-intent', anim=False, + types=empty_list, + const=frozenset(['auto', 'saturation', 'perceptual', 'relative-colorimetric', + 'absolute-colorimetric'])), +'repeatCount': SVGAttribute('repeatCount', anim=False, + types=frozenset(['number']), + const=frozenset(['indefinite'])), +'repeatDur': SVGAttribute('repeatDur', anim=False, + types=frozenset(['time']), + const=frozenset(['indefinite'])), +'requiredExtensions': SVGAttribute('requiredExtensions', anim=False, + types=frozenset(['string']), + const=empty_list), +'requiredFeatures': SVGAttribute('requiredFeatures', anim=False, + types=frozenset(['string']), + const=empty_list), +'restart': SVGAttribute('restart', anim=False, + types=empty_list, + const=frozenset(['always', 'never', 'whenNotActive'])), +'result': SVGAttribute('result', anim=True, + types=frozenset(['list-of-name']), + const=empty_list), +'rotate': SVGMultiAttribute({ + '* altGlyph text tref tspan': SVGAttribute( + 'rotate', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), + 'animateMotion': SVGAttribute( + 'rotate', anim=False, + types=frozenset(['number']), + const=frozenset(['auto', 'auto-reverse'])), + }), +'rx': SVGAttribute('rx', anim=True, + types=frozenset(['length']), + const=empty_list), +'ry': SVGAttribute('ry', anim=True, + types=frozenset(['length']), + const=empty_list), +'scale': SVGAttribute('scale', anim=True, + types=frozenset(['number']), + const=empty_list), +'seed': SVGAttribute('seed', anim=True, + types=frozenset(['number']), + const=empty_list), +'shape-rendering': SVGAttribute('shape-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'inherit', 'geometricPrecision', + 'crispEdges'])), +'slope': SVGMultiAttribute({ + '*': SVGAttribute( + 'slope', anim=True, + types=frozenset(['number']), + const=empty_list), + 'font-face': SVGAttribute( + 'slope', anim=False, + types=frozenset(['number']), + const=empty_list), + }), +'spacing': SVGAttribute('spacing', anim=True, + types=empty_list, + const=frozenset(['auto', 'exact'])), +'specularConstant': SVGAttribute('specularConstant', anim=True, + types=frozenset(['number']), + const=empty_list), +'specularExponent': SVGAttribute('specularExponent', anim=True, + types=frozenset(['number']), + const=empty_list), +'spreadMethod': SVGAttribute('spreadMethod', anim=True, + types=empty_list, + const=frozenset(['reflect', 'repeat', 'pad'])), +'startOffset': SVGAttribute('startOffset', anim=True, + types=frozenset(['length']), + const=empty_list), +'stdDeviation': SVGAttribute('stdDeviation', anim=True, + types=frozenset(['number-optional-number']), + const=empty_list), +'stemh': SVGAttribute('stemh', anim=False, + types=frozenset(['number']), + const=empty_list), +'stemv': SVGAttribute('stemv', anim=False, + types=frozenset(['number']), + const=empty_list), +'stitchTiles': SVGAttribute('stitchTiles', anim=True, + types=empty_list, + const=frozenset(['noStitch', 'stitch'])), +'stop-color': SVGAttribute('stop-color', anim=True, + types=frozenset(['color', 'icccolor']), + const=frozenset(['currentColor', 'inherit'])), +'stop-opacity': SVGAttribute('stop-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'strikethrough-position': SVGAttribute('strikethrough-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'strikethrough-thickness': SVGAttribute('strikethrough-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'string': SVGAttribute('string', anim=False, + types=frozenset('anything'), + const=empty_list), +'stroke': SVGAttribute('stroke', anim=True, + types=frozenset(['paint']), + const=empty_list), +'stroke-dasharray': SVGAttribute('stroke-dasharray', anim=True, + types=frozenset(['list-of-length']), + const=frozenset(['none', 'inherit'])), +'stroke-dashoffset': SVGAttribute('stroke-dashoffset', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'stroke-linecap': SVGAttribute('stroke-linecap', anim=True, + types=empty_list, + const=frozenset(['square', 'round', 'inherit', 'butt'])), +'stroke-linejoin': SVGAttribute('stroke-linejoin', anim=True, + types=empty_list, + const=frozenset(['bevel', 'miter', 'round', 'inherit'])), +'stroke-miterlimit': SVGAttribute('stroke-miterlimit', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'stroke-opacity': SVGAttribute('stroke-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'stroke-width': SVGAttribute('stroke-width', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'style': SVGAttribute('style', anim=False, + types=frozenset('anything'), + const=empty_list), +'surfaceScale': SVGAttribute('surfaceScale', anim=True, + types=frozenset(['number']), + const=empty_list), +'systemLanguage': SVGAttribute('systemLanguage', anim=False, + types=frozenset(['string']), + const=empty_list), +'tableValues': SVGAttribute('tableValues', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), +'target': SVGAttribute('target', anim=True, + types=frozenset(['XML-Name']), + const=frozenset(['_replace', '_self', '_parent', '_top', '_blank'])), +'targetX': SVGAttribute('targetX', anim=True, + types=frozenset(['integer']), + const=empty_list), +'targetY': SVGAttribute('targetY', anim=True, + types=frozenset(['integer']), + const=empty_list), +'text-anchor': SVGAttribute('text-anchor', anim=True, + types=empty_list, + const=frozenset(['start', 'end', 'inherit', 'middle'])), +'text-decoration': SVGAttribute('text-decoration', anim=True, + types=frozenset(['list-of-text-decoration-style']), + const=frozenset(['', 'none', 'inherit'])), +'text-rendering': SVGAttribute('text-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'optimizeLegibility', + 'geometricPrecision', 'inherit'])), +'textLength': SVGAttribute('textLength', anim=True, + types=frozenset(['length']), + const=empty_list), +'title': SVGAttribute('title', anim=False, + types=frozenset(['string']), + const=empty_list), +'to': SVGAttribute('to', anim=False, + types=frozenset(['string']), + const=empty_list), +'transform': SVGAttribute('transform', anim=True, + types=frozenset(['transform-list']), + const=empty_list), +'type': SVGMultiAttribute({ + '* feColorMatrix': SVGAttribute( + 'type', anim=True, + types=empty_list, + const=frozenset(['matrix', 'saturate', 'hueRotate', 'luminanceToAlpha'])), + 'feTurbulence': SVGAttribute( + 'type', anim=True, + types=empty_list, + const=frozenset(['fractalNoise', 'turbulence'])), + 'feFuncR feFuncG feFuncB feFuncA': SVGAttribute( + 'type', anim=True, + types=empty_list, + const=frozenset(['identity', 'table', 'discrete', 'linear', 'gamma'])), + 'script style': SVGAttribute( + 'type', anim=False, + types=frozenset(['content-type']), + const=empty_list), + 'animateTransform': SVGAttribute( + 'type', anim=False, + types=empty_list, + const=frozenset(['translate', 'scale', 'rotate', 'skewX', 'skewY'])), + }), +'u1': SVGAttribute('u1', anim=False, + types=frozenset(['string']), + const=empty_list), +'u2': SVGAttribute('u2', anim=False, + types=frozenset(['string']), + const=empty_list), +'underline-position': SVGAttribute('underline-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'underline-thickness': SVGAttribute('underline-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'unicode': SVGAttribute('unicode', anim=False, + types=frozenset(['string']), + const=empty_list), +'unicode-bidi': SVGAttribute('unicode-bidi', anim=False, + types=empty_list, + const=frozenset(['embed', 'inherit', 'bidi-override', 'normal'])), +'unicode-range': SVGAttribute('unicode-range', anim=False, + types=frozenset(['string']), + const=empty_list), +'units-per-em': SVGAttribute('units-per-em', anim=False, + types=frozenset(['number']), + const=empty_list), +'v-alphabetic': SVGAttribute('v-alphabetic', anim=False, + types=frozenset(['number']), + const=empty_list), +'v-hanging': SVGAttribute('v-hanging', anim=False, + types=frozenset(['number']), + const=empty_list), +'v-ideographic': SVGAttribute('v-ideographic', anim=False, + types=frozenset(['number']), + const=empty_list), +'v-mathematical': SVGAttribute('v-mathematical', anim=False, + types=frozenset(['number']), + const=empty_list), +'values': SVGMultiAttribute({ + '*': SVGAttribute( + 'values', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), + 'feColorMatrix': SVGAttribute( + 'values', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), + }), +'version': SVGAttribute('version', anim=False, + types=empty_list, + const=frozenset(['1.1', '1.2'])), +'vert-adv-y': SVGAttribute('vert-adv-y', anim=False, + types=frozenset(['number']), + const=empty_list), +'vert-origin-x': SVGAttribute('vert-origin-x', anim=False, + types=frozenset(['number']), + const=empty_list), +'vert-origin-y': SVGAttribute('vert-origin-y', anim=False, + types=frozenset(['number']), + const=empty_list), +'viewBox': SVGAttribute('viewBox', anim=True, + types=frozenset(['four-numbers']), + const=empty_list), +'viewTarget': SVGAttribute('viewTarget', anim=False, + types=frozenset(['list-of-XML-Name']), + const=empty_list), +'visibility': SVGAttribute('visibility', anim=True, + types=empty_list, + const=frozenset(['visible', 'hidden', 'collapse', 'inherit'])), +'width': SVGAttribute('width', anim=True, + types=frozenset(['length']), + const=empty_list), +'widths': SVGAttribute('widths', anim=False, + types=frozenset(['string']), + const=empty_list), +'word-spacing': SVGAttribute('word-spacing', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit', 'normal'])), +'writing-mode': SVGAttribute('writing-mode', anim=False, + types=empty_list, + const=frozenset(['rl-tb', 'lr', 'rl', 'tb-rl', 'lr-tb', 'inherit', 'tb'])), +'x': SVGMultiAttribute({ + '*': SVGAttribute( + 'x', anim=True, + types=frozenset(['coordinate']), + const=empty_list), + 'altGlyph text tref tspan': SVGAttribute( + 'x', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), + 'fePointLight feSpotLight glyphRef': SVGAttribute( + 'x', anim=True, + types=frozenset(['number']), + const=empty_list), + }), +'x-height': SVGAttribute('x-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'x1': SVGAttribute('x1', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), +'x2': SVGAttribute('x2', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), +'xChannelSelector': SVGAttribute('xChannelSelector', anim=True, + types=empty_list, + const=frozenset(['A', 'B', 'R', 'G'])), +'xlink:actuate': SVGMultiAttribute({ + '*': SVGAttribute( + 'xlink:actuate', anim=False, + types=empty_list, + const=frozenset(['onLoad'])), + 'a': SVGAttribute( + 'xlink:actuate', anim=False, + types=empty_list, + const=frozenset(['onRequest'])), + }), +'xlink:arcrole': SVGAttribute('xlink:arcrole', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xlink:href': SVGAttribute('xlink:href', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xlink:role': SVGAttribute('xlink:role', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xlink:show': SVGMultiAttribute({ + '*': SVGAttribute( + 'xlink:show', anim=False, + types=empty_list, + const=frozenset(['other', 'new', 'replace', 'none', 'embed'])), + 'a': SVGAttribute( + 'xlink:show', anim=False, + types=empty_list, + const=frozenset(['new', 'replace'])), + }), +'xlink:title': SVGAttribute('xlink:title', anim=False, + types=frozenset(['string']), + const=empty_list), +'xlink:type': SVGAttribute('xlink:type', anim=False, + types=empty_list, + const=frozenset(['simple'])), +'xmlns': SVGAttribute('xmlns', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xmlns:xlink': SVGAttribute('xmlns:xlink', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xmlns:ev': SVGAttribute('xmlns:ev', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xml:base': SVGAttribute('xml:base', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xml:lang': SVGAttribute('xml:lang', anim=False, + types=frozenset(['name']), + const=empty_list), +'xml:space': SVGAttribute('xml:space', anim=False, + types=empty_list, + const=frozenset(['default', 'preserve'])), +'y': SVGMultiAttribute({ + '*': SVGAttribute( + 'y', anim=True, + types=frozenset(['coordinate']), + const=empty_list), + 'altGlyph text tref tspan': SVGAttribute( + 'y', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), + 'fePointLight feSpotLight glyphRef': SVGAttribute( + 'y', anim=True, + types=frozenset(['number']), + const=empty_list), + }), +'y1': SVGAttribute('y1', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), +'y2': SVGAttribute('y2', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), +'yChannelSelector': SVGAttribute('yChannelSelector', anim=True, + types=empty_list, + const=frozenset(['A', 'B', 'R', 'G'])), +'z': SVGAttribute('z', anim=True, + types=frozenset(['number']), + const=empty_list), +'zoomAndPan': SVGAttribute('zoomAndPan', anim=False, + types=empty_list, + const=frozenset(['disable', 'magnify'])), +} + +presentation_attributes = frozenset([ "alignment-baseline", "baseline-shift", + "clip", "clip-path", "clip-rule", "color", "color-interpolation", + "color-interpolation-filters", "color-profile", "color-rendering", "cursor", + "direction", "display", "dominant-baseline", "enable-background", + "fill", "fill-opacity", "fill-rule", "filter", "flood-color", + "flood-opacity", "font-family", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-variant", "font-weight", + "glyph-orientation-horizontal", "glyph-orientation-vertical", + "image-rendering", "kerning", "letter-spacing", "lighting-color", "marker", + "marker-end", "marker-mid", "marker-start", "mask", "opacity", + "overflow", "pointer-events", "shape-rendering", "stop-color", + "stop-opacity", "stroke", "stroke-dasharray", "stroke-dashoffset", + "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", + "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", + "text-rendering", "unicode-bidi", "visibility", "word-spacing", + "writing-mode"]) + +elements = { + 'a': SVGElement('a', + attributes=frozenset(['xlink:title', 'xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'systemLanguage', 'onmouseover', 'xlink:type', 'externalResourcesRequired', 'id', 'xlink:actuate', 'onload', 'style', 'xlink:show', 'target', 'onactivate', 'onmousedown', 'transform', 'class', 'xlink:role', 'requiredFeatures', 'xml:lang', 'onmousemove', 'xmlns:xlink', 'onclick', 'xlink:arcrole', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'altGlyph': SVGElement('altGlyph', + attributes=frozenset(['requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'id', 'onload', 'style', 'onmousedown', 'onmousemove', 'onclick', 'xlink:arcrole', 'onfocusin', 'xml:base', 'onmouseup', 'onmouseout', 'format', 'xlink:title', 'systemLanguage', 'onmouseover', 'dx', 'dy', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'xlink:show', 'onactivate', 'glyphRef', 'xlink:role', 'requiredFeatures', 'xml:lang', 'y', 'x', 'rotate']), + properties=presentation_attributes, + children=empty_list), + + 'altGlyphDef': SVGElement('altGlyphDef', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'altGlyphItem': SVGElement('altGlyphItem', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'animate': SVGElement('animate', + attributes=frozenset(['requiredExtensions', 'from', 'repeatCount', 'xml:space', 'xlink:href', 'xlink:type', 'attributeType', 'repeatDur', 'id', 'fill', 'onload', 'additive', 'calcMode', 'min', 'keySplines', 'to', 'dur', 'xlink:arcrole', 'onend', 'begin', 'xml:base', 'max', 'xlink:title', 'attributeName', 'onbegin', 'systemLanguage', 'accumulate', 'end', 'externalResourcesRequired', 'by', 'restart', 'xlink:actuate', 'xlink:show', 'xlink:role', 'requiredFeatures', 'xml:lang', 'values', 'keyTimes', 'onrepeat']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'animateColor': SVGElement('animateColor', + attributes=frozenset(['requiredExtensions', 'from', 'repeatCount', 'xml:space', 'xlink:href', 'xlink:type', 'attributeType', 'repeatDur', 'id', 'fill', 'onload', 'additive', 'calcMode', 'min', 'keySplines', 'to', 'dur', 'xlink:arcrole', 'onend', 'begin', 'xml:base', 'max', 'xlink:title', 'attributeName', 'onbegin', 'systemLanguage', 'accumulate', 'end', 'externalResourcesRequired', 'by', 'restart', 'xlink:actuate', 'xlink:show', 'xlink:role', 'requiredFeatures', 'xml:lang', 'values', 'keyTimes', 'onrepeat']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'animateMotion': SVGElement('animateMotion', + attributes=frozenset(['origin', 'requiredExtensions', 'from', 'repeatCount', 'xml:space', 'xlink:href', 'xlink:type', 'repeatDur', 'id', 'fill', 'onload', 'additive', 'calcMode', 'min', 'keySplines', 'to', 'dur', 'xlink:arcrole', 'onend', 'begin', 'xlink:title', 'xml:base', 'max', 'end', 'keyPoints', 'onbegin', 'systemLanguage', 'accumulate', 'path', 'externalResourcesRequired', 'by', 'restart', 'xlink:actuate', 'xlink:show', 'xlink:role', 'requiredFeatures', 'xml:lang', 'values', 'keyTimes', 'onrepeat', 'rotate']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'mpath', 'title'])), + + 'animateTransform': SVGElement('animateTransform', + attributes=frozenset(['requiredExtensions', 'from', 'repeatCount', 'xml:space', 'xlink:href', 'xlink:type', 'attributeType', 'repeatDur', 'id', 'fill', 'onload', 'additive', 'calcMode', 'min', 'keySplines', 'to', 'dur', 'xlink:arcrole', 'type', 'onend', 'begin', 'xml:base', 'max', 'xlink:title', 'attributeName', 'onbegin', 'systemLanguage', 'accumulate', 'end', 'externalResourcesRequired', 'by', 'restart', 'xlink:actuate', 'xlink:show', 'xlink:role', 'requiredFeatures', 'xml:lang', 'values', 'keyTimes', 'onrepeat']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'circle': SVGElement('circle', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'cy', 'cx', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'class', 'requiredFeatures', 'r', 'onmousemove', 'onclick', 'xml:lang', 'onfocusin', 'systemLanguage']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'metadata', 'desc'])), + + 'clipPath': SVGElement('clipPath', + attributes=frozenset(['clipPathUnits', 'style', 'xml:base', 'requiredExtensions', 'xml:space', 'transform', 'id', 'requiredFeatures', 'xml:lang', 'externalResourcesRequired', 'class', 'systemLanguage']), + properties=presentation_attributes, + children=frozenset(['set', 'animate', 'text', 'use', 'animateColor', 'polyline', 'path', 'line', 'ellipse', 'rect', 'desc', 'animateMotion', 'polygon', 'title', 'animateTransform', 'circle', 'metadata'])), + + 'color-profile': SVGElement('color-profile', + attributes=frozenset(['xlink:actuate', 'xlink:show', 'xml:base', 'name', 'rendering-intent', 'xml:space', 'xlink:href', 'xlink:role', 'xml:lang', 'xlink:type', 'xlink:title', 'xlink:arcrole', 'local', 'id']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'cursor': SVGElement('cursor', + attributes=frozenset(['xlink:title', 'xml:base', 'requiredExtensions', 'xml:space', 'xlink:href', 'systemLanguage', 'xlink:type', 'externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:show', 'xlink:role', 'requiredFeatures', 'xml:lang', 'y', 'x', 'xlink:arcrole']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'defs': SVGElement('defs', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'class', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'id', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'desc': SVGElement('desc', + attributes=frozenset(['style', 'xml:lang', 'xml:base', 'xml:space', 'class', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'ellipse': SVGElement('ellipse', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'ry', 'cy', 'cx', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'onactivate', 'onmousedown', 'rx', 'transform', 'class', 'requiredFeatures', 'systemLanguage', 'onmousemove', 'onclick', 'xml:lang', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'feBlend': SVGElement('feBlend', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'in2', 'height', 'width', 'xml:lang', 'id', 'result', 'in', 'y', 'x', 'class', 'mode']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feColorMatrix': SVGElement('feColorMatrix', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'id', 'height', 'width', 'xml:lang', 'values', 'result', 'in', 'y', 'x', 'type', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feComponentTransfer': SVGElement('feComponentTransfer', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'height', 'width', 'xml:lang', 'id', 'result', 'in', 'y', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['feFuncA', 'feFuncR', 'feFuncB', 'feFuncG'])), + + 'feComposite': SVGElement('feComposite', + attributes=frozenset(['xml:base', 'xml:space', 'in2', 'height', 'result', 'in', 'operator', 'class', 'style', 'width', 'id', 'k3', 'k2', 'k1', 'xml:lang', 'k4', 'y', 'x']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feConvolveMatrix': SVGElement('feConvolveMatrix', + attributes=frozenset(['xml:base', 'xml:space', 'kernelUnitLength', 'edgeMode', 'height', 'bias', 'result', 'in', 'preserveAlpha', 'id', 'style', 'divisor', 'kernelMatrix', 'width', 'xml:lang', 'targetX', 'targetY', 'y', 'x', 'class2', 'order']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feDiffuseLighting': SVGElement('feDiffuseLighting', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'diffuseConstant', 'height', 'kernelUnitLength', 'width', 'xml:lang', 'id', 'result', 'in', 'y', 'x', 'class', 'surfaceScale']), + properties=presentation_attributes, + children=frozenset(['fePointLight', 'feSpotLight', 'title', 'metadata', 'feDistantLight', 'desc'])), + + 'feDisplacementMap': SVGElement('feDisplacementMap', + attributes=frozenset(['xml:base', 'xml:space', 'yChannelSelector', 'in2', 'height', 'result', 'in', 'class', 'style', 'scale', 'id', 'width', 'xml:lang', 'xChannelSelector', 'y', 'x']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feDistantLight': SVGElement('feDistantLight', + attributes=frozenset(['xml:lang', 'elevation', 'azimuth', 'xml:base', 'xml:space', 'id']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feFlood': SVGElement('feFlood', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'height', 'width', 'xml:lang', 'id', 'result', 'y', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set', 'animateColor'])), + + 'feFuncA': SVGElement('feFuncA', + attributes=frozenset(['slope', 'xml:base', 'tableValues', 'xml:space', 'xml:lang', 'intercept', 'amplitude', 'offset', 'type', 'id', 'exponent']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feFuncB': SVGElement('feFuncB', + attributes=frozenset(['slope', 'xml:base', 'tableValues', 'xml:space', 'xml:lang', 'intercept', 'amplitude', 'offset', 'type', 'id', 'exponent']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feFuncG': SVGElement('feFuncG', + attributes=frozenset(['slope', 'xml:base', 'tableValues', 'xml:space', 'xml:lang', 'intercept', 'amplitude', 'offset', 'type', 'id', 'exponent']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feFuncR': SVGElement('feFuncR', + attributes=frozenset(['slope', 'xml:base', 'tableValues', 'xml:space', 'xml:lang', 'intercept', 'amplitude', 'offset', 'type', 'id', 'exponent']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feGaussianBlur': SVGElement('feGaussianBlur', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'height', 'width', 'xml:lang', 'id', 'result', 'in', 'y', 'x', 'stdDeviation', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feImage': SVGElement('feImage', + attributes=frozenset(['xlink:title', 'xml:base', 'xml:space', 'xlink:href', 'height', 'result', 'xlink:type', 'externalResourcesRequired', 'preserveAsectRatio', 'class', 'xlink:actuate', 'style', 'xlink:show', 'id', 'xlink:role', 'width', 'xml:lang', 'y', 'x', 'xlink:arcrole']), + properties=presentation_attributes, + children=frozenset(['animate', 'set', 'animateColor'])), + + 'feMerge': SVGElement('feMerge', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'height', 'width', 'xml:lang', 'id', 'result', 'y', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set', 'feMergeNode'])), + + 'feMergeNode': SVGElement('feMergeNode', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id', 'in']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feMorphology': SVGElement('feMorphology', + attributes=frozenset(['style', 'xml:base', 'y', 'xml:space', 'id', 'height', 'width', 'xml:lang', 'radius', 'result', 'in', 'operator', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feOffset': SVGElement('feOffset', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'in', 'height', 'width', 'xml:lang', 'id', 'result', 'dx', 'dy', 'y', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'fePointLight': SVGElement('fePointLight', + attributes=frozenset(['xml:lang', 'xml:base', 'y', 'x', 'xml:space', 'z', 'id']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feSpecularLighting': SVGElement('feSpecularLighting', + attributes=frozenset(['specularConstant', 'xml:base', 'xml:space', 'kernelUnitLength', 'height', 'result', 'in', 'class', 'style', 'id', 'width', 'xml:lang', 'specularExponent', 'y', 'x', 'surfaceScale']), + properties=presentation_attributes, + children=frozenset(['fePointLight', 'feSpotLight', 'title', 'metadata', 'feDistantLight', 'desc'])), + + 'feSpotLight': SVGElement('feSpotLight', + attributes=frozenset(['pointsAtX', 'xml:base', 'xml:space', 'limitingConeAngle', 'xml:lang', 'specularExponent', 'pointsAtZ', 'y', 'x', 'pointsAtY', 'z', 'id']), + properties=empty_list, + children=frozenset(['animate', 'set'])), + + 'feTile': SVGElement('feTile', + attributes=frozenset(['style', 'xml:base', 'xml:space', 'height', 'width', 'xml:lang', 'id', 'result', 'in', 'y', 'x', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set'])), + + 'feTurbulence': SVGElement('feTurbulence', + attributes=frozenset(['xml:base', 'baseFrequency', 'xml:space', 'stitchTiles', 'height', 'width', 'xml:lang', 'id', 'result', 'x', 'y', 'numOctaves', 'type', 'seed']), + properties=presentation_attributes, + children=empty_list), + + 'filter': SVGElement('filter', + attributes=frozenset(['xlink:title', 'xml:base', 'xml:space', 'xlink:href', 'height', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'style', 'xlink:show', 'filterRes', 'primitiveUnits', 'id', 'xlink:role', 'width', 'xml:lang', 'y', 'x', 'xlink:arcrole', 'filterUnits']), + properties=presentation_attributes, + children=frozenset(['set', 'animate', 'metadata', 'desc', 'feBlend', 'feColorMatrix', 'feComponentTransfer', + 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', + 'feDisplacementMap', 'feFlood', 'feGaussianBlur', + 'feImage', 'feMerge', 'feMorphology', 'feOffset', + 'feSpecularLighting', 'feTile', 'feTurbulence'])), + 'font': SVGElement('font', + attributes=frozenset(['xml:space', 'id', 'xml:lang', 'xml:base', 'class', 'style', 'externalResourcesRequired', 'horiz-origin-x', 'horiz-origin-y', 'horiz-adv-x', 'vert-origin-x', 'vert-origin-y', 'vert-adv-y']), + properties=presentation_attributes, + children=frozenset(['title', 'metadata', 'missing-glyph', 'font-face', 'vkern', 'hkern', 'glyph', 'desc'])), + + 'font-face': SVGElement('font-face', + attributes=frozenset(['mathematical', 'slope', 'font-size', 'xml:space', 'v-hanging', 'hanging', 'overline-thickness', 'ascent', 'id', 'strikethrough-position', 'underline-position', 'descent', 'cap-height', 'units-per-em', 'font-style', 'unicode-range', 'font-stretch', 'font-variant', 'x-height', 'font-weight', 'xml:base', 'panose-1', 'strikethrough-thickness', 'stemh', 'v-alphabetic', 'stemv', 'bbox', 'underline-thickness', 'font-family', 'v-mathematical', 'v-ideographic', 'ideographic', 'overline-position', 'widths', 'xml:lang', 'accent-height', 'alphabetic']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'font-face-src', 'title'])), + + 'font-face-format': SVGElement('font-face-format', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id']), + properties=empty_list, + children=empty_list), + + 'font-face-name': SVGElement('font-face-name', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id', 'name']), + properties=empty_list, + children=empty_list), + + 'font-face-uri': SVGElement('font-face-uri', + attributes=frozenset(['xlink:actuate', 'xlink:show', 'xml:base', 'xml:space', 'xlink:href', 'xlink:role', 'xml:lang', 'xlink:type', 'xlink:title', 'xlink:arcrole', 'id']), + properties=empty_list, + children=frozenset(['font-face-format'])), + + 'foreignObject': SVGElement('foreignObject', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'height', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'class', 'width', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'y', 'x', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['*'])), + + 'g': SVGElement('g', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'class', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'id', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'glyph': SVGElement('glyph', + attributes=frozenset(['xml:base', 'xml:space', 'id', 'xml:lang', 'class', 'style','d','horiz-adv-x', 'vert-origin-x', 'vert-origin-y', 'vert-adv-y', 'unicode', 'glyph-name', 'orientation', 'arabic-form', 'lang']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'glyphRef': SVGElement('glyphRef', + attributes=frozenset(['xlink:title', 'xml:base', 'format', 'xml:space', 'xlink:href', 'dx', 'dy', 'xlink:type', 'class', 'xlink:actuate', 'style', 'xlink:show', 'id', 'xlink:role', 'xml:lang', 'y', 'x', 'xlink:arcrole', 'glyphRef']), + properties=presentation_attributes, + children=empty_list), + + 'hkern': SVGElement('hkern', + attributes=frozenset(['xml:base', 'g2', 'g1', 'xml:space', 'u1', 'u2', 'xml:lang', 'id', 'k']), + properties=empty_list, + children=empty_list), + + 'image': SVGElement('image', + attributes=frozenset(['requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'height', 'id', 'onload', 'style', 'onmousedown', 'transform', 'width', 'onmousemove', 'onclick', 'xlink:arcrole', 'onfocusin', 'xml:base', 'onmouseup', 'onmouseout', 'xlink:title', 'systemLanguage', 'onmouseover', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'xlink:show', 'onactivate', 'xlink:role', 'requiredFeatures', 'xml:lang', 'y', 'x', 'preserveAspectRatio']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'line': SVGElement('line', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'x2', 'systemLanguage', 'onmouseover', 'y1', 'externalResourcesRequired', 'y2', 'id', 'onload', 'style', 'x1', 'onactivate', 'onmousedown', 'transform', 'class', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'linearGradient': SVGElement('linearGradient', + attributes=frozenset(['xlink:title', 'xml:base', 'xml:space', 'xlink:href', 'x2', 'y1', 'externalResourcesRequired', 'y2', 'class', 'xlink:actuate', 'xlink:role', 'style', 'xlink:show', 'spreadMethod', 'id', 'gradientUnits', 'xml:lang', 'gradientTransform', 'xlink:type', 'xlink:arcrole', 'x1']), + properties=presentation_attributes, + children=frozenset(['set', 'title', 'animate', 'animateTransform', 'stop', 'metadata', 'desc'])), + + 'marker': SVGElement('marker', + attributes=frozenset(['xml:space', 'id', 'xml:lang', 'xml:base', 'class', 'style', 'externalResourcesRequired', 'viewBox', 'preserveAspectRatio', 'refX', 'refY', 'markerUnits', 'markerWidth', 'markerHeight', 'orient']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'mask': SVGElement('mask', + attributes=frozenset(['xml:base', 'requiredExtensions', 'xml:space', 'height', 'systemLanguage', 'externalResourcesRequired', 'maskContentUnits', 'class', 'style', 'id', 'width', 'requiredFeatures', 'xml:lang', 'y', 'x', 'maskUnits']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'metadata': SVGElement('metadata', + attributes=frozenset(['xml:space', 'xml:lang', 'xml:base', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'missing-glyph': SVGElement('missing-glyph', + attributes=frozenset(['xml:base', 'xml:space', 'id', 'xml:lang', 'class', 'style', 'd', 'horiz-adv-x', 'vert-origin-x', 'vert-origin-y', 'vert-adv-y']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'mpath': SVGElement('mpath', + attributes=frozenset(['xlink:actuate', 'xlink:show', 'xml:base', 'xml:space', 'xlink:href', 'id', 'xlink:role', 'xml:lang', 'xlink:type', 'xlink:title', 'xlink:arcrole', 'externalResourcesRequired']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'path': SVGElement('path', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'pathLength', 'externalResourcesRequired', 'id', 'onload', 'style', 'd', 'onactivate', 'onmousedown', 'transform', 'class', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'pattern': SVGElement('pattern', + attributes=frozenset(['xlink:title', 'xml:base', 'requiredExtensions', 'xml:space', 'xlink:href', 'height', 'class', 'systemLanguage', 'patternContentUnits', 'xlink:type', 'externalResourcesRequired', 'id', 'xlink:actuate', 'style', 'xlink:show', 'viewBox', 'xlink:role', 'width', 'requiredFeatures', 'patternUnits', 'patternTransform', 'y', 'x', 'preserveAspectRatio', 'xlink:arcrole', 'xml:lang']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'polygon': SVGElement('polygon', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'class', 'requiredFeatures', 'points', 'onmousemove', 'onclick', 'xml:lang', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'polyline': SVGElement('polyline', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'class', 'requiredFeatures', 'points', 'onmousemove', 'onclick', 'xml:lang', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'radialGradient': SVGElement('radialGradient', + attributes=frozenset(['xlink:title', 'xml:base', 'fx', 'fy', 'xml:space', 'xlink:href', 'cy', 'cx', 'xlink:type', 'externalResourcesRequired', 'r', 'id', 'xlink:actuate', 'gradientUnits', 'style', 'xlink:show', 'spreadMethod', 'class', 'xlink:role', 'xml:lang', 'gradientTransform', 'xlink:arcrole']), + properties=presentation_attributes, + children=frozenset(['set', 'title', 'animate', 'animateTransform', 'stop', 'metadata', 'desc'])), + + 'rect': SVGElement('rect', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'height', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'id', 'onload', 'style', 'ry', 'onactivate', 'onmousedown', 'rx', 'transform', 'class', 'width', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'y', 'x', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'metadata', 'desc'])), + + 'script': SVGElement('script', + attributes=frozenset(['xlink:actuate', 'xlink:show', 'xml:base', 'xml:space', 'xlink:href', 'id', 'xlink:role', 'xml:lang', 'xlink:type', 'xlink:title', 'xlink:arcrole', 'type', 'externalResourcesRequired']), + properties=empty_list, + children=empty_list), + + 'set': SVGElement('set', + attributes=frozenset(['begin', 'xlink:title', 'xml:base', 'requiredExtensions', 'repeatCount', 'xml:space', 'xlink:href', 'attributeName', 'onbegin', 'systemLanguage', 'attributeType', 'xlink:type', 'externalResourcesRequired', 'id', 'restart', 'fill', 'xlink:actuate', 'onload', 'xlink:show', 'end', 'min', 'repeatDur', 'xlink:role', 'to', 'requiredFeatures', 'xml:lang', 'max', 'dur', 'xlink:arcrole', 'onrepeat', 'onend']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'stop': SVGElement('stop', + attributes=frozenset(['xml:base', 'xml:space', 'xml:lang', 'offset', 'style', 'class']), + properties=presentation_attributes, + children=frozenset(['animate', 'set', 'animateColor'])), + + 'style': SVGElement('style', + attributes=frozenset(['xml:lang', 'xml:base', 'title', 'media', 'xml:space', 'type', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'svg': SVGElement('svg', + attributes=frozenset(['requiredExtensions', 'onerror', 'onfocusout', 'xml:space', 'height', 'onscroll', 'baseProfile', 'contentStyleType', 'id', 'onabort', 'onload', 'style', 'onmousedown', 'onzoom', 'onresize', 'width', 'version', 'onmousemove', 'onmouseup', 'xmlns:xlink', 'xmlns:ev', 'onfocusin', 'xml:base', 'onclick', 'onmouseout', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'zoomAndPan', 'class', 'onunload', 'xmlns', 'onactivate', 'viewBox', 'requiredFeatures', 'xml:lang', 'y', 'x', 'preserveAspectRatio', 'contentScriptType']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'switch': SVGElement('switch', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'systemLanguage', 'onmouseover', 'externalResourcesRequired', 'class', 'onload', 'style', 'onactivate', 'onmousedown', 'transform', 'id', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'line', 'use', 'animateColor', 'polyline', 'path', 'animate', 'ellipse', 'rect', 'desc', 'a', 'animateMotion', 'polygon', 'g', 'title', 'svg', 'switch', 'animateTransform', 'foreignObject', 'circle', 'metadata'])), + + 'symbol': SVGElement('symbol', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'onfocusout', 'xml:space', 'onmouseover', 'id', 'externalResourcesRequired', 'viewBox', 'onload', 'style', 'onactivate', 'onmousedown', 'class', 'xml:lang', 'onmousemove', 'onclick', 'preserveAspectRatio', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['set', 'text', 'image', 'font-face', 'polyline', 'marker', 'animate', 'font', 'color-profile', 'ellipse', 'cursor', 'style', 'polygon', 'title', 'pattern', 'circle', 'radialGradient', 'metadata', 'defs', 'symbol', 'use', 'animateMotion', 'animateColor', 'path', 'line', 'rect', 'desc', 'a', 'g', 'svg', 'script', 'mask', 'altGlyphDef', 'filter', 'switch', 'animateTransform', 'linearGradient', 'clipPath', 'foreignObject', 'view'])), + + 'text': SVGElement('text', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'class', 'systemLanguage', 'onmouseover', 'dx', 'dy', 'externalResourcesRequired', 'lengthAdjust', 'onload', 'style', 'rotate', 'onactivate', 'onmousedown', 'textLength', 'transform', 'id', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'y', 'x', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['a', 'animateMotion', 'set', 'title', 'textPath', 'tspan', 'animateColor', 'tref', 'animateTransform', 'altGlyph', 'animate', 'desc', 'metadata'])), + + 'textPath': SVGElement('textPath', + attributes=frozenset(['requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'startOffset', 'id', 'onload', 'style', 'onmousedown', 'lengthAdjust', 'onmousemove', 'onclick', 'xlink:arcrole', 'onfocusin', 'xml:base', 'onmouseup', 'onmouseout', 'xlink:title', 'spacing', 'systemLanguage', 'onmouseover', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'xlink:show', 'onactivate', 'textLength', 'method', 'xlink:role', 'requiredFeatures', 'xml:lang']), + properties=presentation_attributes, + children=frozenset(['a', 'set', 'title', 'tspan', 'animateColor', 'tref', 'altGlyph', 'animate', 'metadata', 'desc'])), + + 'title': SVGElement('title', + attributes=frozenset(['style', 'xml:lang', 'xml:base', 'xml:space', 'class', 'id']), + properties=empty_list, + children=frozenset(['*'])), + + 'tref': SVGElement('tref', + attributes=frozenset(['requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'id', 'onload', 'style', 'onmousedown', 'lengthAdjust', 'onmousemove', 'onclick', 'xlink:arcrole', 'onfocusin', 'xml:base', 'onmouseup', 'onmouseout', 'xlink:title', 'systemLanguage', 'onmouseover', 'dx', 'dy', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'xlink:show', 'onactivate', 'textLength', 'xlink:role', 'requiredFeatures', 'xml:lang', 'y', 'x', 'rotate']), + properties=presentation_attributes, + children=frozenset(['set', 'title', 'animate', 'metadata', 'animateColor', 'desc'])), + + 'tspan': SVGElement('tspan', + attributes=frozenset(['xml:base', 'onmouseup', 'onmouseout', 'requiredExtensions', 'onfocusout', 'xml:space', 'class', 'systemLanguage', 'onmouseover', 'dx', 'dy', 'externalResourcesRequired', 'lengthAdjust', 'onload', 'style', 'rotate', 'onactivate', 'onmousedown', 'textLength', 'id', 'requiredFeatures', 'xml:lang', 'onmousemove', 'onclick', 'y', 'x', 'onfocusin']), + properties=presentation_attributes, + children=frozenset(['a', 'set', 'title', 'tspan', 'animateColor', 'tref', 'altGlyph', 'animate', 'metadata', 'desc'])), + + 'use': SVGElement('use', + attributes=frozenset(['requiredExtensions', 'onfocusout', 'xml:space', 'xlink:href', 'height', 'id', 'onload', 'style', 'onmousedown', 'transform', 'width', 'onmousemove', 'onclick', 'xlink:arcrole', 'onfocusin', 'xml:base', 'onmouseup', 'onmouseout', 'xlink:title', 'systemLanguage', 'onmouseover', 'xlink:type', 'externalResourcesRequired', 'class', 'xlink:actuate', 'xlink:show', 'onactivate', 'xlink:role', 'requiredFeatures', 'xml:lang', 'y', 'x']), + properties=presentation_attributes, + children=frozenset(['animateMotion', 'set', 'title', 'animateColor', 'animateTransform', 'animate', 'desc', 'metadata'])), + + 'view': SVGElement('view', + attributes=frozenset(['xml:base', 'viewTarget', 'xml:space', 'viewBox', 'xml:lang', 'preserveAspectRatio', 'externalResourcesRequired', 'zoomAndPan', 'id']), + properties=empty_list, + children=frozenset(['desc', 'metadata', 'title'])), + + 'vkern': SVGElement('vkern', + attributes=frozenset(['xml:base', 'g2', 'g1', 'xml:space', 'u1', 'u2', 'xml:lang', 'id', 'k']), + properties=empty_list, + children=empty_list), + +} diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/pattern.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..233722d2d94942797808ff8c33111ff72bdb7c5f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/pattern.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: pattern module +# Created: 27.09.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +import re + +#coordinate ::= number ("em" | "ex" | "px" | "in" | "cm" | "mm" | "pt" | "pc" | "%")? +coordinate = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(cm|em|ex|in|mm|pc|pt|px|%)?$") + +#length ::= number ("em" | "ex" | "px" | "in" | "cm" | "mm" | "pt" | "pc" | "%")? +length = coordinate + +#angle ::= number (~"deg" | ~"grad" | ~"rad")? +angle = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(deg|rad|grad)?$") + +# numbers without units +number = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)$") + +# number as percentage value '###%' +percentage = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)%$") + +#frequency ::= number (~"Hz" | ~"kHz") +frequency = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(Hz|kHz)?$") + +#time ::= number (~"s" | ~"ms") +time = re.compile(r"(^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(s|ms)?$") diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/svgparser.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/svgparser.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6a82fad3da06aad2b46f825889e95e06b66087 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/svgparser.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python +# coding:utf-8 +# Authors: mozman , Florian Festi +# Purpose: svgparser using re module +# Created: 16.10.2010 +# Copyright (c) 2010, Manfred Moitzi & 2020, Florian Festi +# License: MIT License + +__all__ = ["is_valid_transferlist", "is_valid_pathdata", "is_valid_animation_timing"] + +import re + +event_names = [ + "focusin", "focusout", "activate", "click", "mousedown", "mouseup", "mouseover", + "mousemove", "mouseout", "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", + "DOMNodeRemovedFromDocument", "DOMNodeInsertedtoDocument", "DOMAttrModified", + "DOMCharacterDataModified", "SVGLoad", "SVGUnload", "SVGAbort", "SVGError", + "SVGResize", "SVGScroll", "SVGZoom", "beginEvent", "endEvent", "repeatEvent", +] + +c = r"\s*[, ]\s*" +s = r"\s*[; ]\s*" +integer_constant = r"\d+" +exponent = r"([eE][+-]?\d+)" +nonnegative_number = fr"(\d+\.?\d*|\.\d+){exponent}?" +number = r"[+-]?" + nonnegative_number +flag = r"[01]" + +comma_delimited_coordinates = fr"\s*{number}({c}{number})*\s*" +two_comma_delimited_numbers = fr"\s*{number}({c}{number}\s*)" "{1}" +four_comma_delimited_numbers = fr"\s*{number}\s*({c}{number}\s*)" "{3}" +six_comma_delimited_numbers = fr"\s*{number}\s*({c}{number}\s*)" "{5}" +comma_delimited_coordinate_pairs = fr"{two_comma_delimited_numbers}({c}{two_comma_delimited_numbers})*" + + +def is_valid(regex): + reg = re.compile(regex) + + def f(term): + return bool(reg.fullmatch(term)) + + return f + + +def build_transferlist_parser(): + matrix = fr"matrix\s*\(\s*{six_comma_delimited_numbers}\s*\)" + translate = fr"translate\s*\(\s*{number}({c}{number})?\s*\)" + scale = fr"scale\s*\(\s*{number}({c}{number})?\s*\)" + rotate = fr"rotate\s*\(\s*{number}({c}{number}{c}{number})?\s*\)" + skewX = fr"skewX\s*\(\s*{number}\s*\)" + skewY = fr"skewY\s*\(\s*{number}\s*\)" + + tl_re = "|".join((fr"(\s*{cmd}\s*)" for cmd in ( + matrix, translate, scale, rotate, skewX, skewY))) + return fr"({tl_re})({c}({tl_re}))*" + + +is_valid_transferlist = is_valid(build_transferlist_parser()) + + +def build_pathdata_parser(): + moveto = fr"[mM]\s*{comma_delimited_coordinate_pairs}" + lineto = fr"[lL]\s*{comma_delimited_coordinate_pairs}" + horizontal_lineto = fr"[hH]\s*{comma_delimited_coordinates}" + vertical_lineto = fr"[vV]\s*{comma_delimited_coordinates}" + curveto = fr"[cC]\s*({six_comma_delimited_numbers})({c}{six_comma_delimited_numbers})*" + smooth_curveto = fr"[sS]{four_comma_delimited_numbers}({c}{four_comma_delimited_numbers})*" + quadratic_bezier_curveto = fr"[qQ]{four_comma_delimited_numbers}({c}{four_comma_delimited_numbers})*" + smooth_quadratic_bezier_curveto = fr"[tT]\s*{comma_delimited_coordinate_pairs}" + + elliptical_arc_argument = fr"{c}".join(( + fr"{nonnegative_number}", + fr"{nonnegative_number}", + fr"{number}", + fr"{flag}", + fr"{flag}", + fr"{number}", + fr"{number}",)) + elliptical_arc_argument = r"\s*" + elliptical_arc_argument + r"\s*" + elliptical_arc = fr"[aA]({elliptical_arc_argument})({c}{elliptical_arc_argument})*" + + drawto_command = "|".join((fr"(\s*{cmd}\s*)" for cmd in ( + moveto, lineto, horizontal_lineto, vertical_lineto, "[zZ]", + curveto, smooth_curveto, quadratic_bezier_curveto, + smooth_quadratic_bezier_curveto, elliptical_arc))) + + return f"{moveto}({drawto_command})*" + + +is_valid_pathdata = is_valid(build_pathdata_parser()) + +digit2 = r"\d{2}" +digit4 = r"\d{4}" +seconds = fr"\d+(\.\d+)?" +seconds2 = fr"{digit2}(\.\d+)?" +metric = "(h|min|s|ms)" + + +def clock_val_re(): + timecount_val = fr"{seconds}\s*({metric})?" + clock_val = fr"{digit2}:({digit2}:)?{seconds2}" + return fr"({timecount_val}|{clock_val})" + + +def wall_clock_val_re(): + hhmmss = fr"{digit2}:{digit2}(:{seconds2})?" + walltime = fr"{hhmmss}(Z|[+-]?{digit2}:{digit2})?" + date = fr"{digit4}-{digit2}-{digit2}" + datetime = fr"{date}(T{walltime})?" + return "(" + "|".join((walltime, datetime)) + ")" + + +def build_animation_timing_parser(): + clock_val = clock_val_re() + wallclock_val = wall_clock_val_re() + + event_ref = "(" + "|".join(event_names) + ")" + id_value = "#?[-_a-zA-Z0-9]+" + + wallclock_sync_value = fr"wallclock\(\s*{wallclock_val}\s*\)" + accesskey_value = fr"accessKey\(\s*[a-zA-Z]\s*\)\s*([+-]?{clock_val})?" + repeat_value = fr"({id_value}\.)?repeat\s*\(\s*\d+\s*\)\s*([+-?]{clock_val})?" + event_value = fr"({id_value}\.)?{event_ref}([+-]?{clock_val})?" + offset_value = fr"[-+]?{clock_val}" + syncbase_value = fr"{id_value}\.(begin|end)({offset_value})?" + begin_value = "(" + "|".join((f"({reg})" for reg in ( + offset_value, syncbase_value, event_value, repeat_value, + accesskey_value, wallclock_sync_value, "indefinite"))) + ")" + return fr"{begin_value}({s}{begin_value})*" + + +is_valid_animation_timing = is_valid(build_animation_timing_parser()) diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/tiny12.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/tiny12.py new file mode 100644 index 0000000000000000000000000000000000000000..53108f90988068efb723e7ddbca9523b61259fff --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/tiny12.py @@ -0,0 +1,966 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: tiny12 data +# Created: 15.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.data.types import SVGAttribute, SVGMultiAttribute +from svgwrite.data.types import SVGElement +from svgwrite.data.typechecker import Tiny12TypeChecker as TypeChecker + +empty_list = [] + +attributes = { +'about': SVGAttribute('about', anim=True, + types=frozenset(['string']), + const=empty_list), +'accent-height': SVGAttribute('accent-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'accumulate': SVGAttribute('accumulate', anim=False, + types=empty_list, + const=frozenset(['none', 'sum'])), +'additive': SVGAttribute('additive', anim=False, + types=empty_list, + const=frozenset(['replace', 'sum'])), +'alphabetic': SVGAttribute('alphabetic', anim=False, + types=frozenset(['number']), + const=empty_list), +'arabic-form': SVGAttribute('arabic-form', anim=False, + types=empty_list, + const=frozenset(['terminal', 'initial', 'isolated', 'medial'])), +'ascent': SVGAttribute('ascent', anim=False, + types=frozenset(['number']), + const=empty_list), +'attributeName': SVGAttribute('attributeName', anim=False, + types=frozenset(['name']), + const=empty_list), +'attributeType': SVGAttribute('attributeType', anim=False, + types=empty_list, + const=frozenset(['XML', 'CSS', 'auto'])), +'audio-level': SVGAttribute('audio-level', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'bandwidth': SVGAttribute('bandwidth', anim=False, + types=frozenset(['number']), + const=frozenset(['auto'])), +'baseProfile': SVGAttribute('baseProfile', anim=False, + types=empty_list, + const=frozenset(['none', 'tiny', 'basic', 'full'])), +'bbox': SVGAttribute('bbox', anim=False, + types=frozenset(['string']), + const=empty_list), +'begin': SVGAttribute('begin', anim=False, + types=frozenset(['timing-value-list']), + const=frozenset(['indefinite'])), +'buffered-rendering': SVGAttribute('buffered-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'dynamic', 'static', 'inherit'])), +'by': SVGAttribute('by', anim=False, + types=frozenset(['string']), + const=empty_list), +'calcMode': SVGAttribute('calcMode', anim=False, + types=empty_list, + const=frozenset(['discrete', 'linear', 'paced', 'spline'])), +'cap-height': SVGAttribute('cap-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'class': SVGAttribute('class', anim=True, + types=frozenset(['list-of-name']), + const=empty_list), +'color': SVGAttribute('color', anim=True, + types=frozenset(['color']), + const=frozenset(['inherit'])), +'color-rendering': SVGAttribute('color-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'optimizeQuality', 'inherit'])), +'content': SVGAttribute('content', anim=True, + types=frozenset(['string']), + const=empty_list), +'contentScriptType': SVGAttribute('contentScriptType', anim=False, + types=frozenset(['content-type']), + const=empty_list), +'cx': SVGAttribute('cx', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'cy': SVGAttribute('cy', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'d': SVGAttribute('d', anim=True, + types=frozenset(['path-data']), + const=empty_list), +'datatype': SVGAttribute('datatype', anim=True, + types=frozenset(['string']), + const=empty_list), +'defaultAction': SVGAttribute('defaultAction', anim=False, + types=empty_list, + const=frozenset(['perform', 'cancel'])), +'descent': SVGAttribute('descent', anim=False, + types=frozenset(['number']), + const=empty_list), +'direction': SVGAttribute('direction', anim=False, + types=empty_list, + const=frozenset(['ltr', 'rtl', 'inherit'])), +'display': SVGAttribute('display', anim=True, + types=empty_list, + const=frozenset(['inline', 'block', 'list-item', 'run-in', 'compact', + 'marker', 'table', 'inline-table', 'table-row-group', + 'table-header-group', 'table-footer-group', 'table-row', + 'table-column-group', 'table-column', 'table-cell', + 'table-caption', 'none', 'inherit'])), +'display-align': SVGAttribute('display-align', anim=True, + types=empty_list, + const=frozenset(['auto', 'before', 'center', 'after', 'inherit'])), +'dur': SVGAttribute('dur', anim=False, + types=frozenset(['time']), + const=frozenset(['media', 'indefinite'])), +'editable': SVGAttribute('editable', anim=True, + types=empty_list, + const=frozenset(['none', 'simple'])), +'end': SVGAttribute('end', anim=False, + types=frozenset(['timing-value-list']), + const=frozenset(['indefinite'])), +'ev:event': SVGAttribute('ev:event', anim=False, + types=frozenset(['XML-Name']), + const=empty_list), +'event': SVGAttribute('event', anim=False, + types=frozenset(['XML-Name']), + const=empty_list), +'externalResourcesRequired': SVGAttribute('externalResourcesRequired', anim=False, + types=frozenset(['boolean']), + const=empty_list), +'fill': SVGMultiAttribute({ + '*': SVGAttribute( + 'fill', anim=True, + types=frozenset(['paint']), + const=frozenset(['inherit'])), + 'set animateMotion animate animateColor animateTransform': SVGAttribute( + 'fill', anim=False, + types=empty_list, + const=frozenset(['freeze', 'remove'])) + }), +'fill-opacity': SVGAttribute('fill-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'fill-rule': SVGAttribute('fill-rule', anim=True, + types=empty_list, + const=frozenset(['nonzero', 'evenodd', 'inherit'])), +'focusHighlight': SVGAttribute('focusHighlight', anim=True, + types=empty_list, + const=frozenset(['auto', 'none'])), +'focusable': SVGAttribute('focusable', anim=True, + types=frozenset(['boolean']), + const=frozenset(['auto'])), +'font-family': SVGAttribute('font-family', anim=True, + types=frozenset(['string']), + const=frozenset(['inherit'])), +'font-size': SVGAttribute('font-size', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'font-stretch': SVGAttribute('font-stretch', anim=False, + types=empty_list, + const=frozenset(['condensed', 'normal', 'ultra-condensed', 'expanded', + 'narrower', 'inherit', 'semi-condensed', 'extra-condensed', + 'ultra-expanded', 'wider', 'semi-expanded', 'extra-expanded'])), +'font-style': SVGAttribute('font-style', anim=True, + types=empty_list, + const=frozenset(['normal', 'italic', 'oblique', 'inherit'])), +'font-variant': SVGAttribute('font-variant', anim=True, + types=empty_list, + const=frozenset(['normal', 'small-caps', 'inherit'])), +'font-weight': SVGAttribute('font-weight', anim=True, + types=empty_list, + const=frozenset(['normal', 'bold', 'bolder', 'lighter', '100', '200', + '300', '400', '500', '600', '700', '800', '900', + 'inherit'])), +'from': SVGAttribute('from', anim=False, + types=frozenset(['string']), + const=empty_list), +'g1': SVGAttribute('g1', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'g2': SVGAttribute('g2', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'glyph-name': SVGAttribute('glyph-name', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'gradientUnits': SVGAttribute('gradientUnits', anim=True, + types=empty_list, + const=frozenset(['userSpaceOnUse', 'objectBoundingBox'])), +'handler': SVGAttribute('handler', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'hanging': SVGAttribute('hanging', anim=False, + types=frozenset(['number']), + const=empty_list), +'height': SVGMultiAttribute({ + '*': SVGAttribute( + 'height', anim=True, + types=frozenset(['length']), + const=empty_list), + 'textArea': SVGAttribute( + 'height', anim=True, + types=frozenset(['length']), + const=frozenset(['auto'])), + }), +'horiz-adv-x': SVGAttribute('horiz-adv-x', anim=False, + types=frozenset(['number']), + const=empty_list), +'horiz-origin-x': SVGAttribute('horiz-origin-x', anim=False, + types=frozenset(['number']), + const=empty_list), +'id': SVGAttribute('id', anim=False, + types=frozenset(['name']), + const=empty_list), +'ideographic': SVGAttribute('ideographic', anim=False, + types=frozenset(['number']), + const=empty_list), +'image-rendering': SVGAttribute('image-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'optimizeQuality', 'inherit'])), +'initialVisibility': SVGAttribute('initialVisibility', anim=False, + types=empty_list, + const=frozenset(['whenStarted', 'always'])), +'k': SVGAttribute('k', anim=False, + types=frozenset(['number']), + const=empty_list), +'keyPoints': SVGAttribute('keyPoints', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'keySplines': SVGAttribute('keySplines', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'keyTimes': SVGAttribute('keyTimes', anim=False, + types=frozenset(['semicolon-list']), + const=empty_list), +'lang': SVGAttribute('lang', anim=False, + types=frozenset(['list-of-name']), + const=empty_list), +'line-increment': SVGAttribute('line-increment', anim=True, + types=frozenset(['number']), + const=frozenset(['auto', 'inherit'])), +'mathematical': SVGAttribute('mathematical', anim=False, + types=frozenset(['number']), + const=empty_list), +'max': SVGAttribute('max', anim=False, + types=frozenset(['time']), + const=frozenset(['media'])), +'mediaCharacterEncoding': SVGAttribute('mediaCharacterEncoding', anim=False, + types=frozenset(['string']), + const=empty_list), +'mediaContentEncodings': SVGAttribute('mediaContentEncodings', anim=False, + types=frozenset(['string']), + const=empty_list), +'mediaSize': SVGAttribute('mediaSize', anim=False, + types=frozenset(['number']), + const=empty_list), +'mediaTime': SVGAttribute('mediaTime', anim=False, + types=frozenset(['time']), + const=empty_list), +'min': SVGAttribute('min', anim=False, + types=frozenset(['time']), + const=frozenset(['media'])), +'nav-down': SVGAttribute('nav-down', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-down-left': SVGAttribute('nav-down-left', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-down-right': SVGAttribute('nav-down-right', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-left': SVGAttribute('nav-left', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-next': SVGAttribute('nav-next', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-prev': SVGAttribute('nav-prev', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-right': SVGAttribute('nav-right', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-up': SVGAttribute('nav-up', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-up-left': SVGAttribute('nav-up-left', anim=True, + types=frozenset(['focus']), + const=empty_list), +'nav-up-right': SVGAttribute('nav-up-right', anim=True, + types=frozenset(['focus']), + const=empty_list), +'observer': SVGAttribute('observer', anim=False, + types=frozenset(['IDREF']), + const=empty_list), +'offset': SVGAttribute('offset', anim=True, + types=frozenset(['number']), + const=empty_list), +'opacity': SVGAttribute('opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'origin': SVGAttribute('origin', anim=False, + types=empty_list, + const=frozenset(['default'])), +'overlay': SVGAttribute('overlay', anim=False, + types=empty_list, + const=frozenset(['none', 'top'])), +'overline-position': SVGAttribute('overline-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'overline-thickness': SVGAttribute('overline-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'panose-1': SVGAttribute('panose-1', anim=False, + types=frozenset(['list-of-integer']), + const=empty_list), +'path': SVGAttribute('path', anim=False, + types=frozenset(['path-data']), + const=empty_list), +'pathLength': SVGAttribute('pathLength', anim=True, + types=frozenset(['number']), + const=empty_list), +'phase': SVGAttribute('phase', anim=False, + types=empty_list, + const=frozenset(['default', 'capture'])), +'playbackOrder': SVGAttribute('playbackOrder', anim=False, + types=empty_list, + const=frozenset(['all', 'forwardOnly'])), +'pointer-events': SVGAttribute('pointer-events', anim=True, + types=empty_list, + const=frozenset(['visiblePainted', 'visibleFill', 'visibleStroke', 'visible', + 'painted', 'fill', 'stroke', 'all', 'none', 'inherit'])), +'points': SVGAttribute('points', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), +'preserveAspectRatio': SVGAttribute('preserveAspectRatio', anim=True, + types=frozenset(['string']), + const=empty_list), +'propagate': SVGAttribute('propagate', anim=False, + types=empty_list, + const=frozenset(['continue', 'stop'])), +'property': SVGAttribute('property', anim=True, + types=frozenset(['string']), + const=empty_list), +'r': SVGAttribute('r', anim=True, + types=frozenset(['length']), + const=empty_list), +'rel': SVGAttribute('rel', anim=True, + types=frozenset(['string']), + const=empty_list), +'repeatCount': SVGAttribute('repeatCount', anim=False, + types=frozenset(['number']), + const=frozenset(['indefinite'])), +'repeatDur': SVGAttribute('repeatDur', anim=False, + types=frozenset(['time']), + const=frozenset(['indefinite'])), +'requiredExtensions': SVGAttribute('requiredExtensions', anim=False, + types=frozenset(['list-of-IRI']), + const=empty_list), +'requiredFeatures': SVGAttribute('requiredFeatures', anim=False, + types=frozenset(['list-of-IRI']), + const=empty_list), +'requiredFonts': SVGAttribute('requiredFonts', anim=False, + types=frozenset(['string']), + const=empty_list), +'requiredFormats': SVGAttribute('requiredFormats', anim=False, + types=frozenset(['anything']), + const=empty_list), +'resource': SVGAttribute('resource', anim=True, + types=frozenset(['string']), + const=empty_list), +'restart': SVGAttribute('restart', anim=False, + types=empty_list, + const=frozenset(['always', 'never', 'whenNotActive'])), +'rev': SVGAttribute('rev', anim=True, + types=frozenset(['string']), + const=empty_list), +'role': SVGAttribute('role', anim=True, + types=frozenset(['string']), + const=empty_list), +'rotate': SVGAttribute('rotate', anim=True, + types=frozenset(['list-of-number']), + const=empty_list), +'rx': SVGAttribute('rx', anim=True, + types=frozenset(['length']), + const=empty_list), +'ry': SVGAttribute('ry', anim=True, + types=frozenset(['length']), + const=empty_list), +'shape-rendering': SVGAttribute('shape-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'crispEdges', 'geometricPrecision', 'inherit'])), +'slope': SVGAttribute('slope', anim=False, + types=frozenset(['number']), + const=empty_list), +'snapshotTime': SVGAttribute('snapshotTime', anim=False, + types=frozenset(['time']), + const=frozenset(['none'])), +'solid-color': SVGAttribute('solid-color', anim=True, + types=frozenset(['color']), + const=frozenset(['currentColor', 'inherit'])), +'solid-opacity': SVGAttribute('solid-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'stemh': SVGAttribute('stemh', anim=False, + types=frozenset(['number']), + const=empty_list), +'stemv': SVGAttribute('stemv', anim=False, + types=frozenset(['number']), + const=empty_list), +'stop-color': SVGAttribute('stop-color', anim=True, + types=frozenset(['color']), + const=frozenset(['inherit'])), +'stop-opacity': SVGAttribute('stop-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'strikethrough-position': SVGAttribute('strikethrough-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'strikethrough-thickness': SVGAttribute('strikethrough-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'stroke': SVGAttribute('stroke', anim=True, + types=frozenset(['paint']), + const=frozenset(['inherit'])), +'stroke-dasharray': SVGAttribute('stroke-dasharray', anim=True, + types=frozenset(['list-of-length']), + const=frozenset(['none', 'inherit'])), +'stroke-dashoffset': SVGAttribute('stroke-dashoffset', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'stroke-linecap': SVGAttribute('stroke-linecap', anim=True, + types=empty_list, + const=frozenset(['butt', 'round', 'square', 'inherit'])), +'stroke-linejoin': SVGAttribute('stroke-linejoin', anim=True, + types=empty_list, + const=frozenset(['miter', 'round', 'bevel', 'inherit'])), +'stroke-miterlimit': SVGAttribute('stroke-miterlimit', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'stroke-opacity': SVGAttribute('stroke-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'stroke-width': SVGAttribute('stroke-width', anim=True, + types=frozenset(['length']), + const=frozenset(['inherit'])), +'syncBehavior': SVGAttribute('syncBehavior', anim=False, + types=empty_list, + const=frozenset(['canSlip', 'locked', 'independent', 'default'])), +'syncBehaviorDefault': SVGAttribute('syncBehaviorDefault', anim=False, + types=empty_list, + const=frozenset(['canSlip', 'locked', 'independent', 'inherit'])), +'syncMaster': SVGAttribute('syncMaster', anim=False, + types=frozenset(['boolean']), + const=empty_list), +'syncTolerance': SVGAttribute('syncTolerance', anim=False, + types=frozenset(['time']), + const=frozenset(['default'])), +'syncToleranceDefault': SVGAttribute('syncToleranceDefault', anim=False, + types=frozenset(['time']), + const=frozenset(['inherit'])), +'systemLanguage': SVGAttribute('systemLanguage', anim=False, + types=frozenset(['string']), + const=empty_list), +'target': SVGMultiAttribute({ + '* a': SVGAttribute( + 'target', anim=True, + types=frozenset(['XML-Name']), + const=frozenset(['_replace', '_self', '_parent', '_top', '_blank'])), + 'listener': SVGAttribute( + 'target', anim=False, + types=frozenset(['XML-Name']), + const=empty_list), + }), +'text-align': SVGAttribute('text-align', anim=True, + types=empty_list, + const=frozenset(['start', 'center', 'end', 'inherit'])), +'text-anchor': SVGAttribute('text-anchor', anim=True, + types=empty_list, + const=frozenset(['start', 'middle', 'end', 'inherit'])), +'text-rendering': SVGAttribute('text-rendering', anim=True, + types=empty_list, + const=frozenset(['auto', 'optimizeSpeed', 'optimizeLegibility', 'geometricPrecision', 'inherit'])), +'timelineBegin': SVGAttribute('timelineBegin', anim=False, + types=empty_list, + const=frozenset(['onLoad', 'onStart'])), +'to': SVGAttribute('to', anim=False, + types=frozenset(['string']), + const=empty_list), +'transform': SVGAttribute('transform', anim=True, + types=frozenset(['transform-list']), + const=frozenset(['none'])), +'transformBehavior': SVGAttribute('transformBehavior', anim=False, + types=empty_list, + const=frozenset(['geometric', 'pinned', 'pinned90', 'pinned180', 'pinned270'])), +'type': SVGMultiAttribute({ + '* audio image video': SVGAttribute( + 'type', anim=True, + types=frozenset(['content-type']), + const=empty_list), + 'handler script': SVGAttribute( + 'type', anim=False, + types=frozenset(['content-type']), + const=empty_list), + 'animateTransform': SVGAttribute( + 'type', anim=False, + types=empty_list, + const=frozenset(['translate', 'scale', 'rotate', 'skewX', 'skewY'])), + }), +'typeof': SVGAttribute('typeof', anim=True, + types=frozenset(['string']), + const=empty_list), +'u1': SVGAttribute('u1', anim=False, + types=frozenset(['string']), + const=empty_list), +'u2': SVGAttribute('u2', anim=False, + types=frozenset(['string']), + const=empty_list), +'underline-position': SVGAttribute('underline-position', anim=False, + types=frozenset(['number']), + const=empty_list), +'underline-thickness': SVGAttribute('underline-thickness', anim=False, + types=frozenset(['number']), + const=empty_list), +'unicode': SVGAttribute('unicode', anim=False, + types=frozenset(['string']), + const=empty_list), +'unicode-bidi': SVGAttribute('unicode-bidi', anim=False, + types=empty_list, + const=frozenset(['normal', 'embed', 'bidi-override', 'inherit'])), +'unicode-range': SVGAttribute('unicode-range', anim=False, + types=frozenset(['string']), + const=empty_list), +'units-per-em': SVGAttribute('units-per-em', anim=False, + types=frozenset(['number']), + const=empty_list), +'values': SVGAttribute('values', anim=False, + types=frozenset(['list-of-number']), + const=empty_list), +'vector-effect': SVGAttribute('vector-effect', anim=True, + types=empty_list, + const=frozenset(['none', 'non-scaling-stroke', 'inherit'])), +'version': SVGAttribute('version', anim=False, + types=empty_list, + const=frozenset(['1.1', '1.2'])), +'viewBox': SVGAttribute('viewBox', anim=True, + types=frozenset(['four-numbers']), + const=empty_list), +'viewport-fill': SVGAttribute('viewport-fill', anim=True, + types=frozenset(['color']), + const=frozenset(['none', 'inherit'])), +'viewport-fill-opacity': SVGAttribute('viewport-fill-opacity', anim=True, + types=frozenset(['number']), + const=frozenset(['inherit'])), +'visibility': SVGAttribute('visibility', anim=True, + types=empty_list, + const=frozenset(['visible', 'hidden', 'inherit'])), +'width': SVGMultiAttribute({ + '*': SVGAttribute( + 'width', anim=True, + types=frozenset(['length']), + const=empty_list), + 'textArea': SVGAttribute( + 'width', anim=True, + types=frozenset(['length']), + const=frozenset(['auto'])), + }), +'widths': SVGAttribute('widths', anim=False, + types=frozenset(['string']), + const=empty_list), +'x': SVGMultiAttribute({ + '*': SVGAttribute( + 'x', anim=True, + types=frozenset(['coordinate']), + const=empty_list), + 'text': SVGAttribute( + 'x', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), + }), +'x-height': SVGAttribute('x-height', anim=False, + types=frozenset(['number']), + const=empty_list), +'x1': SVGAttribute('x1', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'x2': SVGAttribute('x2', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'xlink:actuate': SVGMultiAttribute({ + '*': SVGAttribute( + 'xlink:actuate', anim=False, + types=empty_list, + const=frozenset(['onLoad'])), + 'a': SVGAttribute( + 'xlink:actuate', anim=False, + types=empty_list, + const=frozenset(['onRequest'])), + }), +'xlink:arcrole': SVGAttribute('xlink:arcrole', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xlink:href': SVGAttribute('xlink:href', anim=True, + types=frozenset(['IRI']), + const=empty_list), +'xlink:role': SVGAttribute('xlink:role', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xlink:show': SVGMultiAttribute({ + '*': SVGAttribute( + 'xlink:show', anim=False, + types=empty_list, + const=frozenset(['other'])), + 'animation audio foreignObject image use video': SVGAttribute( + 'xlink:show', anim=False, + types=empty_list, + const=frozenset(['embed'])), + 'a': SVGAttribute( + 'xlink:show', anim=False, + types=empty_list, + const=frozenset(['new', 'replace'])), + }), +'xlink:title': SVGAttribute('xlink:title', anim=False, + types=frozenset(['string']), + const=empty_list), +'xlink:type': SVGAttribute('xlink:type', anim=True, + types=empty_list, + const=frozenset(['simple'])), +'xmlns': SVGAttribute('xmlns', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xmlns:xlink': SVGAttribute('xmlns:xlink', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xmlns:ev': SVGAttribute('xmlns:ev', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xml:base': SVGAttribute('xml:base', anim=False, + types=frozenset(['IRI']), + const=empty_list), +'xml:id': SVGAttribute('xml:id', anim=False, + types=frozenset(['name']), + const=empty_list), +'xml:lang': SVGAttribute('xml:lang', anim=False, + types=frozenset(['name']), + const=empty_list), +'xml:space': SVGMultiAttribute({ + '*': SVGAttribute( + 'xml:space', anim=False, + types=empty_list, + const=frozenset(['preserve', 'default'])), + 'handler script': SVGAttribute( + 'xml:space', anim=False, + types=empty_list, + const=frozenset(['preserve'])), + }), +'y': SVGMultiAttribute({ + '*': SVGAttribute( + 'y', anim=True, + types=frozenset(['coordinate']), + const=empty_list), + 'text': SVGAttribute( + 'y', anim=True, + types=frozenset(['list-of-coordinate']), + const=empty_list), + }), +'y1': SVGAttribute('y1', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'y2': SVGAttribute('y2', anim=True, + types=frozenset(['coordinate']), + const=empty_list), +'zoomAndPan': SVGAttribute('zoomAndPan', anim=False, + types=empty_list, + const=frozenset(['disable', 'magnify'])), +} + +attribute_names = ['slope', 'keySplines', 'rx', 'accumulate', 'bandwidth', + 'attributeType', 'unicode', 'nav-right', 'arabic-form', + 'y2', 'horiz-origin-x', 'underline-position', 'zoomAndPan', + 'cap-height', 'defaultAction', 'to', 'syncBehavior', + 'alphabetic', 'g2', 'g1', 'panose-1', 'strikethrough-thickness', + 'attributeName', 'bbox', 'nav-up-left', 'nav-left', + 'restart', 'target', 'xlink:actuate', 'rotate', 'resource', + 'd', 'syncToleranceDefault', 'initialVisibility', + 'transformBehavior', 'nav-up-right', 'keyTimes', + 'x', 'requiredFormats', 'nav-next', 'glyph-name', + 'xml:lang', 'mathematical', 'observer', 'repeatDur', + 'hanging', 'y1', 'xml:base', 'ascent', 'event', + 'strikethrough-position', 'overlay', 'rev', 'ry', + 'overline-thickness', 'content', 'version', 'rel', + 'focusable', 'requiredFonts', 'nav-down-right', 'xml:id', + 'offset', 'additive', 'underline-thickness', 'font-family', + 'by', 'mediaTime', 'timelineBegin', 'about', 'horiz-adv-x', + 'widths', 'k', 'requiredFeatures', 'preserveAspectRatio', + 'contentScriptType', 'origin', 'xml:space', 'xlink:href', + 'height', 'baseProfile', 'cy', 'cx', 'path', 'xlink:role', + 'from', 'u1', 'transform', 'units-per-em', 'u2', 'width', + 'handler', 'font-variant', 'x-height', 'dur', 'xlink:arcrole', + 'type', 'focusHighlight', 'mediaCharacterEncoding', + 'xlink:title', 'editable', 'stemv', 'systemLanguage', + 'x2', 'x1', 'ideographic', 'xlink:show', 'overline-position', + 'syncTolerance', 'gradientUnits', 'r', 'values', 'typeof', + 'mediaContentEncodings', 'property', 'requiredExtensions', + 'repeatCount', 'ev:event', 'nav-down', 'mediaSize', 'pathLength', + 'syncMaster', 'font-style', 'fill', 'end', 'descent', + 'calcMode', 'min', 'stemh', 'id', 'unicode-range', + 'nav-up', 'font-stretch', 'role', 'font-weight', 'begin', + 'xlink:type', 'syncBehaviorDefault', 'max', 'snapshotTime', + 'playbackOrder', 'keyPoints', 'nav-prev', 'propagate', + 'phase', 'externalResourcesRequired', 'nav-down-left', + 'class', 'lang', 'datatype', 'viewBox', 'points', + 'accent-height', 'y'] +property_names = ['stroke-linejoin', 'font-size', 'text-rendering', 'color-rendering', + 'fill-opacity', 'color', 'shape-rendering', 'solid-color', 'stroke', + 'stroke-linecap', 'vector-effect', 'stroke-width', 'font-style', + 'fill', 'solid-opacity', 'fill-rule', 'viewport-fill-opacity', + 'display-align', 'buffered-rendering', 'stroke-miterlimit', + 'font-variant', 'stop-opacity', 'font-weight', 'opacity', 'direction', + 'audio-level', 'visibility', 'unicode-bidi', 'line-increment', + 'image-rendering', 'font-family', 'viewport-fill', 'text-align', + 'stroke-opacity', 'stroke-dashoffset', 'text-anchor', 'stop-color', + 'pointer-events', 'stroke-dasharray', 'display'] +media_group_names = ['audio-level', 'buffered-rendering', 'display', 'image-rendering', + 'pointer-events', 'shape-rendering', 'text-rendering', + 'viewport-fill', 'viewport-fill-opacity', 'visibility'] + +elements = { + 'a': SVGElement('a', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'target', 'transform', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['likeparent', 'defs', 'text', 'g', 'textArea', 'svg']), + + 'animate': SVGElement('animate', + attributes=['about', 'accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'class', 'content', 'datatype', 'dur', 'end', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'systemLanguage', 'to', 'typeof', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'switch', 'title']), + + 'animateColor': SVGElement('animateColor', + attributes=['about', 'accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'class', 'content', 'datatype', 'dur', 'end', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'systemLanguage', 'to', 'typeof', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'switch', 'title']), + + 'animateMotion': SVGElement('animateMotion', + attributes=['about', 'accumulate', 'additive', 'begin', 'by', 'calcMode', 'class', 'content', 'datatype', 'dur', 'end', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'origin', 'path', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'rotate', 'systemLanguage', 'to', 'typeof', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'mpath', 'switch', 'title']), + + 'animateTransform': SVGElement('animateTransform', + attributes=['about', 'accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'class', 'content', 'datatype', 'dur', 'end', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'systemLanguage', 'to', 'type', 'typeof', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'switch', 'title']), + + 'animation': SVGElement('animation', + attributes=['about', 'begin', 'class', 'content', 'datatype', 'dur', 'end', 'externalResourcesRequired', 'fill', 'focusHighlight', 'focusable', 'height', 'id', 'initialVisibility', 'max', 'min', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'preserveAspectRatio', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'syncBehavior', 'syncMaster', 'syncTolerance', 'systemLanguage', 'transform', 'typeof', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=media_group_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'audio': SVGElement('audio', + attributes=['about', 'begin', 'class', 'content', 'datatype', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'syncBehavior', 'syncMaster', 'syncTolerance', 'systemLanguage', 'type', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=media_group_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'circle': SVGElement('circle', + attributes=['about', 'class', 'content', 'cx', 'cy', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'r', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'defs': SVGElement('defs', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'animation', 'audio', 'circle', 'defs', 'desc', 'discard', 'ellipse', 'font', 'font-face', 'foreignObject', 'g', 'handler', 'image', 'line', 'linearGradient', 'listener', 'metadata', 'path', 'polygon', 'polyline', 'prefetch', 'radialGradient', 'rect', 'script', 'set', 'solidColor', 'switch', 'text', 'textArea', 'title', 'use', 'video']), + + 'desc': SVGElement('desc', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=media_group_names, + children=empty_list), + + 'discard': SVGElement('discard', + attributes=['about', 'begin', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'switch', 'title']), + + 'ellipse': SVGElement('ellipse', + attributes=['about', 'class', 'content', 'cx', 'cy', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'rx', 'ry', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'font': SVGElement('font', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'font-face', 'glyph', 'hkern', 'metadata', 'missing-glyph', 'switch', 'title']), + + 'font-face': SVGElement('font-face', + attributes=['about', 'accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'class', 'content', 'datatype', 'descent', 'externalResourcesRequired', 'font-family', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'property', 'rel', 'resource', 'rev', 'role', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'typeof', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'widths', 'x-height', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'font-face-src', 'metadata', 'switch', 'title']), + + 'font-face-src': SVGElement('font-face-src', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'font-face-uri', 'metadata', 'switch', 'title']), + + 'font-face-uri': SVGElement('font-face-uri', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'foreignObject': SVGElement('foreignObject', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'height', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=property_names, + children=['desc', 'metadata', 'svg', 'switch', 'title']), + + 'g': SVGElement('g', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'animation', 'audio', 'circle', 'defs', 'desc', 'discard', 'ellipse', 'font', 'font-face', 'foreignObject', 'g', 'handler', 'image', 'line', 'linearGradient', 'listener', 'metadata', 'path', 'polygon', 'polyline', 'prefetch', 'radialGradient', 'rect', 'script', 'set', 'solidColor', 'switch', 'text', 'textArea', 'title', 'use', 'video']), + + 'glyph': SVGElement('glyph', + attributes=['about', 'arabic-form', 'class', 'content', 'd', 'datatype', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'unicode', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'handler': SVGElement('handler', + attributes=['about', 'class', 'content', 'datatype', 'ev:event', 'externalResourcesRequired', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'type', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'hkern': SVGElement('hkern', + attributes=['about', 'class', 'content', 'datatype', 'g1', 'g2', 'id', 'k', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'u1', 'u2', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'image': SVGElement('image', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'height', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'opacity', 'preserveAspectRatio', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'type', 'typeof', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=media_group_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'line': SVGElement('line', + attributes=['about', 'class', 'content', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'x1', 'x2', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y1', 'y2'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'linearGradient': SVGElement('linearGradient', + attributes=['about', 'class', 'content', 'datatype', 'gradientUnits', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'x1', 'x2', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y1', 'y2'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'metadata', 'set', 'stop', 'switch', 'title']), + + 'listener': SVGElement('listener', + attributes=['about', 'class', 'content', 'datatype', 'defaultAction', 'event', 'handler', 'id', 'observer', 'phase', 'propagate', 'property', 'rel', 'resource', 'rev', 'role', 'target', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=empty_list), + + 'metadata': SVGElement('metadata', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=media_group_names, + children=empty_list), + + 'missing-glyph': SVGElement('missing-glyph', + attributes=['about', 'class', 'content', 'd', 'datatype', 'horiz-adv-x', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'mpath': SVGElement('mpath', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'path': SVGElement('path', + attributes=['about', 'class', 'content', 'd', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'pathLength', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'polygon': SVGElement('polygon', + attributes=['about', 'class', 'content', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'points', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'polyline': SVGElement('polyline', + attributes=['about', 'class', 'content', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'points', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'prefetch': SVGElement('prefetch', + attributes=['about', 'bandwidth', 'class', 'content', 'datatype', 'id', 'mediaCharacterEncoding', 'mediaContentEncodings', 'mediaSize', 'mediaTime', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'radialGradient': SVGElement('radialGradient', + attributes=['about', 'class', 'content', 'cx', 'cy', 'datatype', 'gradientUnits', 'id', 'property', 'r', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'metadata', 'set', 'stop', 'switch', 'title']), + + 'rect': SVGElement('rect', + attributes=['about', 'class', 'content', 'datatype', 'focusHighlight', 'focusable', 'height', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'rx', 'ry', 'systemLanguage', 'transform', 'typeof', 'width', 'x', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'script': SVGElement('script', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'type', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'metadata', 'switch', 'title']), + + 'set': SVGElement('set', + attributes=['about', 'attributeName', 'attributeType', 'begin', 'class', 'content', 'datatype', 'dur', 'end', 'fill', 'id', 'max', 'min', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'systemLanguage', 'to', 'typeof', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=['desc', 'handler', 'metadata', 'switch', 'title']), + + 'solidColor': SVGElement('solidColor', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'stop': SVGElement('stop', + attributes=['about', 'class', 'content', 'datatype', 'id', 'offset', 'property', 'rel', 'resource', 'rev', 'role', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'metadata', 'set', 'switch', 'title']), + + 'svg': SVGElement('svg', + attributes=['about', 'baseProfile', 'class', 'content', 'contentScriptType', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'height', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'playbackOrder', 'preserveAspectRatio', 'property', 'rel', 'resource', 'rev', 'role', 'snapshotTime', 'syncBehaviorDefault', 'syncToleranceDefault', 'timelineBegin', 'transform', 'typeof', 'version', 'viewBox', 'width', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'xmlns:ev', 'zoomAndPan'], + properties=property_names, + children=['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'animation', 'audio', 'circle', 'defs', 'desc', 'discard', 'ellipse', 'font', 'font-face', 'foreignObject', 'g', 'handler', 'image', 'line', 'linearGradient', 'listener', 'metadata', 'path', 'polygon', 'polyline', 'prefetch', 'radialGradient', 'rect', 'script', 'set', 'solidColor', 'switch', 'text', 'textArea', 'title', 'use', 'video']), + + 'switch': SVGElement('switch', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['likeparent', 'set', 'textArea', 'text', 'image', 'missing-glyph', 'font-face', 'video', 'path', 'animate', 'font', 'ellipse', 'glyph', 'use', 'font-face-src', 'polygon', 'script', 'handler', 'circle', 'radialGradient', 'prefetch', 'defs', 'mpath', 'stop', 'animateMotion', 'animateColor', 'discard', 'solidColor', 'hkern', 'line', 'animation', 'rect', 'g', 'svg', 'animateTransform', 'linearGradient', 'font-face-uri', 'foreignObject', 'polyline', 'audio']), + + 'tbreak': SVGElement('tbreak', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=empty_list, + children=empty_list), + + 'text': SVGElement('text', + attributes=['about', 'class', 'content', 'datatype', 'editable', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'rotate', 'systemLanguage', 'transform', 'typeof', 'x', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=property_names, + children=['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title', 'tspan']), + + 'textArea': SVGElement('textArea', + attributes=['about', 'class', 'content', 'datatype', 'editable', 'focusHighlight', 'focusable', 'height', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'width', 'x', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=property_names, + children=['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'tbreak', 'title', 'tspan']), + + 'title': SVGElement('title', + attributes=['about', 'class', 'content', 'datatype', 'id', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=media_group_names, + children=empty_list), + + 'tspan': SVGElement('tspan', + attributes=['about', 'class', 'content', 'datatype', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'typeof', 'xml:base', 'xml:id', 'xml:lang', 'xml:space'], + properties=property_names, + children=['likeparent', 'text', 'textArea']), + + 'use': SVGElement('use', + attributes=['about', 'class', 'content', 'datatype', 'externalResourcesRequired', 'focusHighlight', 'focusable', 'id', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'property', 'rel', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'rev', 'role', 'systemLanguage', 'transform', 'typeof', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=property_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), + + 'video': SVGElement('video', + attributes=['about', 'begin', 'class', 'content', 'datatype', 'dur', 'end', 'externalResourcesRequired', 'fill', 'focusHighlight', 'focusable', 'height', 'id', 'initialVisibility', 'max', 'min', 'nav-down', 'nav-down-left', 'nav-down-right', 'nav-left', 'nav-next', 'nav-prev', 'nav-right', 'nav-up', 'nav-up-left', 'nav-up-right', 'overlay', 'preserveAspectRatio', 'property', 'rel', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'requiredFonts', 'requiredFormats', 'resource', 'restart', 'rev', 'role', 'syncBehavior', 'syncMaster', 'syncTolerance', 'systemLanguage', 'transform', 'transformBehavior', 'type', 'typeof', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:id', 'xml:lang', 'xml:space', 'y'], + properties=media_group_names, + children=['animate', 'animateColor', 'animateMotion', 'animateTransform', 'desc', 'discard', 'handler', 'metadata', 'set', 'switch', 'title']), +} diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/typechecker.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/typechecker.py new file mode 100644 index 0000000000000000000000000000000000000000..8cace93eabae1c1126bc6336dbb647656ae47b44 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/typechecker.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: typechecker +# Created: 15.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +import re + +from svgwrite.data import pattern +from svgwrite.data.colors import colornames +from svgwrite.data.svgparser import is_valid_transferlist, is_valid_pathdata, is_valid_animation_timing +from svgwrite.utils import is_string + +def iterflatlist(values): + """ Flatten nested *values*, returns an *iterator*. """ + for element in values: + if hasattr(element, "__iter__") and not is_string(element): + for item in iterflatlist(element): + yield item + else: + yield element + +INVALID_NAME_CHARS = frozenset([' ', '\t', '\r', '\n', ',', '(', ')']) +WHITESPACE = frozenset([' ', '\t', '\r', '\n']) +SHAPE_PATTERN = re.compile(r"^rect\((.*),(.*),(.*),(.*)\)$") +FUNCIRI_PATTERN = re.compile(r"^url\((.*)\)$") +ICCCOLOR_PATTERN = re.compile(r"^icc-color\((.*)\)$") +COLOR_HEXDIGIT_PATTERN = re.compile(r"^#[a-fA-F0-9]{3}([a-fA-F0-9]{3})?$") +COLOR_RGB_INTEGER_PATTERN = re.compile(r"^rgb\( *\d+ *, *\d+ *, *\d+ *\)$") +COLOR_RGB_PERCENTAGE_PATTERN = re.compile(r"^rgb\( *\d+(\.\d*)?% *, *\d+(\.\d*)?% *, *\d+(\.\d*)?% *\)$") +NMTOKEN_PATTERN = re.compile(r"^[a-zA-Z_:][\w\-\.:]*$") + + +class Full11TypeChecker(object): + def get_version(self): + return '1.1', 'full' + + def is_angle(self, value): + #angle ::= number (~"deg" | ~"grad" | ~"rad")? + if self.is_number(value): + return True + elif is_string(value): + return pattern.angle.match(value.strip()) is not None + return False + + def is_anything(self, value): + #anything ::= Char* + return bool(str(value).strip()) + is_string = is_anything + is_content_type = is_anything + + def is_color(self, value): + #color ::= "#" hexdigit hexdigit hexdigit (hexdigit hexdigit hexdigit)? + # | "rgb(" wsp* integer comma integer comma integer wsp* ")" + # | "rgb(" wsp* number "%" comma number "%" comma number "%" wsp* ")" + # | color-keyword + #hexdigit ::= [0-9A-Fa-f] + #comma ::= wsp* "," wsp* + value = str(value).strip() + if value.startswith('#'): + if COLOR_HEXDIGIT_PATTERN.match(value): + return True + else: + return False + elif value.startswith('rgb('): + if COLOR_RGB_INTEGER_PATTERN.match(value): + return True + elif COLOR_RGB_PERCENTAGE_PATTERN.match(value): + return True + return False + return self.is_color_keyword(value) + + def is_color_keyword(self, value): + return value.strip() in colornames + + def is_frequency(self, value): + # frequency ::= number (~"Hz" | ~"kHz") + if self.is_number(value): + return True + elif is_string(value): + return pattern.frequency.match(value.strip()) is not None + return False + + def is_FuncIRI(self, value): + # FuncIRI ::= "url(" ")" + res = FUNCIRI_PATTERN.match(str(value).strip()) + if res: + return self.is_IRI(res.group(1)) + return False + + def is_icccolor(self, value): + # icccolor ::= "icc-color(" name (comma-wsp number)+ ")" + res = ICCCOLOR_PATTERN.match(str(value).strip()) + if res: + return self.is_list_of_T(res.group(1), 'name') + return False + + def is_integer(self, value): + if isinstance(value, float): + return False + try: + number = int(value) + return True + except: + return False + + def is_IRI(self, value): + # Internationalized Resource Identifiers + # a more generalized complement to Uniform Resource Identifiers (URIs) + # nearly everything can be a valid + # only a none-empty string ist a valid input + if is_string(value): + return bool(value.strip()) + else: + return False + + def is_length(self, value): + # length ::= number ("em" | "ex" | "px" | "in" | "cm" | "mm" | "pt" | "pc" | "%")? + if value is None: + return False + if isinstance(value, (int, float)): + return self.is_number(value) + elif is_string(value): + result = pattern.length.match(value.strip()) + if result: + number, tmp, unit = result.groups() + return self.is_number(number) # for tiny check! + return False + + is_coordinate = is_length + + def is_list_of_T(self, value, t='string'): + def split(value): + #TODO: improve split function!!!! + if isinstance(value, (int, float)): + return (value, ) + if is_string(value): + return iterflatlist(v.split(',') for v in value.split(' ')) + return value + #list-of-Ts ::= T + # | T comma-wsp list-of-Ts + #comma-wsp ::= (wsp+ ","? wsp*) | ("," wsp*) + #wsp ::= (#x20 | #x9 | #xD | #xA) + checker = self.get_func_by_name(t) + for v in split(value): + if not checker(v): + return False + return True + + def is_four_numbers(self, value): + def split(value): + if is_string(value): + values = iterflatlist( (v.strip().split(' ') for v in value.split(',')) ) + return (v for v in values if v) + else: + return iterflatlist(value) + + values = list(split(value)) + if len(values) != 4: + return False + checker = self.get_func_by_name('number') + for v in values: + if not checker(v): + return False + return True + + def is_semicolon_list(self, value): + #a semicolon-separated list of values + # | value comma-wsp list-of-values + #comma-wsp ::= (wsp+ ";" wsp*) | ("," wsp*) + #wsp ::= (#x20 | #x9 | #xD | #xA) + return self.is_list_of_T(value.replace(';', ' '), 'string') + + def is_name(self, value): + # name ::= [^,()#x20#x9#xD#xA] /* any char except ",", "(", ")" or wsp */ + chars = frozenset(str(value).strip()) + if not chars or INVALID_NAME_CHARS.intersection(chars): + return False + else: + return True + + def is_number(self, value): + try: + number = float(value) + return True + except: + return False + + def is_number_optional_number(self, value): + #number-optional-number ::= number + # | number comma-wsp number + if is_string(value): + values = re.split('[ ,]+', value.strip()) + if 0 < len(values) < 3: # 1 or 2 numbers + for v in values: + if not self.is_number(v): + return False + return True + else: + try: # is it a 2-tuple + n1, n2 = value + if self.is_number(n1) and \ + self.is_number(n2): + return True + except TypeError: # just one value + return self.is_number(value) + except ValueError: # more than 2 values + pass + return False + + def is_paint(self, value): + #paint ::= "none" | + # "currentColor" | + # [] | + # [ "none" | "currentColor" | [] | + # "inherit" + def split_values(value): + try: + funcIRI, value = value.split(")", 1) + values = [funcIRI+")"] + values.extend(split_values(value)) + return values + except ValueError: + return value.split() + + values = split_values(str(value).strip()) + for value in [v.strip() for v in values]: + if value in ('none', 'currentColor', 'inherit'): + continue + elif self.is_color(value): + continue + elif self.is_icccolor(value): + continue + elif self.is_FuncIRI(value): + continue + return False + return True + + def is_percentage(self, value): + #percentage ::= number "%" + if self.is_number(value): + return True + elif is_string(value): + return pattern.percentage.match(value.strip()) is not None + return False + + def is_time(self, value): + #time ::= (~"ms" | ~"s")? + if self.is_number(value): + return True + elif is_string(value): + return pattern.time.match(value.strip()) is not None + return False + + def is_transform_list(self, value): + if is_string(value): + return is_valid_transferlist(value) + else: + return False + + def is_path_data(self, value): + if is_string(value): + return is_valid_pathdata(value) + else: + return False + + def is_XML_Name(self, value): + # http://www.w3.org/TR/2006/REC-xml-20060816/#NT-Name + # Nmtoken + return bool(NMTOKEN_PATTERN.match(str(value).strip())) + + def is_shape(self, value): + # shape ::= ( ) + # where , , and specify offsets from the + # respective sides of the box. + # , , , and are values + # i.e. 'rect(5px, 10px, 10px, 5px)' + res = SHAPE_PATTERN.match(value.strip()) + if res: + for arg in res.groups(): + if arg.strip() == 'auto': + continue + if not self.is_length(arg): + return False + else: + return False + return True + + def is_timing_value_list(self, value): + if is_string(value): + return is_valid_animation_timing(value) + else: + return False + + def is_list_of_text_decoration_style(self, value): + return self.is_list_of_T(value, t='text_decoration_style') + + def is_text_decoration_style(self, value): + return value in ('overline', 'underline', 'line-through', 'blink') + + def get_func_by_name(self, funcname): + return getattr(self, + 'is_'+funcname.replace('-', '_'), + self.is_anything) + + def check(self, typename, value): + if typename.startswith('list-of-'): + t = typename[8:] + return self.is_list_of_T(value, t) + return self.get_func_by_name(typename)(value) + + +FOCUS_CONST = frozenset(['nav-next', 'nav-prev', 'nav-up', 'nav-down', 'nav-left', + 'nav-right', 'nav-up-left', 'nav-up-right', 'nav-down-left', + 'nav-down-right']) + + +class Tiny12TypeChecker(Full11TypeChecker): + def get_version(self): + return '1.2', 'tiny' + + def is_boolean(self, value): + if isinstance(value, bool): + return True + if is_string(value): + return value.strip().lower() in ('true', 'false') + return False + + def is_number(self, value): + try: + number = float(value) + if -32767.9999 <= number <= 32767.9999: + return True + else: + return False + except: + return False + + def is_focus(self, value): + return str(value).strip() in FOCUS_CONST diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/data/types.py b/videollama2/lib/python3.10/site-packages/svgwrite/data/types.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6f3025fb139d5d830f45dd3561b6591f9edee9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/data/types.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: svg types +# Created: 30.09.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + + +class SVGAttribute(object): + def __init__(self, name, anim, types, const): + self.name = name + self._anim = anim + self._types = types + self._const = const + + # 'elementname' is ignored, but necessary because of the signatures of + # the SVGMultiAttribute class methods get_...() + + def get_anim(self, elementname='*'): + return self._anim + + def get_types(self, elementname='*'): + return self._types + + def get_const(self, elementname='*'): + return self._const + + +class SVGMultiAttribute(object): + # example: SVGMultiAttribute({'*':SVGAttribute(...), 'text tref':SVGAttribute(...)} ) + # parametr is a dict-like object + # '*' is the default attribute definition + # 'text' and 'tref' share the same attribute definition + + def __init__(self, attributes): + self.name = None + self._attributes = {} + + for names, attribute in attributes.items(): + for name in names.split(): + name = name.strip() + self._attributes[name] = attribute + if not self.name: + self.name = attribute.name + elif self.name != attribute.name: + raise ValueError("Different attribute-names for SVGMultiAttribute "\ + "(%s != %s)." % (self.name, attribute.name)) + + if '*' not in self._attributes and len(self._attributes): + # if no default attribute definition were given + # set the first attribute definition as the default attribute definition + firstkey = sorted(self._attributes.keys())[0] + self._attributes['*'] = self._attributes[firstkey] + + def get_attribute(self, elementname): + if elementname in self._attributes: + return self._attributes[elementname] + else: + return self._attributes['*'] + + def get_anim(self, elementname='*'): + attribute = self.get_attribute(elementname) + return attribute.get_anim() + + def get_types(self, elementname='*'): + attribute = self.get_attribute(elementname) + return attribute.get_types() + + def get_const(self, elementname='*'): + attribute = self.get_attribute(elementname) + return attribute.get_const() + + +class SVGElement(object): + def __init__(self, name, attributes, properties, children): + self.name = name + s = set(attributes) + s.update(properties) + self.valid_attributes = frozenset(s) + self.valid_children = frozenset(children) diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__init__.py b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0481e963f016393884f804a06cc0814b35a96874 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__init__.py @@ -0,0 +1,3 @@ +# Copyright (c) 2018 Manfred Moitzi +# License: MIT License +from .inkscape import Inkscape diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97eb16ddcdb64b19931945e020cfbe9390fa4e1d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/inkscape.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/inkscape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373158e64cab1f4f7967153f5e1758e136de6b9e Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/inkscape.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/shapes.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/shapes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9e987033a9a773710d292d2ca7291e9618dbd7 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/__pycache__/shapes.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/inkscape.py b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/inkscape.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea5c02933125d235a5ec2aeb6d14aa0aa742aaa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/inkscape.py @@ -0,0 +1,89 @@ +# Copyright (c) 2018 Manfred Moitzi +# License: MIT License +# based on work of: +# Copyright (c) 2018 Antonio Ospite + +from svgwrite.data.types import SVGAttribute + +INKSCAPE_NAMESPACE = 'http://www.inkscape.org/namespaces/inkscape' +SODIPODI_NAMESPACE = 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' +INKSCAPE_ATTRIBUTES = { + 'xmlns:inkscape': SVGAttribute('xmlns:inkscape', + anim=False, + types=[], + const=frozenset([INKSCAPE_NAMESPACE])), + 'xmlns:sodipodi': SVGAttribute('xmlns:sodipodi', + anim=False, + types=[], + const=frozenset([SODIPODI_NAMESPACE])), + 'inkscape:groupmode': SVGAttribute('inkscape:groupmode', + anim=False, + types=[], + const=frozenset(['layer'])), + 'inkscape:label': SVGAttribute('inkscape:label', + anim=False, + types=frozenset(['string']), + const=[]), + 'sodipodi:insensitive': SVGAttribute('sodipodi:insensitive', + anim=False, + types=[], + const=frozenset(['true', 'false', '0', '1'])) +} + + +def _setup_validator(validator): + # setup already done? + if 'xmlns:inkscape' in validator.attributes: + return + + validator.attributes.update(INKSCAPE_ATTRIBUTES) + elements = validator.elements + + # extend SVG attributes + elements['svg'].valid_attributes = \ + { + 'xmlns:inkscape', + 'xmlns:sodipodi', + } | elements['svg'].valid_attributes + + # extend group attributes + elements['g'].valid_attributes = \ + { + 'inkscape:groupmode', + 'inkscape:label', + 'sodipodi:insensitive', + } | elements['g'].valid_attributes + + +GROUP_MODE = 'inkscape:groupmode' +LABEL = 'inkscape:label' +INSENSITIVE = 'sodipodi:insensitive' + + +class Inkscape(object): + """ + Extension to support SOME Inkscape features. + + """ + def __init__(self, drawing): + self.svg = drawing + _setup_validator(drawing.validator) + drawing['xmlns:inkscape'] = INKSCAPE_NAMESPACE + drawing['xmlns:sodipodi'] = SODIPODI_NAMESPACE + + def layer(self, label=None, locked=False, **kwargs): + """ + Create new Inkscape layer. + + Args: + label: layer name as string + locked: when set to True, make objects at this layer unselectable + + """ + new_layer = self.svg.g(**kwargs) + new_layer[GROUP_MODE] = 'layer' + if label is not None: + new_layer[LABEL] = label + if locked: + new_layer[INSENSITIVE] = 1 + return new_layer diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/extensions/shapes.py b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..d2714580e250e7e3f4c9eae706c8731c27f35726 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/extensions/shapes.py @@ -0,0 +1,129 @@ +""" +Extension to create and manipulate shapes +""" +# Copyright (c) 2019 Christof Hanke (christof.hanke@induhviduals.de) +# License: MIT License +import math + + +def ngon(num_corners, edge_length=None, radius=None, rotation=0.): + """ + Returns the corners of a regular polygon as iterable of (x, y) tuples. The polygon size is determined by the + `edge_length` or the `radius` argument. If both are given `edge_length` will be taken. + + Args: + num_corners: count of polygon corners + edge_length: length of polygon side + radius: circum radius + rotation: rotation angle in radians + + Returns: iterable of (x, y) tuples + + """ + if num_corners < 3: + raise ValueError('Argument `num_corners` has to be greater than 2.') + if edge_length is not None: + radius = edge_length / 2 / math.sin(math.pi / num_corners) + elif radius is not None: + if radius <= 0.: + raise ValueError('Argument `radius` has to be greater than 0.') + else: + raise ValueError('Argument `edge_length` or `radius` required.') + + delta = 2 * math.pi / num_corners + angle = rotation + for _ in range(num_corners): + yield (radius * math.cos(angle), radius * math.sin(angle)) + angle += delta + + +def star(spikes, r1, r2, rotation=0.): + """ + Create a star shape as iterable of (x, y) vertices. + + Argument `spikes` defines the count of star spikes, `r1` defines the radius of the "outer" vertices and `r2` + defines the radius of the "inner" vertices, but this does not mean that `r1` has to greater than `r2`. + + Args: + spikes: spike count + r1: radius 1 + r2: radius 2 + rotation: rotation angle in radians + + Returns: iterable of (x, y) tuples + + """ + if spikes < 3: + raise ValueError('Argument `spikes` has to be greater than 2.') + if r1 <= 0.: + raise ValueError('Argument `r1` has to be greater than 0.') + if r2 <= 0.: + raise ValueError('Argument `r2` has to be greater than 0.') + + corners1 = ngon(spikes, radius=r1, rotation=rotation) + corners2 = ngon(spikes, radius=r2, rotation=math.pi/spikes+rotation) + for s1, s2 in zip(corners1, corners2): + yield s1 + yield s2 + + +def translate(vertices, delta_x, delta_y): + """ + Translates `vertices` about `delta_x` and `delta_y` + + Args: + vertices: iterable of (x, y) tuples + delta_x: translation in x axis + delta_y: translation in y axis + + Returns: iterable of (x, y) tuples + + """ + for x, y in vertices: + yield (x + delta_x, y + delta_y) + + +def scale(vertices, scale_x, scale_y): + """ + Scales `vertices` about `scale_x` and `scale_y` + + Args: + vertices: iterable of (x, y) tuples + scale_x: scaling factor in x axis direction + scale_y: scaling factor in y axis direction + + Returns: iterable of (x, y) tuples + + """ + for x, y in vertices: + yield (x * scale_x, y * scale_y) + + +def rotate(vertices, delta): + """ + Rotates `vertices` about `delta` degrees around the origin (0, 0). + + Args: + vertices: iterable of (x, y) tuples + delta: rotation angle in radians + + Returns: iterable of (x, y) tuples + + """ + for x, y in vertices: + r = math.hypot(x, y) + angle = math.atan2(y, x) + delta + yield (r * math.cos(angle), r * math.sin(angle)) + + +def centroid(vertices): + """ + Returns the centroid of a series of `vertices`. + + """ + k, c_x, c_y = 0, 0, 0 + for x, y in vertices: + c_x += x + c_y += y + k += 1 + return c_x / k, c_y / k diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/gradients.py b/videollama2/lib/python3.10/site-packages/svgwrite/gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..0857af3d5baa4906d0f7964f30801e245dc8cf52 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/gradients.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: gradients module +# Created: 26.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License +""" +Gradients consist of continuously smooth color transitions along a vector +from one color to another, possibly followed by additional transitions along +the same vector to other colors. SVG provides for two types of gradients: +linear gradients and radial gradients. +""" + +from svgwrite.base import BaseElement +from svgwrite.mixins import Transform, XLink +from svgwrite.utils import is_string + + +class _GradientStop(BaseElement): + elementname = 'stop' + + def __init__(self, offset=None, color=None, opacity=None, **extra): + super(_GradientStop, self).__init__(**extra) + + if offset is not None: + self['offset'] = offset + if color is not None: + self['stop-color'] = color + if opacity is not None: + self['stop-opacity'] = opacity + + +class _AbstractGradient(BaseElement, Transform, XLink): + transformname = 'gradientTransform' + + def __init__(self, inherit=None, **extra): + super(_AbstractGradient, self).__init__(**extra) + if inherit is not None: + if is_string(inherit): + self.set_href(inherit) + else: + self.set_href(inherit.get_iri()) + + def get_paint_server(self, default='none'): + """ Returns the of the gradient. """ + return "%s %s" % (self.get_funciri(), default) + + def add_stop_color(self, offset=None, color=None, opacity=None): + """ Adds a stop-color to the gradient. + + :param offset: is either a (usually ranging from 0 to 1) or + a `` (usually ranging from 0% to 100%) which indicates where + the gradient stop is placed. Represents a location along the gradient + vector. For radial gradients, it represents a percentage distance from + (fx,fy) to the edge of the outermost/largest circle. + :param color: indicates what color to use at that gradient stop + :param opacity: defines the opacity of a given gradient stop + """ + self.add(_GradientStop(offset, color, opacity, factory=self)) + return self + + def add_colors(self, colors, sweep=(0., 1.), opacity=None): + """ Add stop-colors from colors with linear offset distributuion + from sweep[0] to sweep[1]. + + i.e. colors=['white', 'red', 'blue'] + 'white': offset = 0.0 + 'red': offset = 0.5 + 'blue': offset = 1.0 + """ + delta = (sweep[1] - sweep[0]) / (len(colors) - 1) + offset = sweep[0] + for color in colors: + self.add_stop_color(round(offset, 3), color, opacity) + offset += delta + return self + + def get_xml(self): + if hasattr(self, 'href'): + self.update_id() + return super(_AbstractGradient, self).get_xml() + + +class LinearGradient(_AbstractGradient): + """ Linear gradients are defined by a SVG element. + """ + elementname = 'linearGradient' + + def __init__(self, start=None, end=None, inherit=None, **extra): + """ + :param 2-tuple start: start point of the gradient (**x1**, **y1**) + :param 2-tuple end: end point of the gradient (**x2**, **y2**) + :param inherit: gradient inherits properties from `inherit` see: **xlink:href** + + """ + super(LinearGradient, self).__init__(inherit=inherit, **extra) + if start is not None: + self['x1'] = start[0] + self['y1'] = start[1] + if end is not None: + self['x2'] = end[0] + self['y2'] = end[1] + + +class RadialGradient(_AbstractGradient): + """ Radial gradients are defined by a SVG element. + """ + elementname = 'radialGradient' + + def __init__(self, center=None, r=None, focal=None, inherit=None, **extra): + """ + :param 2-tuple center: center point for the gradient (**cx**, **cy**) + :param r: radius for the gradient + :param 2-tuple focal: focal point for the radial gradient (**fx**, **fy**) + :param inherit: gradient inherits properties from `inherit` see: **xlink:href** + + """ + + super(RadialGradient, self).__init__(inherit=inherit, **extra) + if center is not None: + self['cx'] = center[0] + self['cy'] = center[1] + if r is not None: + self['r'] = r + if focal is not None: + self['fx'] = focal[0] + self['fy'] = focal[1] diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/masking.py b/videollama2/lib/python3.10/site-packages/svgwrite/masking.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c344bf5d87c72884c2e17e25c01ef9f9a2eec9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/masking.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: masking module +# Created: 30.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.base import BaseElement +from svgwrite.mixins import Transform + + +class ClipPath(BaseElement, Transform): + """ + The clipping path restricts the region to which paint can be applied. + Conceptually, any parts of the drawing that lie outside of the region + bounded by the currently active clipping path are not drawn. A clipping + path can be thought of as a mask wherein those pixels outside the clipping + path are black with an alpha value of zero and those pixels inside the + clipping path are white with an alpha value of one (with the possible + exception of anti-aliasing along the edge of the silhouette). + + A **clipPath** element can contain **path** elements, **text** elements, + basic shapes (such as **circle**) or a **use** element. If a **use** + element is a child of a **clipPath** element, it must directly reference + **path**, **text** or basic shape elements. Indirect references are an + error. + """ + elementname = 'clipPath' + + +class Mask(BaseElement): + """ + In SVG, you can specify that any other graphics object or **g** element + can be used as an alpha mask for compositing the current object into the + background. + + A **mask** can contain any graphical elements or container elements such + as a **g**. + """ + elementname = 'mask' + + def __init__(self, start=None, size=None, **extra): + super(Mask, self).__init__(**extra) + if start is not None: + self['x'] = start[0] + self['y'] = start[1] + if size is not None: + self['width'] = size[0] + self['height'] = size[1] diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/shapes.py b/videollama2/lib/python3.10/site-packages/svgwrite/shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..dcff9690b14b548aba6641d42b63d8e4809bd41c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/shapes.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman +# Purpose: svg shapes +# Created: 08.09.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.base import BaseElement +from svgwrite.mixins import Presentation, Markers, Transform + + +class Line(BaseElement, Transform, Presentation, Markers): + """ The **line** element defines a line segment that starts at one point + and ends at another. + """ + elementname = 'line' + + def __init__(self, start=(0, 0), end=(0, 0), **extra): + """ + :param 2-tuple start: start point (**x1**, **y1**) + :param 2-tuple end: end point (**x2**, **y2**) + :param extra: additional SVG attributes as keyword-arguments + + """ + super(Line, self).__init__(**extra) + x1, y1 = start + x2, y2 = end + self['x1'] = x1 + self['y1'] = y1 + self['x2'] = x2 + self['y2'] = y2 + + +class Rect(BaseElement, Transform, Presentation): + """ The **rect** element defines a rectangle which is axis-aligned with the current + user coordinate system. Rounded rectangles can be achieved by setting appropriate + values for attributes **rx** and **ry**. + """ + elementname = 'rect' + + def __init__(self, insert=(0, 0), size=(1, 1), rx=None, ry=None, **extra): + """ + :param 2-tuple insert: insert point (**x**, **y**), left-upper point + :param 2-tuple size: (**width**, **height**) + :param rx: corner x-radius + :param ry: corner y-radius + :param extra: additional SVG attributes as keyword-arguments + + """ + super(Rect, self).__init__(**extra) + x, y = insert + width, height = size + self['x'] = x + self['y'] = y + self['width'] = width + self['height'] = height + if rx is not None: + self['rx'] = rx + if ry is not None: + self['ry'] = ry + + +class Circle(BaseElement, Transform, Presentation): + """ The **circle** element defines a circle based on a center point and a radius. + """ + elementname = 'circle' + + def __init__(self, center=(0, 0), r=1, **extra): + """ + :param 2-tuple center: circle center point (**cx**, **cy**) + :param length r: circle-radius **r** + :param extra: additional SVG attributes as keyword-arguments + + """ + super(Circle, self).__init__(**extra) + cx, cy = center + self['cx'] = cx + self['cy'] = cy + self['r'] = r + + +class Ellipse(BaseElement, Transform, Presentation): + """ The **ellipse** element defines an ellipse which is axis-aligned with the + current user coordinate system based on a center point and two radii. + """ + elementname = 'ellipse' + + def __init__(self, center=(0, 0), r=(1, 1), **extra): + """ + :param 2-tuple center: ellipse center point (**cx**, **cy**) + :param 2-tuple r: ellipse radii (**rx**, **ry**) + :param extra: additional SVG attributes as keyword-arguments + + """ + super(Ellipse, self).__init__(**extra) + cx, cy = center + rx, ry = r + self['cx'] = cx + self['cy'] = cy + self['rx'] = rx + self['ry'] = ry + + +class Polyline(BaseElement, Transform, Presentation, Markers): + """ The **polyline** element defines a set of connected straight line + segments. Typically, **polyline** elements define open shapes. + """ + elementname = 'polyline' + + def __init__(self, points=[], **extra): + """ + :param `iterable` points: `iterable` of points (points are `2-tuples`) + :param extra: additional SVG attributes as keyword-arguments + + """ + super(Polyline, self).__init__(**extra) + self.points = list(points) + if self.debug: + for point in self.points: + x, y = point + self.validator.check_svg_type(x, 'coordinate') + self.validator.check_svg_type(y, 'coordinate') + + def get_xml(self): + self.attribs['points'] = self.points_to_string(self.points) + return super(Polyline, self).get_xml() + + def points_to_string(self, points): + """ + Convert a `list` of points `2-tuples` to a `string` ``'p1x,p1y p2x,p2y ...'``. + + """ + strings = [] + for point in points: + if len(point) != 2: + raise TypeError('got %s values, but expected 2 values.' % len(point)) + x, y = point + if self.debug: + self.validator.check_svg_type(x, 'coordinate') + self.validator.check_svg_type(y, 'coordinate') + if self.profile == 'tiny': + if isinstance(x, float): + x = round(x, 4) + if isinstance(y, float): + y = round(y, 4) + point = "%s,%s" % (x, y) + strings.append(point) + return ' '.join(strings) + + +class Polygon(Polyline): + """ The **polygon** element defines a closed shape consisting of a set of + connected straight line segments. + + Same as :class:`~svgwrite.shapes.Polyline` but closed. + """ + elementname = 'polygon' + diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/solidcolor.py b/videollama2/lib/python3.10/site-packages/svgwrite/solidcolor.py new file mode 100644 index 0000000000000000000000000000000000000000..148821b848c4d8487eaeca106164175c322a0903 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/solidcolor.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: solidColor paint serve (Tiny 1.2 profile) +# Created: 26.10.2016 +# Copyright (C) 2016, Manfred Moitzi +# License: MIT License + +from svgwrite.base import BaseElement +from svgwrite.mixins import XLink + + +class SolidColor(BaseElement, XLink): + """ + The `solidColor` element is a paint server that provides a single color with opacity. + It can be referenced like the other paint servers (i.e. gradients). + The `color` parameter specifies the color that shall be used for this `solidColor` element. + The keyword ``"currentColor"`` can be specified in the same manner as within a specification for the `fill` + and `stroke` properties. The `opacity` parameter defines the opacity of the `solidColor`. + """ + elementname = 'solidColor' + + def __init__(self, color="currentColor", opacity=None, **extra): + """ + :param color: solid color like the other paint servers (i.e. gradients). + :param float opacity: opacity of the solid color in the range `0.0` (fully transparent) to `1.0` (fully opaque) + + """ + super(SolidColor, self).__init__(**extra) + if self.profile != 'tiny': + raise TypeError("Paint server 'solidColor' requires the Tiny SVG profile.") + self['solid-color'] = color + if opacity is not None: + self['solid-opacity'] = opacity + + if self.debug: + self.validator.check_all_svg_attribute_values(self.elementname, self.attribs) + + def get_paint_server(self, default='none'): + """ Returns the of the gradient. """ + return "%s %s" % (self.get_funciri(), default) diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/utils.py b/videollama2/lib/python3.10/site-packages/svgwrite/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7095813e8d0fa7052b0a7be9230ee0150b288a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/utils.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python +# coding:utf-8 +# Author: mozman +# Purpose: svg util functions and classes +# Created: 08.09.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License +""" + +.. autofunction:: rgb + +.. autofunction:: iterflatlist + +.. autofunction:: strlist + +.. autofunction:: get_unit + +.. autofunction:: split_coordinate + +.. autofunction:: split_angle + +.. autofunction:: rect_top_left_corner + +.. autofunction:: pretty_xml + +""" +import base64 +from pathlib import Path +from svgwrite.data import pattern + + +def is_string(value): + return isinstance(value, str) + + +def rgb(r=0, g=0, b=0, mode='RGB'): + """ + Convert **r**, **g**, **b** values to a `string`. + + :param r: red part + :param g: green part + :param b: blue part + :param string mode: ``'RGB | %'`` + + :rtype: string + + ========= ============================================================= + mode Description + ========= ============================================================= + ``'RGB'`` returns a rgb-string format: ``'rgb(r, g, b)'`` + ``'%'`` returns percent-values as rgb-string format: ``'rgb(r%, g%, b%)'`` + ========= ============================================================= + + """ + + def percent(value): + value = float(value) + if value < 0: + value = 0 + if value > 100: + value = 100 + return value + + if mode.upper() == 'RGB': + return "rgb(%d,%d,%d)" % (int(r) & 255, int(g) & 255, int(b) & 255) + elif mode == "%": + # see http://www.w3.org/TR/SVG11/types.html#DataTypeColor + # percentage is an 'number' value + return "rgb(%d%%,%d%%,%d%%)" % (percent(r), percent(g), percent(b)) + else: + raise ValueError("Invalid mode '%s'" % mode) + + +def iterflatlist(values): + """ + Flatten nested *values*, returns an `iterator`. + + """ + for element in values: + if hasattr(element, "__iter__") and not is_string(element): + for item in iterflatlist(element): + yield item + else: + yield element + + +def strlist(values, seperator=","): + """ + Concatenate **values** with **sepertator**, `None` values will be excluded. + + :param values: `iterable` object + :returns: `string` + + """ + if is_string(values): + return values + else: + return seperator.join([str(value) for value in iterflatlist(values) if value is not None]) + + +def get_unit(coordinate): + """ + Get the `unit` identifier of **coordinate**, if **coordinate** has a valid + `unit` identifier appended, else returns `None`. + + """ + if isinstance(coordinate, (int, float)): + return None + result = pattern.coordinate.match(coordinate) + if result: + return result.group(3) + else: + raise ValueError("Invalid format: '%s'" % coordinate) + + +def split_coordinate(coordinate): + """ + Split coordinate into `` and 'unit` identifier. + + :returns: <2-tuple> (number, unit-identifier) or (number, None) if no unit-identifier + is present or coordinate is an int or float. + + """ + if isinstance(coordinate, (int, float)): + return (float(coordinate), None) + result = pattern.coordinate.match(coordinate) + if result: + return (float(result.group(1)), result.group(3)) + else: + raise ValueError("Invalid format: '%s'" % coordinate) + + +def split_angle(angle): + """ + Split angle into `` and `` identifier. + + :returns: <2-tuple> (number, angle-identifier) or (number, None) if no angle-identifier + is present or angle is an int or float. + + """ + + if isinstance(angle, (int, float)): + return (float(angle), None) + result = pattern.angle.match(angle) + if result: + return (float(result.group(1)), result.group(3)) + else: + raise ValueError("Invalid format: '%s'" % angle) + + +def rect_top_left_corner(insert, size, pos='top-left'): + """ + Calculate top-left corner of a rectangle. + + **insert** and **size** must have the same units. + + :param 2-tuple insert: insert point + :param 2-tuple size: (width, height) + :param string pos: insert position ``'vert-horiz'`` + :return: ``'top-left'`` corner of the rect + :rtype: 2-tuple + + ========== ============================== + pos valid values + ========== ============================== + **vert** ``'top | middle | bottom'`` + **horiz** ``'left'|'center'|'right'`` + ========== ============================== + """ + vert, horiz = pos.lower().split('-') + x, xunit = split_coordinate(insert[0]) + y, yunit = split_coordinate(insert[1]) + width, wunit = split_coordinate(size[0]) + height, hunit = split_coordinate(size[1]) + + if xunit != wunit: + raise ValueError("x-coordinate and width has to have the same unit") + if yunit != hunit: + raise ValueError("y-coordinate and height has to have the same unit") + + if horiz == 'center': + x = x - width / 2. + elif horiz == 'right': + x = x - width + elif horiz != 'left': + raise ValueError("Invalid horizontal position: '%s'" % horiz) + + if vert == 'middle': + y = y - height / 2. + elif vert == 'bottom': + y = y - height + elif vert != 'top': + raise ValueError("Invalid vertical position: '%s'" % vert) + + if xunit: + x = "%s%s" % (x, xunit) + if yunit: + y = "%s%s" % (y, yunit) + return x, y + + +class AutoID(object): + _nextid = 1 + + def __init__(self, value=None): + self._set_value(value) + + @classmethod + def _set_value(cls, value=None): + if value is not None: + cls._nextid = value + + @classmethod + def next_id(cls, value=None): + cls._set_value(value) + retval = "id%d" % cls._nextid + cls._nextid += 1 + return retval + + +def pretty_xml(xml_string, indent=2): + """ + Create human readable XML string. + + :param xml_string: input xml string without line breaks and indentation + :indent int: how much to indent, by default 2 spaces + :return: xml_string with linebreaks and indentation + + """ + import xml.dom.minidom as minidom + + # check for empty string, len check avoids unnecessary string manipulation with large XML strings + if len(xml_string) < 20 and xml_string.strip() == "": + return "" + xml_tree = minidom.parseString(xml_string) + lines = xml_tree.toprettyxml(indent=' ' * indent).split('\n') + # remove 1. line = xml declaration + return '\n'.join(lines[1:]) + + +FONT_MIMETYPES = { + 'ttf': "application/x-font-ttf", + 'otf': "application/x-font-opentype", + 'woff': "application/font-woff", + 'woff2': "application/font-woff2", + 'eot': "application/vnd.ms-fontobject", + 'sfnt': "application/font-sfnt", +} + + +def font_mimetype(name): + return FONT_MIMETYPES[Path(name.lower()).suffix[1:]] + + +def base64_data(data, mimetype): + data = base64.b64encode(data).decode() + return "data:{mimetype};charset=utf-8;base64,{data}".format(mimetype=mimetype, data=data) + + +def find_first_url(text): + import re + result = re.findall(r"url\((.*?)\)", text) + if result: + return result[0] + else: + return None diff --git a/videollama2/lib/python3.10/site-packages/svgwrite/validator2.py b/videollama2/lib/python3.10/site-packages/svgwrite/validator2.py new file mode 100644 index 0000000000000000000000000000000000000000..0121ff08ee9d52bddc21b6ef9b2b0fe633660d3f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/svgwrite/validator2.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman -- +# Purpose: validator2 module - new validator module +# Created: 01.10.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License + +from svgwrite.data import full11 +from svgwrite.data import tiny12 +from svgwrite.data import pattern + +validator_cache = {} + + +def cache_key(profile, debug): + return str(profile) + str(debug) + + +def get_validator(profile, debug=True): + """ Validator factory """ + try: + return validator_cache[cache_key(profile, debug)] + except KeyError: + if profile == 'tiny': + validator = Tiny12Validator(debug) + elif profile in ('full', 'basic', 'none'): + validator = Full11Validator(debug) + else: + raise ValueError("Unsupported profile: '%s'" % profile) + validator_cache[cache_key(profile, debug)] = validator + return validator + + +class Tiny12Validator(object): + profilename = "Tiny 1.2" + + def __init__(self, debug=True): + self.debug = debug + self.attributes = tiny12.attributes + self.elements = tiny12.elements + self.typechecker = tiny12.TypeChecker() + + def check_all_svg_attribute_values(self, elementname, attributes): + """ + Check if attributes are valid for object 'elementname' and all svg + attributes have valid types and values. + + Raises ValueError. + """ + for attributename, value in attributes.items(): + self.check_svg_attribute_value(elementname, attributename, value) + + def check_svg_attribute_value(self, elementname, attributename, value): + """ + Check if 'attributename' is valid for object 'elementname' and 'value' + is a valid svg type and value. + + Raises ValueError. + """ + self._check_valid_svg_attribute_name(elementname, attributename) + self._check_svg_value(elementname, attributename, value) + + def _check_svg_value(self, elementname, attributename, value): + """ + Checks if 'value' is a valid svg-type for svg-attribute + 'attributename' at svg-element 'elementname'. + + Raises TypeError. + """ + attribute = self.attributes[attributename] + # check if 'value' match a valid datatype + for typename in attribute.get_types(elementname): + if self.typechecker.check(typename, value): + return + # check if 'value' is a valid constant + valuestr = str(value) + if not valuestr in attribute.get_const(elementname): + raise TypeError("'%s' is not a valid value for attribute '%s' at svg-element <%s>." % (value, attributename, elementname)) + + def _check_valid_svg_attribute_name(self, elementname, attributename): + """ Check if 'attributename' is a valid svg-attribute for svg-element + 'elementname'. + + Raises ValueError. + """ + if not self.is_valid_svg_attribute(elementname, attributename): + raise ValueError("Invalid attribute '%s' for svg-element <%s>." % (attributename, elementname)) + + def _get_element(self, elementname): + try: + return self.elements[elementname] + except KeyError: + raise KeyError("<%s> is not valid for selected profile: '%s'." % (elementname, self.profilename)) + + def check_svg_type(self, value, typename='string'): + """ + Check if 'value' matches svg type 'typename'. + + Raises TypeError. + """ + if self.typechecker.check(typename, value): + return value + else: + raise TypeError("%s is not of type '%s'." % (value, typename)) + + def is_valid_svg_type(self, value, typename): + return self.typechecker.check(typename, value) + + def is_valid_elementname(self, elementname): + """ True if 'elementname' is a valid svg-element name. """ + return elementname in self.elements + + def is_valid_svg_attribute(self, elementname, attributename): + """ True if 'attributename' is a valid svg-attribute for svg-element + 'elementname'. + """ + element = self._get_element(elementname) + return attributename in element.valid_attributes + + def is_valid_children(self, elementname, childrenname): + """ True if svg-element 'childrenname' is a valid children of + svg-element 'elementname'. + """ + element = self._get_element(elementname) + return childrenname in element.valid_children + + def check_valid_children(self, elementname, childrenname): + """ Checks if svg-element 'childrenname' is a valid children of + svg-element 'elementname'. + + Raises ValueError. + """ + if not self.is_valid_children(elementname, childrenname): + raise ValueError("Invalid children '%s' for svg-element <%s>." % (childrenname, elementname)) + + def get_coordinate(self, value): + """ Split value in (number, unit) if value has an unit or (number, None). + + Raises ValueError. + """ + + if value is None: + raise TypeError("Invalid type 'None'.") + if isinstance(value, (int, float)): + result = (value, None) + else: + result = pattern.coordinate.match(value.strip()) + if result: + number, tmp, unit = result.groups() + number = float(number) + else: + raise ValueError("'%s' is not a valid svg-coordinate." % value) + result = (number, unit) + if self.typechecker.is_number(result[0]): + return result + else: + version = "SVG %s %s" % self.typechecker.get_version() + raise ValueError("%s is not a valid number for: %s." % (value, version)) + get_length = get_coordinate + + +class Full11Validator(Tiny12Validator): + profilename = "Full 1.1" + + def __init__(self, debug=True): + self.debug = debug + self.attributes = full11.attributes + self.elements = full11.elements + self.typechecker = full11.TypeChecker() diff --git a/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..aa6f76041b65b2e8a0545493d6bd1afc2f34d668 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py @@ -0,0 +1,70 @@ +""" + pygments.filter + ~~~~~~~~~~~~~~~ + + Module that implements the default filter. + + :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + + +def apply_filters(stream, filters, lexer=None): + """ + Use this method to apply an iterable of filters to + a stream. If lexer is given it's forwarded to the + filter, otherwise the filter receives `None`. + """ + def _apply(filter_, stream): + yield from filter_.filter(lexer, stream) + for filter_ in filters: + stream = _apply(filter_, stream) + return stream + + +def simplefilter(f): + """ + Decorator that converts a function into a filter:: + + @simplefilter + def lowercase(self, lexer, stream, options): + for ttype, value in stream: + yield ttype, value.lower() + """ + return type(f.__name__, (FunctionFilter,), { + '__module__': getattr(f, '__module__'), + '__doc__': f.__doc__, + 'function': f, + }) + + +class Filter: + """ + Default filter. Subclass this class or use the `simplefilter` + decorator to create own filters. + """ + + def __init__(self, **options): + self.options = options + + def filter(self, lexer, stream): + raise NotImplementedError() + + +class FunctionFilter(Filter): + """ + Abstract class used by `simplefilter` to create simple + function filters on the fly. The `simplefilter` decorator + automatically creates subclasses of this class for + functions passed to it. + """ + function = None + + def __init__(self, **options): + if not hasattr(self, 'function'): + raise TypeError(f'{self.__class__.__name__!r} used without bound function') + Filter.__init__(self, **options) + + def filter(self, lexer, stream): + # pylint: disable=not-callable + yield from self.function(lexer, stream, self.options) diff --git a/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/regexopt.py b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/regexopt.py new file mode 100644 index 0000000000000000000000000000000000000000..c44eedbf2ad7559757dde19c98d9ddb5cd8b2406 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/regexopt.py @@ -0,0 +1,91 @@ +""" + pygments.regexopt + ~~~~~~~~~~~~~~~~~ + + An algorithm that generates optimized regexes for matching long lists of + literal strings. + + :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re +from re import escape +from os.path import commonprefix +from itertools import groupby +from operator import itemgetter + +CS_ESCAPE = re.compile(r'[\[\^\\\-\]]') +FIRST_ELEMENT = itemgetter(0) + + +def make_charset(letters): + return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']' + + +def regex_opt_inner(strings, open_paren): + """Return a regex that matches any string in the sorted list of strings.""" + close_paren = open_paren and ')' or '' + # print strings, repr(open_paren) + if not strings: + # print '-> nothing left' + return '' + first = strings[0] + if len(strings) == 1: + # print '-> only 1 string' + return open_paren + escape(first) + close_paren + if not first: + # print '-> first string empty' + return open_paren + regex_opt_inner(strings[1:], '(?:') \ + + '?' + close_paren + if len(first) == 1: + # multiple one-char strings? make a charset + oneletter = [] + rest = [] + for s in strings: + if len(s) == 1: + oneletter.append(s) + else: + rest.append(s) + if len(oneletter) > 1: # do we have more than one oneletter string? + if rest: + # print '-> 1-character + rest' + return open_paren + regex_opt_inner(rest, '') + '|' \ + + make_charset(oneletter) + close_paren + # print '-> only 1-character' + return open_paren + make_charset(oneletter) + close_paren + prefix = commonprefix(strings) + if prefix: + plen = len(prefix) + # we have a prefix for all strings + # print '-> prefix:', prefix + return open_paren + escape(prefix) \ + + regex_opt_inner([s[plen:] for s in strings], '(?:') \ + + close_paren + # is there a suffix? + strings_rev = [s[::-1] for s in strings] + suffix = commonprefix(strings_rev) + if suffix: + slen = len(suffix) + # print '-> suffix:', suffix[::-1] + return open_paren \ + + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \ + + escape(suffix[::-1]) + close_paren + # recurse on common 1-string prefixes + # print '-> last resort' + return open_paren + \ + '|'.join(regex_opt_inner(list(group[1]), '') + for group in groupby(strings, lambda s: s[0] == first[0])) \ + + close_paren + + +def regex_opt(strings, prefix='', suffix=''): + """Return a compiled regex that matches any string in the given list. + + The strings to match must be literal strings, not regexes. They will be + regex-escaped. + + *prefix* and *suffix* are pre- and appended to the final regex. + """ + strings = sorted(strings) + return prefix + regex_opt_inner(strings, '(') + suffix diff --git a/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/token.py b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/token.py new file mode 100644 index 0000000000000000000000000000000000000000..f78018a7aa7a714360d4bbfa1fdbb2ebee57ac74 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/pip/_vendor/pygments/token.py @@ -0,0 +1,214 @@ +""" + pygments.token + ~~~~~~~~~~~~~~ + + Basic token types and the standard tokens. + + :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + + +class _TokenType(tuple): + parent = None + + def split(self): + buf = [] + node = self + while node is not None: + buf.append(node) + node = node.parent + buf.reverse() + return buf + + def __init__(self, *args): + # no need to call super.__init__ + self.subtypes = set() + + def __contains__(self, val): + return self is val or ( + type(val) is self.__class__ and + val[:len(self)] == self + ) + + def __getattr__(self, val): + if not val or not val[0].isupper(): + return tuple.__getattribute__(self, val) + new = _TokenType(self + (val,)) + setattr(self, val, new) + self.subtypes.add(new) + new.parent = self + return new + + def __repr__(self): + return 'Token' + (self and '.' or '') + '.'.join(self) + + def __copy__(self): + # These instances are supposed to be singletons + return self + + def __deepcopy__(self, memo): + # These instances are supposed to be singletons + return self + + +Token = _TokenType() + +# Special token types +Text = Token.Text +Whitespace = Text.Whitespace +Escape = Token.Escape +Error = Token.Error +# Text that doesn't belong to this lexer (e.g. HTML in PHP) +Other = Token.Other + +# Common token types for source code +Keyword = Token.Keyword +Name = Token.Name +Literal = Token.Literal +String = Literal.String +Number = Literal.Number +Punctuation = Token.Punctuation +Operator = Token.Operator +Comment = Token.Comment + +# Generic types for non-source code +Generic = Token.Generic + +# String and some others are not direct children of Token. +# alias them: +Token.Token = Token +Token.String = String +Token.Number = Number + + +def is_token_subtype(ttype, other): + """ + Return True if ``ttype`` is a subtype of ``other``. + + exists for backwards compatibility. use ``ttype in other`` now. + """ + return ttype in other + + +def string_to_tokentype(s): + """ + Convert a string into a token type:: + + >>> string_to_token('String.Double') + Token.Literal.String.Double + >>> string_to_token('Token.Literal.Number') + Token.Literal.Number + >>> string_to_token('') + Token + + Tokens that are already tokens are returned unchanged: + + >>> string_to_token(String) + Token.Literal.String + """ + if isinstance(s, _TokenType): + return s + if not s: + return Token + node = Token + for item in s.split('.'): + node = getattr(node, item) + return node + + +# Map standard token types to short names, used in CSS class naming. +# If you add a new item, please be sure to run this file to perform +# a consistency check for duplicate values. +STANDARD_TYPES = { + Token: '', + + Text: '', + Whitespace: 'w', + Escape: 'esc', + Error: 'err', + Other: 'x', + + Keyword: 'k', + Keyword.Constant: 'kc', + Keyword.Declaration: 'kd', + Keyword.Namespace: 'kn', + Keyword.Pseudo: 'kp', + Keyword.Reserved: 'kr', + Keyword.Type: 'kt', + + Name: 'n', + Name.Attribute: 'na', + Name.Builtin: 'nb', + Name.Builtin.Pseudo: 'bp', + Name.Class: 'nc', + Name.Constant: 'no', + Name.Decorator: 'nd', + Name.Entity: 'ni', + Name.Exception: 'ne', + Name.Function: 'nf', + Name.Function.Magic: 'fm', + Name.Property: 'py', + Name.Label: 'nl', + Name.Namespace: 'nn', + Name.Other: 'nx', + Name.Tag: 'nt', + Name.Variable: 'nv', + Name.Variable.Class: 'vc', + Name.Variable.Global: 'vg', + Name.Variable.Instance: 'vi', + Name.Variable.Magic: 'vm', + + Literal: 'l', + Literal.Date: 'ld', + + String: 's', + String.Affix: 'sa', + String.Backtick: 'sb', + String.Char: 'sc', + String.Delimiter: 'dl', + String.Doc: 'sd', + String.Double: 's2', + String.Escape: 'se', + String.Heredoc: 'sh', + String.Interpol: 'si', + String.Other: 'sx', + String.Regex: 'sr', + String.Single: 's1', + String.Symbol: 'ss', + + Number: 'm', + Number.Bin: 'mb', + Number.Float: 'mf', + Number.Hex: 'mh', + Number.Integer: 'mi', + Number.Integer.Long: 'il', + Number.Oct: 'mo', + + Operator: 'o', + Operator.Word: 'ow', + + Punctuation: 'p', + Punctuation.Marker: 'pm', + + Comment: 'c', + Comment.Hashbang: 'ch', + Comment.Multiline: 'cm', + Comment.Preproc: 'cp', + Comment.PreprocFile: 'cpf', + Comment.Single: 'c1', + Comment.Special: 'cs', + + Generic: 'g', + Generic.Deleted: 'gd', + Generic.Emph: 'ge', + Generic.Error: 'gr', + Generic.Heading: 'gh', + Generic.Inserted: 'gi', + Generic.Output: 'go', + Generic.Prompt: 'gp', + Generic.Strong: 'gs', + Generic.Subheading: 'gu', + Generic.EmphStrong: 'ges', + Generic.Traceback: 'gt', +}