ZTWHHH commited on
Commit
ccfa07a
·
verified ·
1 Parent(s): 824f82f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videollama2/lib/python3.10/site-packages/blobfile/VERSION +1 -0
  2. videollama2/lib/python3.10/site-packages/blobfile/__init__.py +85 -0
  3. videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_common.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_context.cpython-310.pyc +0 -0
  5. videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_xml_test.cpython-310.pyc +0 -0
  6. videollama2/lib/python3.10/site-packages/blobfile/_azure.py +1689 -0
  7. videollama2/lib/python3.10/site-packages/blobfile/_context.py +1518 -0
  8. videollama2/lib/python3.10/site-packages/blobfile/_gcp.py +786 -0
  9. videollama2/lib/python3.10/site-packages/blobfile/_ops.py +401 -0
  10. videollama2/lib/python3.10/site-packages/blobfile/_ops_test.py +1675 -0
  11. videollama2/lib/python3.10/site-packages/blobfile/_xml.py +78 -0
  12. videollama2/lib/python3.10/site-packages/blobfile/_xml_test.py +163 -0
  13. videollama2/lib/python3.10/site-packages/blobfile/py.typed +0 -0
  14. videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/LICENSE.txt +59 -0
  15. videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/RECORD +11 -0
  16. videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/REQUESTED +0 -0
  17. videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/entry_points.txt +3 -0
  18. videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/top_level.txt +1 -0
  19. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER +1 -0
  20. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE +21 -0
  21. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA +34 -0
  22. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD +13 -0
  23. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED +0 -0
  24. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL +5 -0
  25. videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt +1 -0
  26. videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/INSTALLER +1 -0
  27. videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/METADATA +87 -0
  28. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/__init__.cpython-310.pyc +0 -0
  29. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/animate.cpython-310.pyc +0 -0
  30. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/base.cpython-310.pyc +0 -0
  31. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/container.cpython-310.pyc +0 -0
  32. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/drawing.cpython-310.pyc +0 -0
  33. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/elementfactory.cpython-310.pyc +0 -0
  34. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/filters.cpython-310.pyc +0 -0
  35. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/masking.cpython-310.pyc +0 -0
  36. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/mixins.cpython-310.pyc +0 -0
  37. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/params.cpython-310.pyc +0 -0
  38. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/path.cpython-310.pyc +0 -0
  39. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/pattern.cpython-310.pyc +0 -0
  40. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/shapes.cpython-310.pyc +0 -0
  41. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/utils.cpython-310.pyc +0 -0
  42. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/validator2.cpython-310.pyc +0 -0
  43. videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/version.cpython-310.pyc +0 -0
  44. videollama2/lib/python3.10/site-packages/svgwrite/animate.py +183 -0
  45. videollama2/lib/python3.10/site-packages/svgwrite/base.py +285 -0
  46. videollama2/lib/python3.10/site-packages/svgwrite/data/__init__.py +0 -0
  47. videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/__init__.cpython-310.pyc +0 -0
  48. videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/colors.cpython-310.pyc +0 -0
  49. videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/full11.cpython-310.pyc +0 -0
  50. videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/pattern.cpython-310.pyc +0 -0
videollama2/lib/python3.10/site-packages/blobfile/VERSION ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.0.0
videollama2/lib/python3.10/site-packages/blobfile/__init__.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # all the modules are under _internal to indicate that they are not exported
4
+ # the A as A syntax seems to cause pycharm to list these
5
+ # symbols as coming from blobfile instead of blobfile._internal
6
+ from blobfile._ops import (
7
+ copy as copy,
8
+ exists as exists,
9
+ glob as glob,
10
+ scanglob as scanglob,
11
+ isdir as isdir,
12
+ listdir as listdir,
13
+ scandir as scandir,
14
+ makedirs as makedirs,
15
+ remove as remove,
16
+ rmdir as rmdir,
17
+ rmtree as rmtree,
18
+ stat as stat,
19
+ walk as walk,
20
+ basename as basename,
21
+ dirname as dirname,
22
+ join as join,
23
+ get_url as get_url,
24
+ md5 as md5,
25
+ set_mtime as set_mtime,
26
+ configure as configure,
27
+ BlobFile as BlobFile,
28
+ last_version_seen as last_version_seen,
29
+ read_bytes as read_bytes,
30
+ read_text as read_text,
31
+ write_bytes as write_bytes,
32
+ write_text as write_text,
33
+ )
34
+ from blobfile._context import Context as Context, create_context as create_context
35
+ from blobfile._common import (
36
+ Request as Request,
37
+ Error as Error,
38
+ RequestFailure as RequestFailure,
39
+ RestartableStreamingWriteFailure as RestartableStreamingWriteFailure,
40
+ ConcurrentWriteFailure as ConcurrentWriteFailure,
41
+ VersionMismatch as VersionMismatch,
42
+ DeadlineExceeded as DeadlineExceeded,
43
+ Stat as Stat,
44
+ DirEntry as DirEntry,
45
+ )
46
+
47
+
48
+ _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
49
+ with open(os.path.join(_SCRIPT_DIR, "VERSION")) as _version_file:
50
+ __version__ = _version_file.read().strip()
51
+
52
+ __all__ = [
53
+ "copy",
54
+ "exists",
55
+ "glob",
56
+ "scanglob",
57
+ "isdir",
58
+ "listdir",
59
+ "scandir",
60
+ "makedirs",
61
+ "remove",
62
+ "rmdir",
63
+ "rmtree",
64
+ "stat",
65
+ "walk",
66
+ "basename",
67
+ "dirname",
68
+ "join",
69
+ "get_url",
70
+ "md5",
71
+ "set_mtime",
72
+ "configure",
73
+ "BlobFile",
74
+ "Request",
75
+ "Error",
76
+ "RequestFailure",
77
+ "RestartableStreamingWriteFailure",
78
+ "ConcurrentWriteFailure",
79
+ "DeadlineExceeded",
80
+ "Stat",
81
+ "DirEntry",
82
+ "Context",
83
+ "create_context",
84
+ "VersionMismatch",
85
+ ]
videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_common.cpython-310.pyc ADDED
Binary file (28.7 kB). View file
 
videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_context.cpython-310.pyc ADDED
Binary file (37.1 kB). View file
 
videollama2/lib/python3.10/site-packages/blobfile/__pycache__/_xml_test.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
videollama2/lib/python3.10/site-packages/blobfile/_azure.py ADDED
@@ -0,0 +1,1689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import binascii
3
+ import calendar
4
+ import concurrent.futures
5
+ import datetime
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import time
13
+ import urllib.parse
14
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple
15
+
16
+ import urllib3
17
+
18
+ from blobfile import _common as common
19
+ from blobfile import _xml as xml
20
+ from blobfile._common import (
21
+ DEFAULT_RETRY_CODES,
22
+ INVALID_HOSTNAME_STATUS,
23
+ BaseStreamingReadFile,
24
+ BaseStreamingWriteFile,
25
+ ConcurrentWriteFailure,
26
+ Config,
27
+ DirEntry,
28
+ Error,
29
+ FileBody,
30
+ Request,
31
+ RequestFailure,
32
+ Stat,
33
+ TokenManager,
34
+ VersionMismatch,
35
+ path_join,
36
+ rng,
37
+ strip_slashes,
38
+ )
39
+
40
+ SHARED_KEY = "shared_key"
41
+ OAUTH_TOKEN = "oauth_token"
42
+ ANONYMOUS = "anonymous"
43
+
44
+ # it looks like azure signed urls cannot exceed the lifetime of the token used
45
+ # to create them, so don't keep the key around too long
46
+ SAS_TOKEN_EXPIRATION_SECONDS = 60 * 60
47
+ # these seem to be expired manually, but we don't currently detect that
48
+ SHARED_KEY_EXPIRATION_SECONDS = 24 * 60 * 60
49
+
50
+ # max 100MB https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#remarks
51
+ # there is a preview version of the API that allows this to be 4000MiB
52
+ MAX_BLOCK_SIZE = 100_000_000
53
+
54
+ BLOCK_COUNT_LIMIT = 50_000
55
+
56
+ RESPONSE_HEADER_TO_REQUEST_HEADER = {
57
+ "Cache-Control": "x-ms-blob-cache-control",
58
+ "Content-Type": "x-ms-blob-content-type",
59
+ "Content-MD5": "x-ms-blob-content-md5",
60
+ "Content-Encoding": "x-ms-blob-content-encoding",
61
+ "Content-Language": "x-ms-blob-content-language",
62
+ "Content-Disposition": "x-ms-blob-content-disposition",
63
+ }
64
+
65
+
66
+ def _load_credentials() -> Dict[str, Any]:
67
+ # When AZURE_USE_IDENTITY=1, blobfile will use the azure-identity package to retrieve AAD access tokens
68
+ if os.getenv("AZURE_USE_IDENTITY", "0") == "1":
69
+ return {"_azure_auth": "azure-identity"}
70
+
71
+ # https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#environment-variables
72
+ # AZURE_STORAGE_KEY seems to be the environment variable mentioned by the az cli
73
+ # AZURE_STORAGE_ACCOUNT_KEY is mentioned elsewhere on the internet
74
+ for varname in ["AZURE_STORAGE_KEY", "AZURE_STORAGE_ACCOUNT_KEY"]:
75
+ if varname in os.environ:
76
+ account = {}
77
+ if "AZURE_STORAGE_ACCOUNT" in os.environ:
78
+ account["account"] = os.environ["AZURE_STORAGE_ACCOUNT"]
79
+ return {"_azure_auth": "sakey", "storage_account_key": os.environ[varname], **account}
80
+
81
+ if "AZURE_STORAGE_CONNECTION_STRING" in os.environ:
82
+ connection_data = {}
83
+ # technically this should be parsed according to the rules in
84
+ # https://www.connectionstrings.com/formating-rules-for-connection-strings/
85
+ for part in os.environ["AZURE_STORAGE_CONNECTION_STRING"].split(";"):
86
+ key, _, val = part.partition("=")
87
+ connection_data[key.lower()] = val
88
+ return {
89
+ "_azure_auth": "sakey",
90
+ "account": connection_data["accountname"],
91
+ "storage_account_key": connection_data["accountkey"],
92
+ }
93
+
94
+ if "AZURE_APPLICATION_CREDENTIALS" in os.environ:
95
+ creds_path = os.environ["AZURE_APPLICATION_CREDENTIALS"]
96
+ if not os.path.exists(creds_path):
97
+ raise Error(
98
+ f"Credentials not found at '{creds_path}' specified by environment variable 'AZURE_APPLICATION_CREDENTIALS'"
99
+ )
100
+ with open(creds_path) as f:
101
+ creds = json.load(f)
102
+ return {
103
+ "_azure_auth": "svcact",
104
+ "client_id": creds["appId"],
105
+ "client_secret": creds["password"],
106
+ "tenant_id": creds["tenant"],
107
+ }
108
+
109
+ if "AZURE_CLIENT_ID" in os.environ:
110
+ return {
111
+ "_azure_auth": "svcact",
112
+ "client_id": os.environ["AZURE_CLIENT_ID"],
113
+ "client_secret": os.environ["AZURE_CLIENT_SECRET"],
114
+ "tenant_id": os.environ["AZURE_TENANT_ID"],
115
+ }
116
+
117
+ # look for a refresh token in the az command line credentials
118
+ # we could also try to use any found access tokens
119
+ msal_tokens_path = os.path.expanduser("~/.azure/msal_token_cache.json")
120
+ if os.path.exists(msal_tokens_path):
121
+ with open(msal_tokens_path) as f:
122
+ tokens = json.load(f)
123
+ for token in tokens.get("RefreshToken", {}).values():
124
+ if token["credential_type"] != "RefreshToken":
125
+ continue
126
+ return {"_azure_auth": "refresh", "refresh_token": token["secret"]}
127
+
128
+ access_tokens_path = os.path.expanduser("~/.azure/accessTokens.json")
129
+ if os.path.exists(access_tokens_path):
130
+ with open(access_tokens_path) as f:
131
+ tokens = json.load(f)
132
+ best_token = None
133
+ for token in tokens:
134
+ if "refreshToken" not in token:
135
+ continue
136
+ creds = {"_azure_auth": "refresh", "refresh_token": token["refreshToken"]}
137
+ if best_token is None:
138
+ best_token = creds
139
+ else:
140
+ # expiresOn may be missing for tokens from service principals
141
+ if token.get("expiresOn", "") > best_token.get("expiresOn", ""):
142
+ best_token = creds
143
+ if best_token is not None:
144
+ return best_token
145
+
146
+ return {}
147
+
148
+
149
+ def load_subscription_ids() -> List[str]:
150
+ """
151
+ Return a list of subscription ids from the local azure profile
152
+ the default subscription will appear first in the list
153
+ """
154
+ default_profile_path = os.path.expanduser("~/.azure/azureProfile.json")
155
+ if not os.path.exists(default_profile_path):
156
+ return []
157
+
158
+ with open(default_profile_path, "rb") as f:
159
+ # this file has a UTF-8 BOM
160
+ profile = json.loads(f.read().decode("utf-8-sig"))
161
+
162
+ subscriptions = profile.get("subscriptions", [])
163
+
164
+ def key_fn(x: Mapping[str, Any]) -> bool:
165
+ return x["isDefault"]
166
+
167
+ subscriptions.sort(key=key_fn, reverse=True)
168
+ return [sub["id"] for sub in subscriptions]
169
+
170
+
171
+ def build_url(account: str, template: str, **data: str) -> str:
172
+ return common.build_url(f"https://{account}.blob.core.windows.net", template, **data)
173
+
174
+
175
+ def _create_access_token_request(
176
+ creds: Mapping[str, str], scope: str, success_codes: Sequence[int] = (200,)
177
+ ) -> Request:
178
+ if creds["_azure_auth"] == "refresh":
179
+ # https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token
180
+ data = {
181
+ "grant_type": "refresh_token",
182
+ "refresh_token": creds["refresh_token"],
183
+ "scope": scope,
184
+ }
185
+ tenant_id = "common"
186
+ elif creds["_azure_auth"] == "svcact":
187
+ # 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
188
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-azure-active-directory#use-oauth-access-tokens-for-authentication
189
+ # The following Azure CLI commands will create an AzureAD service principal with sufficient access to use Azure's `client_credentials` grant type:
190
+ # az ad sp create-for-rbac --name <name>
191
+ # az account list
192
+ # az role assignment create --role "Storage Blob Data Contributor" --assignee <app_id> --scope "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.Storage/storageAccounts/<storage_account_name>"
193
+ data = {
194
+ "grant_type": "client_credentials",
195
+ "client_id": creds["client_id"],
196
+ "client_secret": creds["client_secret"],
197
+ "scope": scope,
198
+ }
199
+ tenant_id = creds["tenant_id"]
200
+ else:
201
+ raise AssertionError
202
+ return Request(
203
+ url=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token",
204
+ method="POST",
205
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
206
+ data=urllib.parse.urlencode(data).encode("utf8"),
207
+ success_codes=success_codes,
208
+ )
209
+
210
+
211
+ def create_api_request(req: Request, auth: Tuple[str, str]) -> Request:
212
+ if req.headers is None:
213
+ headers = {}
214
+ else:
215
+ headers = dict(req.headers).copy()
216
+
217
+ if req.params is None:
218
+ params = {}
219
+ else:
220
+ params = dict(req.params).copy()
221
+
222
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/previous-azure-storage-service-versions
223
+ headers["x-ms-version"] = "2019-02-02"
224
+ headers["x-ms-date"] = datetime.datetime.now(tz=datetime.timezone.utc).strftime(
225
+ "%a, %d %b %Y %H:%M:%S GMT"
226
+ )
227
+ data = req.data
228
+ if data is not None and isinstance(data, dict):
229
+ data = xml.unparse(data)
230
+
231
+ result = Request(
232
+ method=req.method,
233
+ url=req.url,
234
+ params=params,
235
+ headers=headers,
236
+ data=data,
237
+ preload_content=req.preload_content,
238
+ success_codes=tuple(req.success_codes),
239
+ retry_codes=tuple(req.retry_codes),
240
+ )
241
+
242
+ kind, token = auth
243
+ if kind == SHARED_KEY:
244
+ # make sure we are signing the request that has the ms headers added already
245
+ headers["Authorization"] = sign_with_shared_key(result, token)
246
+ elif kind == OAUTH_TOKEN:
247
+ headers["Authorization"] = f"Bearer {token}"
248
+ elif kind == ANONYMOUS:
249
+ pass
250
+ return result
251
+
252
+
253
+ def generate_signed_url(key: Mapping[str, str], url: str) -> Tuple[str, float]:
254
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature
255
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas
256
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/service-sas-examples
257
+ params = {
258
+ "st": key["SignedStart"],
259
+ "se": key["SignedExpiry"],
260
+ "sks": key["SignedService"],
261
+ "skt": key["SignedStart"],
262
+ "ske": key["SignedExpiry"],
263
+ "sktid": key["SignedTid"],
264
+ "skoid": key["SignedOid"],
265
+ # signed key version (param name not mentioned in docs)
266
+ "skv": key["SignedVersion"],
267
+ "sv": "2018-11-09", # signed version
268
+ "sr": "b", # signed resource
269
+ "sp": "r", # signed permissions
270
+ "sip": "", # signed ip
271
+ "si": "", # signed identifier
272
+ "spr": "https,http", # signed http protocol
273
+ "rscc": "", # Cache-Control header
274
+ "rscd": "", # Content-Disposition header
275
+ "rsce": "", # Content-Encoding header
276
+ "rscl": "", # Content-Language header
277
+ "rsct": "", # Content-Type header
278
+ }
279
+ u = urllib.parse.urlparse(url)
280
+ storage_account = u.netloc.split(".")[0]
281
+ canonicalized_resource = urllib.parse.unquote(f"/blob/{storage_account}/{u.path[1:]}")
282
+ parts_to_sign = (
283
+ params["sp"],
284
+ params["st"],
285
+ params["se"],
286
+ canonicalized_resource,
287
+ params["skoid"],
288
+ params["sktid"],
289
+ params["skt"],
290
+ params["ske"],
291
+ params["sks"],
292
+ params["skv"],
293
+ params["sip"],
294
+ params["spr"],
295
+ params["sv"],
296
+ params["sr"],
297
+ params["rscc"],
298
+ params["rscd"],
299
+ params["rsce"],
300
+ params["rscl"],
301
+ params["rsct"],
302
+ # this is documented on a different page
303
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#specifying-the-signed-identifier
304
+ params["si"],
305
+ )
306
+ string_to_sign = "\n".join(parts_to_sign)
307
+ params["sig"] = base64.b64encode(
308
+ hmac.digest(base64.b64decode(key["Value"]), string_to_sign.encode("utf8"), "sha256")
309
+ ).decode("utf8")
310
+ query = urllib.parse.urlencode({k: v for k, v in params.items() if v != ""})
311
+ # convert to a utc struct_time by replacing the timezone
312
+ ts = time.strptime(key["SignedExpiry"].replace("Z", "GMT"), "%Y-%m-%dT%H:%M:%S%Z")
313
+ t = calendar.timegm(ts)
314
+ return url + "?" + query, t
315
+
316
+
317
+ def split_path(path: str) -> Tuple[str, str, str]:
318
+ if path.startswith("az://"):
319
+ return split_az_path(path)
320
+ elif path.startswith("https://"):
321
+ return split_https_path(path)
322
+ else:
323
+ raise Error(f"Invalid path: '{path}'")
324
+
325
+
326
+ def split_az_path(path: str) -> Tuple[str, str, str]:
327
+ parts = path[len("az://") :].split("/")
328
+ if len(parts) < 2:
329
+ raise Error(f"Invalid path: '{path}'")
330
+ account = parts[0]
331
+ container = parts[1]
332
+ if container == "":
333
+ raise Error(f"Invalid path: '{path}'")
334
+ obj = "/".join(parts[2:])
335
+ return account, container, obj
336
+
337
+
338
+ def split_https_path(path: str) -> Tuple[str, str, str]:
339
+ parts = path[len("https://") :].split("/")
340
+ if len(parts) < 2:
341
+ raise Error(f"Invalid path: '{path}'")
342
+ hostname = parts[0]
343
+ container = parts[1]
344
+ if not hostname.endswith(".blob.core.windows.net") or container == "":
345
+ raise Error(f"Invalid path: '{path}'")
346
+ obj = "/".join(parts[2:])
347
+ account = hostname.split(".")[0]
348
+ return account, container, obj
349
+
350
+
351
+ def combine_https_path(account: str, container: str, obj: str) -> str:
352
+ return f"https://{account}.blob.core.windows.net/{container}/{obj}"
353
+
354
+
355
+ def combine_az_path(account: str, container: str, obj: str) -> str:
356
+ return f"az://{account}/{container}/{obj}"
357
+
358
+
359
+ def combine_path(conf: Config, account: str, container: str, obj: str) -> str:
360
+ if conf.output_az_paths:
361
+ return combine_az_path(account, container, obj)
362
+ else:
363
+ return combine_https_path(account, container, obj)
364
+
365
+
366
+ def mkdirfile(conf: Config, path: str) -> None:
367
+ if not path.endswith("/"):
368
+ path += "/"
369
+ account, container, blob = split_path(path)
370
+ req = Request(
371
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
372
+ method="PUT",
373
+ headers={"x-ms-blob-type": "BlockBlob"},
374
+ success_codes=(201, 400),
375
+ )
376
+ resp = execute_api_request(conf, req)
377
+ if resp.status == 400:
378
+ raise Error(f"Unable to create directory, account/container does not exist: '{path}'")
379
+
380
+
381
+ def sign_with_shared_key(req: Request, key: str) -> str:
382
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key
383
+ params_to_sign = []
384
+ if req.params is not None:
385
+ for name, value in req.params.items():
386
+ canonical_name = name.lower()
387
+ params_to_sign.append(f"{canonical_name}:{value}")
388
+
389
+ u = urllib.parse.urlparse(req.url)
390
+ storage_account = u.netloc.split(".")[0]
391
+ canonical_url = f"/{storage_account}/{u.path[1:]}"
392
+ canonicalized_resource = "\n".join([canonical_url] + list(sorted(params_to_sign)))
393
+
394
+ if req.headers is None:
395
+ headers = {}
396
+ else:
397
+ headers = dict(req.headers)
398
+
399
+ headers_to_sign = []
400
+ for name, value in headers.items():
401
+ canonical_name = name.lower()
402
+ canonical_value = re.sub(r"\s+", " ", value).strip()
403
+ if canonical_name.startswith("x-ms-"):
404
+ headers_to_sign.append(f"{canonical_name}:{canonical_value}")
405
+ canonicalized_headers = "\n".join(sorted(headers_to_sign))
406
+
407
+ content_length = headers.get("Content-Length", "")
408
+ if req.data is not None:
409
+ content_length = str(len(req.data))
410
+
411
+ parts_to_sign = [
412
+ req.method,
413
+ headers.get("Content-Encoding", ""),
414
+ headers.get("Content-Language", ""),
415
+ content_length,
416
+ headers.get("Content-MD5", ""),
417
+ headers.get("Content-Type", ""),
418
+ headers.get("Date", ""),
419
+ headers.get("If-Modified-Since", ""),
420
+ headers.get("If-Match", ""),
421
+ headers.get("If-None-Match", ""),
422
+ headers.get("If-Unmodified-Since", ""),
423
+ headers.get("Range", ""),
424
+ canonicalized_headers,
425
+ canonicalized_resource,
426
+ ]
427
+ string_to_sign = "\n".join(parts_to_sign)
428
+
429
+ signature = base64.b64encode(
430
+ hmac.digest(base64.b64decode(key), string_to_sign.encode("utf8"), "sha256")
431
+ ).decode("utf8")
432
+
433
+ return f"SharedKey {storage_account}:{signature}"
434
+
435
+
436
+ def _get_md5(metadata: Mapping[str, Any]) -> Optional[str]:
437
+ if "Content-MD5" in metadata:
438
+ b64_encoded = metadata["Content-MD5"]
439
+ if b64_encoded is None:
440
+ return None
441
+ return base64.b64decode(b64_encoded).hex()
442
+ else:
443
+ return None
444
+
445
+
446
+ _MONTH_NAME_TO_INDEX = {
447
+ "Jan": "01",
448
+ "Feb": "02",
449
+ "Mar": "03",
450
+ "Apr": "04",
451
+ "May": "05",
452
+ "Jun": "06",
453
+ "Jul": "07",
454
+ "Aug": "08",
455
+ "Sep": "09",
456
+ "Oct": "10",
457
+ "Nov": "11",
458
+ "Dec": "12",
459
+ }
460
+
461
+
462
+ def _parse_timestamp(text: str) -> float:
463
+ # this function seems faster than using strptime
464
+ # text="Sun, 27 Sep 2009 18:41:57 GMT"
465
+ # 0 1 2 3 4 5
466
+ p = text.split()
467
+ date_string = f"{p[3]}-{_MONTH_NAME_TO_INDEX[p[2]]}-{p[1]}T{p[4]}+00:00"
468
+ dt = datetime.datetime.fromisoformat(date_string)
469
+ return dt.timestamp()
470
+
471
+
472
+ def make_stat(item: Mapping[str, str]) -> Stat:
473
+ if "Creation-Time" in item:
474
+ raw_ctime = item["Creation-Time"]
475
+ else:
476
+ raw_ctime = item["x-ms-creation-time"]
477
+ if "x-ms-meta-blobfilemtime" in item:
478
+ mtime = float(item["x-ms-meta-blobfilemtime"])
479
+ else:
480
+ mtime = _parse_timestamp(item["Last-Modified"])
481
+ return Stat(
482
+ size=int(item["Content-Length"]),
483
+ mtime=mtime,
484
+ ctime=_parse_timestamp(raw_ctime),
485
+ md5=_get_md5(item),
486
+ version=item["Etag"],
487
+ )
488
+
489
+
490
+ def _can_access_container(
491
+ conf: Config,
492
+ account: str,
493
+ container: str,
494
+ auth: Tuple[str, str],
495
+ out_failures: List[RequestFailure],
496
+ ) -> bool:
497
+ # https://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list
498
+ success_codes = [200, 403, 404, INVALID_HOSTNAME_STATUS]
499
+ if auth[0] == ANONYMOUS:
500
+ # some containers can produce a 409 error "PublicAccessNotPermitted" when accessed with an anonymous account
501
+ success_codes.append(409)
502
+
503
+ def build_req() -> Request:
504
+ req = Request(
505
+ method="GET",
506
+ url=build_url(account, "/{container}", container=container),
507
+ params={"restype": "container", "comp": "list", "maxresults": "1"},
508
+ success_codes=success_codes,
509
+ )
510
+ return create_api_request(req, auth=auth)
511
+
512
+ resp = common.execute_request(conf, build_req)
513
+ # technically INVALID_HOSTNAME_STATUS means we can't access the account because it
514
+ # doesn't exist, but to be consistent with how we treat this error elsewhere we
515
+ # ignore it here
516
+ if resp.status == INVALID_HOSTNAME_STATUS:
517
+ return True
518
+ # anonymous requests will for some reason get a 404 when they should get a 403
519
+ # so treat a 404 from anon requests as a 403
520
+ if resp.status == 404 and auth[0] == ANONYMOUS:
521
+ out_failures.append(
522
+ RequestFailure.create_from_request_response(
523
+ "Could not access container", build_req(), resp
524
+ )
525
+ )
526
+ return False
527
+ # if the container list succeeds or the container doesn't exist, return success
528
+ if resp.status in (200, 404):
529
+ return True
530
+ else:
531
+ out_failures.append(
532
+ RequestFailure.create_from_request_response(
533
+ "Could not access container", build_req(), resp
534
+ )
535
+ )
536
+ return False
537
+
538
+
539
+ def _get_storage_account_id(
540
+ conf: Config, subscription_id: str, account: str, auth: Tuple[str, str]
541
+ ) -> Optional[str]:
542
+ # get a list of storage accounts
543
+ url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Storage/storageAccounts"
544
+ params = {"api-version": "2019-04-01"}
545
+ while True:
546
+
547
+ def build_req() -> Request:
548
+ req = Request(method="GET", url=url, params=params, success_codes=(200, 401, 403))
549
+ return create_api_request(req, auth=auth)
550
+
551
+ resp = common.execute_request(conf, build_req)
552
+ if resp.status in (401, 403):
553
+ # we aren't allowed to query this for this subscription, skip it
554
+ return None
555
+
556
+ out = json.loads(resp.data)
557
+ # check if we found the storage account we are looking for
558
+ for obj in out["value"]:
559
+ if obj["name"] == account:
560
+ return obj["id"]
561
+
562
+ if "nextLink" not in out:
563
+ return None
564
+
565
+ url = out["nextLink"]
566
+ params = None # the url will already have params on it
567
+
568
+
569
+ def _get_subscription_ids(conf: Config, auth: Tuple[str, str]) -> List[str]:
570
+ url = "https://management.azure.com/subscriptions"
571
+ params = {"api-version": "2020-01-01"}
572
+ result = []
573
+ while True:
574
+
575
+ def build_req() -> Request:
576
+ req = Request(method="GET", url=url, params=params)
577
+ return create_api_request(req, auth=auth)
578
+
579
+ resp = common.execute_request(conf, build_req)
580
+ data = json.loads(resp.data)
581
+ result.extend([item["subscriptionId"] for item in data["value"]])
582
+ if "nextLink" not in data:
583
+ return result
584
+ url = data["nextLink"]
585
+ params = None # the url will already have params on it
586
+
587
+
588
+ def _get_storage_account_key(
589
+ conf: Config,
590
+ account: str,
591
+ container: str,
592
+ creds: Mapping[str, Any],
593
+ out_failures: List[RequestFailure],
594
+ ) -> Optional[Tuple[Any, float]]:
595
+ # azure resource manager has very low limits on number of requests, so we have
596
+ # to be careful to avoid extra requests here
597
+ # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#storage-resource-provider-limits
598
+
599
+ # in general, this code path should be avoided by using a service principal and
600
+ # giving it access to the bucket
601
+
602
+ # get an access token for the management service
603
+ def build_req_access_token() -> Request:
604
+ return _create_access_token_request(
605
+ creds=creds, scope="https://management.azure.com/.default"
606
+ )
607
+
608
+ resp = common.execute_request(conf, build_req_access_token)
609
+ result = json.loads(resp.data)
610
+ auth = (OAUTH_TOKEN, result["access_token"])
611
+
612
+ # attempt to use list of subscriptions from the azure cli tool
613
+ stored_subscription_ids = load_subscription_ids()
614
+
615
+ storage_account_id = None
616
+ for subscription_id in stored_subscription_ids:
617
+ storage_account_id = _get_storage_account_id(conf, subscription_id, account, auth)
618
+ if storage_account_id is not None:
619
+ break
620
+ else:
621
+ # if we didn't find the storage account we are looking for, check to see if there
622
+ # are any subscriptions that we did not query
623
+ subscription_ids = _get_subscription_ids(conf, auth)
624
+ unchecked_subscription_ids = [
625
+ id for id in subscription_ids if id not in stored_subscription_ids
626
+ ]
627
+
628
+ for subscription_id in unchecked_subscription_ids:
629
+ storage_account_id = _get_storage_account_id(conf, subscription_id, account, auth)
630
+ if storage_account_id is not None:
631
+ break
632
+ else:
633
+ # we failed to find the storage account, give up
634
+ return None
635
+
636
+ def build_req_list_keys() -> Request:
637
+ req = Request(
638
+ method="POST",
639
+ url=f"https://management.azure.com{storage_account_id}/listKeys",
640
+ params={"api-version": "2019-04-01"},
641
+ )
642
+ return create_api_request(req, auth=auth)
643
+
644
+ resp = common.execute_request(conf, build_req_list_keys)
645
+ result = json.loads(resp.data)
646
+ for key in result["keys"]:
647
+ if key["permissions"] == "FULL":
648
+ storage_key_auth = (SHARED_KEY, key["value"])
649
+ if _can_access_container(
650
+ conf, account, container, storage_key_auth, out_failures=out_failures
651
+ ):
652
+ return storage_key_auth
653
+ else:
654
+ raise Error(
655
+ f"Found storage account key, but it was unable to access storage account: '{account}' and container: '{container}'"
656
+ )
657
+ raise Error(f"Storage account was found, but storage account keys were missing: '{account}'")
658
+
659
+
660
+ def _get_access_token(conf: Config, key: Any) -> Tuple[Any, float]:
661
+ account, container = key
662
+ now = time.time()
663
+ creds = _load_credentials()
664
+ azure_auth = creds.get("_azure_auth")
665
+ access_failures: List[RequestFailure] = []
666
+ if azure_auth == "sakey":
667
+ if "account" in creds:
668
+ if creds["account"] != account:
669
+ raise Error(
670
+ f"Provided storage account key for account '{creds['account']}' via environment variables, "
671
+ f"but needed credentials for account '{account}'"
672
+ )
673
+ auth = (SHARED_KEY, creds["storage_account_key"])
674
+ if _can_access_container(conf, account, container, auth, out_failures=access_failures):
675
+ return (auth, now + SHARED_KEY_EXPIRATION_SECONDS)
676
+ elif azure_auth == "refresh":
677
+ # we have a refresh token, convert it into an access token for this account
678
+ def build_req() -> Request:
679
+ return _create_access_token_request(
680
+ creds=creds,
681
+ scope=f"https://{account}.blob.core.windows.net/.default",
682
+ success_codes=(200, 400),
683
+ )
684
+
685
+ resp = common.execute_request(conf, build_req)
686
+ result = json.loads(resp.data)
687
+ if resp.status == 400:
688
+ if (
689
+ (
690
+ result["error"] == "invalid_grant"
691
+ and "AADSTS700082" in result["error_description"]
692
+ )
693
+ or (
694
+ result["error"] == "interaction_required"
695
+ and "AADSTS50078" in result["error_description"]
696
+ )
697
+ or (
698
+ result["error"] == "interaction_required"
699
+ and "AADSTS50076" in result["error_description"]
700
+ )
701
+ ):
702
+ raise Error(
703
+ "Your refresh token is no longer valid, please run `az login` to get a new one"
704
+ )
705
+ else:
706
+ raise Error(
707
+ 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`."
708
+ )
709
+
710
+ auth = (OAUTH_TOKEN, result["access_token"])
711
+
712
+ # for some azure accounts this access token does not work, check if it works
713
+ if _can_access_container(conf, account, container, auth, out_failures=access_failures):
714
+ return (auth, now + float(result["expires_in"]))
715
+
716
+ if conf.use_azure_storage_account_key_fallback:
717
+ # fall back to getting the storage keys
718
+ storage_account_key_auth = _get_storage_account_key(
719
+ conf=conf,
720
+ account=account,
721
+ container=container,
722
+ creds=creds,
723
+ out_failures=access_failures,
724
+ )
725
+ if storage_account_key_auth is not None:
726
+ return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS)
727
+ elif azure_auth == "svcact":
728
+ # we have a service principal, get an oauth token
729
+ def build_req() -> Request:
730
+ return _create_access_token_request(
731
+ creds=creds, scope="https://storage.azure.com/.default"
732
+ )
733
+
734
+ resp = common.execute_request(conf, build_req)
735
+ result = json.loads(resp.data)
736
+ auth = (OAUTH_TOKEN, result["access_token"])
737
+ if _can_access_container(conf, account, container, auth, out_failures=access_failures):
738
+ return (auth, now + float(result["expires_in"]))
739
+
740
+ if conf.use_azure_storage_account_key_fallback:
741
+ # fall back to getting the storage keys
742
+ storage_account_key_auth = _get_storage_account_key(
743
+ conf=conf,
744
+ account=account,
745
+ container=container,
746
+ creds=creds,
747
+ out_failures=access_failures,
748
+ )
749
+ if storage_account_key_auth is not None:
750
+ return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS)
751
+
752
+ # If opted into using azure-identity, use DefaultAzureCredential to get a token
753
+ # This enables the use of Managed Identity, Workload Identity, and other auth methods not implemented here
754
+ elif azure_auth == "azure-identity":
755
+ try:
756
+ from azure.identity import DefaultAzureCredential # pyright: ignore
757
+ except ImportError:
758
+ raise RuntimeError(
759
+ "When setting AZURE_USE_IDENTITY=1, you must also install the azure-identity package"
760
+ )
761
+
762
+ with DefaultAzureCredential() as cred:
763
+ token = cred.get_token("https://storage.azure.com/.default")
764
+ auth = (OAUTH_TOKEN, token.token)
765
+ if _can_access_container(conf, account, container, auth, out_failures=access_failures):
766
+ return (auth, token.expires_on)
767
+
768
+ if conf.use_azure_storage_account_key_fallback:
769
+ # fall back to getting the storage keys
770
+ storage_account_key_auth = _get_storage_account_key(
771
+ conf=conf,
772
+ account=account,
773
+ container=container,
774
+ creds=creds,
775
+ out_failures=access_failures,
776
+ )
777
+ if storage_account_key_auth is not None:
778
+ return (storage_account_key_auth, now + SHARED_KEY_EXPIRATION_SECONDS)
779
+
780
+ # oddly, it seems that if you request a public container with a valid azure account, you cannot list the bucket
781
+ # but if you list it with no account, that works fine
782
+ anonymous_auth = (ANONYMOUS, "")
783
+ if _can_access_container(
784
+ conf, account, container, anonymous_auth, out_failures=access_failures
785
+ ):
786
+ return (anonymous_auth, float("inf"))
787
+
788
+ msg = f"Could not find any credentials that grant access to storage account: '{account}' and container: '{container}'"
789
+ if len(access_failures) > 0:
790
+ for resp_failure in access_failures:
791
+ msg += f"\n Access Failure: {resp_failure}"
792
+ if len(creds) == 0:
793
+ msg += """
794
+
795
+ No Azure credentials were found. If the container is not marked as public, please do one of the following:
796
+
797
+ * Log in with 'az login', blobfile will use your default credentials to lookup your storage account key
798
+ * 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
799
+ * Create an account with 'az ad sp create-for-rbac --name <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"""
800
+ raise Error(msg)
801
+
802
+
803
+ def _get_sas_token(conf: Config, key: Any) -> Tuple[Any, float]:
804
+ auth = access_token_manager.get_token(conf, key=key)
805
+ if auth[0] == ANONYMOUS:
806
+ # for public containers, use None as the token so that this will be cached
807
+ # and we can tell when we don't have a real SAS token for a container
808
+ return (None, time.time() + SAS_TOKEN_EXPIRATION_SECONDS)
809
+
810
+ account, container = key
811
+
812
+ def build_req() -> Request:
813
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas
814
+ now = datetime.datetime.now(tz=datetime.timezone.utc)
815
+ start = (now + datetime.timedelta(hours=-1)).strftime("%Y-%m-%dT%H:%M:%SZ")
816
+ expiry = (now + datetime.timedelta(days=6)).strftime("%Y-%m-%dT%H:%M:%SZ")
817
+ req = Request(
818
+ url=f"https://{account}.blob.core.windows.net/",
819
+ method="POST",
820
+ params=dict(restype="service", comp="userdelegationkey"),
821
+ data={"KeyInfo": {"Start": start, "Expiry": expiry}},
822
+ success_codes=(200, 403),
823
+ )
824
+ auth = access_token_manager.get_token(conf, key=key)
825
+ if auth[0] != OAUTH_TOKEN:
826
+ raise Error(
827
+ "Only OAuth tokens can be used to get SAS tokens. You should set the Storage "
828
+ "Blob Data Reader or Storage Blob Data Contributor IAM role. You can run "
829
+ f"`az storage blob list --auth-mode login --account-name {account} --container {container}` "
830
+ "to confirm that the missing role is the issue."
831
+ )
832
+ return create_api_request(req, auth=auth)
833
+
834
+ resp = common.execute_request(conf, build_req)
835
+ if resp.status == 403:
836
+ raise Error(
837
+ f"You do not have permission to generate an SAS token for account {account}. "
838
+ "Try setting the Storage Blob Delegator or Storage Blob Data Contributor IAM role "
839
+ "at the account level."
840
+ )
841
+ out = xml.parse(resp.data)
842
+ t = time.time() + SAS_TOKEN_EXPIRATION_SECONDS
843
+ return out["UserDelegationKey"], t
844
+
845
+
846
+ def execute_api_request(conf: Config, req: Request) -> "urllib3.BaseHTTPResponse":
847
+ u = urllib.parse.urlparse(req.url)
848
+ account = u.netloc.split(".")[0]
849
+ path_parts = u.path.split("/")
850
+ if len(path_parts) < 2:
851
+ raise Error("missing container from path")
852
+ container = u.path.split("/")[1]
853
+
854
+ def build_req() -> Request:
855
+ return create_api_request(
856
+ req, auth=access_token_manager.get_token(conf, key=(account, container))
857
+ )
858
+
859
+ return common.execute_request(conf, build_req)
860
+
861
+
862
+ def _block_index_to_block_id(index: int, upload_id: int) -> str:
863
+ assert index < 2**17
864
+ id_plus_index = (upload_id << 17) + index
865
+ assert id_plus_index < 2**64
866
+ return base64.b64encode(id_plus_index.to_bytes(8, byteorder="big")).decode("utf8")
867
+
868
+
869
+ def _clear_uncommitted_blocks(
870
+ conf: Config, url: str, metadata: Mapping[str, str]
871
+ ) -> Optional["urllib3.BaseHTTPResponse"]:
872
+ # to avoid leaking uncommitted blocks, we can do a Put Block List with
873
+ # all the existing blocks for a file
874
+ # this will change the last-modified timestamp and the etag
875
+ req = Request(url=url, params=dict(comp="blocklist"), method="GET", success_codes=(200, 404))
876
+ resp = execute_api_request(conf, req)
877
+ if resp.status != 200:
878
+ return
879
+
880
+ result = xml.parse(resp.data, repeated_tags={"Block"})
881
+ if result["BlockList"]["CommittedBlocks"] is None:
882
+ return
883
+
884
+ blocks = result["BlockList"]["CommittedBlocks"]["Block"]
885
+ body = {"BlockList": {"Latest": [b["Name"] for b in blocks]}}
886
+ # make sure to preserve metadata for the file
887
+ headers: Dict[str, str] = {k: v for k, v in metadata.items() if k.startswith("x-ms-meta-")}
888
+ for src, dst in RESPONSE_HEADER_TO_REQUEST_HEADER.items():
889
+ if src in metadata:
890
+ headers[dst] = metadata[src]
891
+ req = Request(
892
+ url=url,
893
+ method="PUT",
894
+ params=dict(comp="blocklist"),
895
+ headers={**headers, "If-Match": metadata["etag"]},
896
+ data=body,
897
+ success_codes=(201, 404, 412),
898
+ )
899
+
900
+ return execute_api_request(conf, req)
901
+
902
+
903
+ def _finalize_blob(
904
+ conf: Config,
905
+ path: str,
906
+ url: str,
907
+ block_ids: List[str],
908
+ md5_digest: Optional[bytes],
909
+ version: Optional[str],
910
+ ) -> "urllib3.BaseHTTPResponse":
911
+ body = {"BlockList": {"Latest": block_ids}}
912
+ headers = {}
913
+ if md5_digest is not None:
914
+ # azure does not calculate md5s for us, we have to do that manually
915
+ # https://web.archive.org/web/20190118183153/https://blogs.msdn.microsoft.com/windowsazurestorage/2011/02/17/windows-azure-blob-md5-overview/
916
+ headers["x-ms-blob-content-md5"] = base64.b64encode(md5_digest).decode("utf8")
917
+
918
+ if version is not None:
919
+ headers["If-Match"] = version
920
+ req = Request(
921
+ url=url,
922
+ method="PUT",
923
+ headers=headers,
924
+ params=dict(comp="blocklist"),
925
+ data=body,
926
+ success_codes=(201, 400, 404, 412, INVALID_HOSTNAME_STATUS),
927
+ )
928
+ resp = execute_api_request(conf, req)
929
+ if resp.status == 400:
930
+ result = xml.parse(resp.data)
931
+ if result["Error"]["Code"] == "InvalidBlockList":
932
+ # the most likely way this could happen is if the file was deleted while
933
+ # we were uploading, so assume that is what happened
934
+ # this could be interpreted as a sort of RestartableStreamingWriteFailure but
935
+ # that could result in two processes fighting while uploading the file
936
+ raise ConcurrentWriteFailure.create_from_request_response(
937
+ f"Invalid block list, most likely a concurrent writer wrote to the same path: `{path}`",
938
+ request=req,
939
+ response=resp,
940
+ )
941
+ else:
942
+ raise RequestFailure.create_from_request_response(
943
+ message=f"unexpected status {resp.status}", request=req, response=resp
944
+ )
945
+ elif resp.status == 404 or resp.status == INVALID_HOSTNAME_STATUS:
946
+ # this can occur when using parallel upload
947
+ raise FileNotFoundError(f"No such file or directory: '{path}'")
948
+ elif resp.status == 412:
949
+ if resp.headers["x-ms-error-code"] != "ConditionNotMet":
950
+ raise RequestFailure.create_from_request_response(
951
+ message=f"unexpected status {resp.status}", request=req, response=resp
952
+ )
953
+ else:
954
+ raise VersionMismatch.create_from_request_response(
955
+ message="etag mismatch", request=req, response=resp
956
+ )
957
+ return resp
958
+
959
+
960
+ def isdir(conf: Config, path: str) -> bool:
961
+ """
962
+ Return true if a path is an existing directory
963
+ """
964
+ if not path.endswith("/"):
965
+ path += "/"
966
+ account, container, blob = split_path(path)
967
+ if blob == "":
968
+ req = Request(
969
+ url=build_url(account, "/{container}", container=container, blob=blob),
970
+ method="GET",
971
+ params=dict(restype="container"),
972
+ success_codes=(200, 404, INVALID_HOSTNAME_STATUS),
973
+ )
974
+ resp = execute_api_request(conf, req)
975
+ return resp.status == 200
976
+ else:
977
+ # even though we're only interested in having one result, we still need to make an
978
+ # iterator. as it happens, azure is perfectly willing to return an empty first page.
979
+ it = create_page_iterator(
980
+ conf,
981
+ url=build_url(account, "/{container}", container=container),
982
+ method="GET",
983
+ params=dict(
984
+ comp="list", restype="container", prefix=blob, delimiter="/", maxresults="1"
985
+ ),
986
+ )
987
+ for result in it:
988
+ if result["Blobs"] is not None:
989
+ return "BlobPrefix" in result["Blobs"] or "Blob" in result["Blobs"]
990
+ return False
991
+
992
+
993
+ def create_page_iterator(
994
+ conf: Config,
995
+ url: str,
996
+ method: str,
997
+ data: Optional[Mapping[str, str]] = None,
998
+ params: Optional[Mapping[str, str]] = None,
999
+ ) -> Iterator[Dict[str, Any]]:
1000
+ if params is None:
1001
+ p = {}
1002
+ else:
1003
+ p = dict(params).copy()
1004
+ if data is None:
1005
+ d = None
1006
+ else:
1007
+ d = dict(data).copy()
1008
+ while True:
1009
+ req = Request(
1010
+ url=url,
1011
+ method=method,
1012
+ params=p,
1013
+ data=d,
1014
+ success_codes=(200, 404, INVALID_HOSTNAME_STATUS),
1015
+ )
1016
+ resp = execute_api_request(conf, req)
1017
+ if resp.status in (404, INVALID_HOSTNAME_STATUS):
1018
+ return
1019
+ result = xml.parse(resp.data, repeated_tags={"BlobPrefix", "Blob"})["EnumerationResults"]
1020
+ yield result
1021
+ if result["NextMarker"] is None:
1022
+ break
1023
+ p["marker"] = result["NextMarker"]
1024
+
1025
+
1026
+ class StreamingReadFile(BaseStreamingReadFile):
1027
+ def __init__(
1028
+ self, conf: Config, path: str, size: Optional[int], version: Optional[str]
1029
+ ) -> None:
1030
+ self._version: Optional[str] = version
1031
+ if size is None:
1032
+ st = maybe_stat(conf, path, version=version)
1033
+ if st is None:
1034
+ raise FileNotFoundError(f"No such file or directory: '{path}'")
1035
+ size = st.size
1036
+ self._version = st.version
1037
+ super().__init__(conf=conf, path=path, size=size)
1038
+
1039
+ def _request_chunk(
1040
+ self, streaming: bool, start: int, end: Optional[int] = None
1041
+ ) -> "urllib3.BaseHTTPResponse":
1042
+ account, container, blob = split_path(self._path)
1043
+ headers = {"Range": common.calc_range(start=start, end=end)}
1044
+ if self._version is not None:
1045
+ headers["If-Match"] = self._version
1046
+ req = Request(
1047
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1048
+ method="GET",
1049
+ headers=headers,
1050
+ success_codes=(206, 416),
1051
+ # if we are streaming the data, make
1052
+ # sure we don't preload it
1053
+ preload_content=not streaming,
1054
+ )
1055
+ resp = execute_api_request(self._conf, req)
1056
+ self._version = self._version or resp.headers.get("ETag")
1057
+ return resp
1058
+
1059
+
1060
+ class StreamingWriteFile(BaseStreamingWriteFile):
1061
+ def __init__(self, conf: Config, path: str, version: Optional[str]) -> None:
1062
+ self._path = path
1063
+ account, container, blob = split_path(path)
1064
+ self._url = build_url(account, "/{container}/{blob}", container=container, blob=blob)
1065
+ # block blobs let you upload up to 100,000 "uncommitted" blocks with user-chosen block ids
1066
+ # using the "Put Block" call
1067
+ # you may then call "Put Block List" with up to 50,000 block ids of the blocks you
1068
+ # want to be in the blob (50,000 is the max blocks per blob)
1069
+ # all unused uncommitted blocks will be deleted
1070
+ # uncommitted blocks also expire after a week if they are not committed
1071
+ #
1072
+ # since we use block blobs, there are a few ways we could implement this streaming write file
1073
+ #
1074
+ # method 1:
1075
+ # upload the first chunk of the file as block id "0", the second as block id "1" etc
1076
+ # when we are done writing the file, we call "Put Block List" using range(num_blocks) as
1077
+ # the block ids
1078
+ #
1079
+ # this has the advantage that if our program crashes, the same block ids will be reused
1080
+ # for the next upload and so we'll never get more than 50,000 uncommitted blocks
1081
+ #
1082
+ # in general, azure does not seem to support concurrent writers except maybe
1083
+ # for writing small files (GCS does to a limited extent through resumable upload sessions)
1084
+ #
1085
+ # with method 1, if you have two writers:
1086
+ #
1087
+ # writer 0: write block id "0"
1088
+ # writer 1: write block id "0"
1089
+ # writer 1: crash
1090
+ # writer 0: write block id "1"
1091
+ # writer 0: put block list ["0", "1"]
1092
+ #
1093
+ # then you will end up with block "0" from writer 1 and block "1" from writer 0, which means
1094
+ # your file will be corrupted
1095
+ #
1096
+ # this appears to be the method used by the azure python SDK
1097
+ #
1098
+ # method 2:
1099
+ # generate a random session id
1100
+ # upload the first chunk of the file as block id "<session id>-0",
1101
+ # the second block as "<session id>-1" etc
1102
+ # when we are done writing the file, call "Put Block List" using
1103
+ # [f"<session id>-{i}" for i in range(num_blocks)] as the block list
1104
+ #
1105
+ # this has the advantage that we should not observe data corruption from concurrent writers
1106
+ # assuming that the session ids are unique, although whichever writer finishes first will
1107
+ # win, because calling "Put Block List" will delete all uncommitted blocks
1108
+ #
1109
+ # this has the disadvantage that we can end up hitting the uncommitted block limit
1110
+ # 1) with 100,000 concurrent writers, each one would write the first block, then all
1111
+ # would immediately hit the block limit and get 409 errors
1112
+ # 2) with a single writer that crashes every time it writes the second block, it would
1113
+ # retry 100,000 times, then be unable to continue due to all the uncommitted blocks
1114
+ # it was generating
1115
+ #
1116
+ # the workaround we use here is that whenever a file is opened for reading, we clear all
1117
+ # uncommitted blocks by calling "Put Block List" with the list of currently committed blocks
1118
+ #
1119
+ # this seems to be reasonably fast in practice, and means that failure #2 should not be an issue
1120
+ #
1121
+ # failure #1 could still happen with concurrent writers, but this should result only in a
1122
+ # confusing error message (409 error) instead of a ConcurrentWriteFailure, though we
1123
+ # could likely raise that error if we saw a 409 with the error RequestEntityTooLargeBlockCountExceedsLimit
1124
+ #
1125
+ # this does change the behavior slightly, now the writer that will end up succeeding on "Put Block List"
1126
+ # is likely to be the last writer to open the file for writing, the others will fail
1127
+ # because their uncommitted blocks have been cleared
1128
+ #
1129
+ # it would be nice to replace this with a less odd method, but it's not obvious how
1130
+ # to do this on azure storage
1131
+ #
1132
+ # if there were upload sessions like GCS, this wouldn't be an issue
1133
+ # if there was no uncommitted block limit, method 2 would work fine
1134
+ # if blobs could automatically expire without having to add a container lifecycle rule
1135
+ # then we could upload to a temp path, then copy to the final path (assuming copy is atomic)
1136
+ # without automatic expiry, we'd leak temp files
1137
+ # we can use the lease system, but then we have to deal with leases
1138
+
1139
+ self._upload_id = rng.randint(0, 2**47 - 1)
1140
+ self._block_index = 0
1141
+ self._version: Optional[str] = version # for azure, this is an etag
1142
+ # check to see if there is an existing blob at this location with the wrong type
1143
+ req = Request(
1144
+ url=self._url,
1145
+ method="HEAD",
1146
+ headers={"If-Match": self._version} if self._version else {},
1147
+ success_codes=(200, 400, 404, 412, INVALID_HOSTNAME_STATUS),
1148
+ )
1149
+ resp = execute_api_request(conf, req)
1150
+ if resp.status == 200:
1151
+ if resp.headers["x-ms-blob-type"] == "BlockBlob":
1152
+ # because we delete all the uncommitted blocks, any concurrent writers will fail
1153
+ # but they would fail anyway since the first writer to finish would end up
1154
+ # deleting all uncommitted blocks
1155
+ # this means that the last writer to start is likely to win, the others should fail
1156
+ # with ConcurrentWriteFailure
1157
+ resp = _clear_uncommitted_blocks(conf, self._url, resp.headers)
1158
+ if resp:
1159
+ self._version = resp.headers["ETag"] # update the version according to new etag
1160
+ else:
1161
+ # if the existing blob type is not compatible with the block blob we are about to write
1162
+ # we have to delete the file before writing our block blob or else we will get a 409
1163
+ # error when putting the first block
1164
+ remove(conf, path)
1165
+ elif resp.status in (400, INVALID_HOSTNAME_STATUS) or (
1166
+ resp.status == 404 and resp.headers["x-ms-error-code"] == "ContainerNotFound"
1167
+ ):
1168
+ raise FileNotFoundError(f"No such file or container/account does not exist: '{path}'")
1169
+ elif resp.status == 412:
1170
+ if resp.headers["x-ms-error-code"] != "ConditionNotMet":
1171
+ raise RequestFailure.create_from_request_response(
1172
+ message=f"unexpected status {resp.status}", request=req, response=resp
1173
+ )
1174
+ else:
1175
+ raise VersionMismatch.create_from_request_response(
1176
+ message="etag mismatch", request=req, response=resp
1177
+ )
1178
+ self._md5 = hashlib.md5()
1179
+ super().__init__(conf=conf, chunk_size=conf.azure_write_chunk_size)
1180
+
1181
+ def _upload_chunk(self, chunk: memoryview, finalize: bool) -> None:
1182
+ start = 0
1183
+ while start < len(chunk):
1184
+ # premium block blob storage supports block blobs and append blobs
1185
+ # https://azure.microsoft.com/en-us/blog/azure-premium-block-blob-storage-is-now-generally-available/
1186
+ # we use block blobs because they are compatible with WASB:
1187
+ # https://docs.microsoft.com/en-us/azure/databricks/kb/data-sources/wasb-check-blob-types
1188
+ end = start + self._conf.azure_write_chunk_size
1189
+ data = chunk[start:end]
1190
+ self._md5.update(data)
1191
+ block_md5 = hashlib.md5(data)
1192
+ req = Request(
1193
+ url=self._url,
1194
+ method="PUT",
1195
+ headers={"Content-MD5": base64.b64encode(block_md5.digest()).decode("utf8")},
1196
+ params=dict(
1197
+ comp="block",
1198
+ blockid=_block_index_to_block_id(self._block_index, self._upload_id),
1199
+ ),
1200
+ data=data,
1201
+ success_codes=(201,),
1202
+ # retry if we get an MD5 mismatch error (unfortunately we are just guessing that it is a mismatch error
1203
+ # from the 400 status code)
1204
+ retry_codes=(400,) + DEFAULT_RETRY_CODES,
1205
+ )
1206
+ try:
1207
+ execute_api_request(self._conf, req)
1208
+ except Exception:
1209
+ del chunk, data, req.data, req
1210
+ raise
1211
+
1212
+ self._block_index += 1
1213
+ if self._block_index >= BLOCK_COUNT_LIMIT:
1214
+ raise Error(
1215
+ 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."
1216
+ )
1217
+
1218
+ start = end
1219
+
1220
+ if finalize:
1221
+ block_ids = [
1222
+ _block_index_to_block_id(i, self._upload_id) for i in range(self._block_index)
1223
+ ]
1224
+ resp = _finalize_blob(
1225
+ conf=self._conf,
1226
+ path=self._path,
1227
+ url=self._url,
1228
+ block_ids=block_ids,
1229
+ md5_digest=self._md5.digest(),
1230
+ version=self._version,
1231
+ )
1232
+ # Update the version according to new etag. The file will be closed
1233
+ # after this, but the version can still be retrieved.
1234
+ self._version = resp.headers.get("ETag") or self._version
1235
+
1236
+
1237
+ def _upload_chunk(conf: Config, path: str, start: int, size: int, url: str, block_id: str) -> None:
1238
+ req = Request(
1239
+ url=url,
1240
+ method="PUT",
1241
+ params=dict(comp="block", blockid=block_id),
1242
+ # this needs to be specified since we use a file object for the data
1243
+ headers={"Content-Length": str(size)},
1244
+ data=FileBody(path, start=start, end=start + size),
1245
+ success_codes=(201, 404, INVALID_HOSTNAME_STATUS),
1246
+ )
1247
+ resp = execute_api_request(conf, req)
1248
+ if resp.status == 404 or resp.status == INVALID_HOSTNAME_STATUS:
1249
+ # this can happen during parallel upload
1250
+ raise FileNotFoundError(f"No such file or directory: '{url}'")
1251
+
1252
+
1253
+ def parallel_upload(
1254
+ conf: Config,
1255
+ executor: concurrent.futures.Executor,
1256
+ src: str,
1257
+ dst: str,
1258
+ return_md5: bool,
1259
+ dst_version: Optional[str],
1260
+ ) -> Optional[str]:
1261
+ with open(src, "rb") as f:
1262
+ md5_digest = common.block_md5(f)
1263
+
1264
+ account, container, blob = split_path(dst)
1265
+ dst_url = build_url(account, "/{container}/{blob}", container=container, blob=blob)
1266
+
1267
+ upload_id = rng.randint(0, 2**47 - 1)
1268
+ s = os.stat(src)
1269
+ block_ids = []
1270
+ max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1)
1271
+ part_size = min(
1272
+ max(math.ceil(s.st_size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE),
1273
+ MAX_BLOCK_SIZE,
1274
+ )
1275
+ i = 0
1276
+ start = 0
1277
+ futures = []
1278
+ while start < s.st_size:
1279
+ block_id = _block_index_to_block_id(i, upload_id)
1280
+ future = executor.submit(
1281
+ _upload_chunk, conf, src, start, min(part_size, s.st_size - start), dst_url, block_id
1282
+ )
1283
+ futures.append(future)
1284
+ block_ids.append(block_id)
1285
+ i += 1
1286
+ start += part_size
1287
+ for future in futures:
1288
+ future.result()
1289
+
1290
+ _finalize_blob(
1291
+ conf=conf,
1292
+ path=dst,
1293
+ url=dst_url,
1294
+ block_ids=block_ids,
1295
+ md5_digest=md5_digest,
1296
+ version=dst_version,
1297
+ )
1298
+ return binascii.hexlify(md5_digest).decode("utf8") if return_md5 else None
1299
+
1300
+
1301
+ def maybe_stat(conf: Config, path: str, *, version: Optional[str] = None) -> Optional[Stat]:
1302
+ account, container, blob = split_path(path)
1303
+ if blob == "":
1304
+ return None
1305
+ req = Request(
1306
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1307
+ method="HEAD",
1308
+ success_codes=(200, 404, INVALID_HOSTNAME_STATUS),
1309
+ )
1310
+ resp = execute_api_request(conf, req)
1311
+ if resp.status != 200:
1312
+ return None
1313
+ stat = make_stat(resp.headers)
1314
+ if version is not None and stat.version != version:
1315
+ raise VersionMismatch.create_from_request_response(
1316
+ message="etag mismatch", request=req, response=resp
1317
+ )
1318
+ return stat
1319
+
1320
+
1321
+ def remove(conf: Config, path: str) -> bool:
1322
+ account, container, blob = split_path(path)
1323
+ if blob == "":
1324
+ raise FileNotFoundError(f"The system cannot find the path specified: '{path}'")
1325
+ req = Request(
1326
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1327
+ method="DELETE",
1328
+ success_codes=(202, 404, INVALID_HOSTNAME_STATUS),
1329
+ )
1330
+ resp = execute_api_request(conf, req)
1331
+ return resp.status == 202
1332
+
1333
+
1334
+ def maybe_update_md5(conf: Config, path: str, etag: str, hexdigest: str) -> bool:
1335
+ account, container, blob = split_path(path)
1336
+ req = Request(
1337
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1338
+ method="HEAD",
1339
+ headers={"If-Match": etag},
1340
+ success_codes=(200, 404, 412),
1341
+ )
1342
+ resp = execute_api_request(conf, req)
1343
+ if resp.status in (404, 412):
1344
+ return False
1345
+
1346
+ # these will be cleared if not provided, there does not appear to be a PATCH method like for GCS
1347
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties#remarks
1348
+ headers: Dict[str, str] = {}
1349
+ for src, dst in RESPONSE_HEADER_TO_REQUEST_HEADER.items():
1350
+ if src in resp.headers:
1351
+ headers[dst] = resp.headers[src]
1352
+ headers["x-ms-blob-content-md5"] = base64.b64encode(binascii.unhexlify(hexdigest)).decode(
1353
+ "utf8"
1354
+ )
1355
+
1356
+ req = Request(
1357
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1358
+ method="PUT",
1359
+ params=dict(comp="properties"),
1360
+ headers={
1361
+ **headers,
1362
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations
1363
+ "If-Match": etag,
1364
+ },
1365
+ # for a 403, we actually maybe could have updated the md5, but we don't have permission
1366
+ # for a 404, this could be due to this being some anonymous access container
1367
+ # for both cases this is potentially bad because it means cache_dir won't work, it might be nice to let the user
1368
+ # know if there's a non-spammy way to do it
1369
+ success_codes=(200, 403, 404, 412),
1370
+ )
1371
+ resp = execute_api_request(conf, req)
1372
+ return resp.status == 200
1373
+
1374
+
1375
+ def list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]:
1376
+ params = {}
1377
+ if delimiter is not None:
1378
+ params["delimiter"] = delimiter
1379
+
1380
+ account, container, prefix = split_path(path)
1381
+ it = create_page_iterator(
1382
+ conf,
1383
+ url=build_url(account, "/{container}", container=container),
1384
+ method="GET",
1385
+ params=dict(comp="list", restype="container", prefix=prefix, **params),
1386
+ )
1387
+ for result in it:
1388
+ yield from _get_entries(conf, account, container, result)
1389
+
1390
+
1391
+ def entry_from_dirpath(path: str) -> DirEntry:
1392
+ if path.endswith("/"):
1393
+ path = path[:-1]
1394
+ _, _, obj = split_path(path)
1395
+ name = obj.split("/")[-1]
1396
+ return DirEntry(name=name, path=path, is_dir=True, is_file=False, stat=None)
1397
+
1398
+
1399
+ def entry_from_path_stat(path: str, stat: Stat) -> DirEntry:
1400
+ assert not path.endswith("/")
1401
+ _, _, obj = split_path(path)
1402
+ name = obj.split("/")[-1]
1403
+ return DirEntry(name=name, path=path, is_dir=False, is_file=True, stat=stat)
1404
+
1405
+
1406
+ def _get_entries(
1407
+ conf: Config, account: str, container: str, result: Mapping[str, Any]
1408
+ ) -> Iterator[DirEntry]:
1409
+ blobs = result["Blobs"]
1410
+ if blobs is None:
1411
+ return
1412
+ if "BlobPrefix" in blobs:
1413
+ for bp in blobs["BlobPrefix"]:
1414
+ path = combine_path(conf, account, container, bp["Name"])
1415
+ yield entry_from_dirpath(path)
1416
+ if "Blob" in blobs:
1417
+ for b in blobs["Blob"]:
1418
+ path = combine_path(conf, account, container, b["Name"])
1419
+ if b["Name"].endswith("/"):
1420
+ yield entry_from_dirpath(path)
1421
+ else:
1422
+ props = b["Properties"]
1423
+ yield entry_from_path_stat(path, make_stat(props))
1424
+
1425
+
1426
+ def get_url(conf: Config, path: str) -> Tuple[str, Optional[float]]:
1427
+ account, container, blob = split_path(path)
1428
+ url = build_url(account, "/{container}/{blob}", container=container, blob=blob)
1429
+ token = sas_token_manager.get_token(conf=conf, key=(account, container))
1430
+ if token is None:
1431
+ # the container has public access
1432
+ return url, float("inf")
1433
+ return generate_signed_url(key=token, url=url)
1434
+
1435
+
1436
+ def set_mtime(conf: Config, path: str, mtime: float, version: Optional[str] = None) -> bool:
1437
+ account, container, blob = split_path(path)
1438
+ headers = {}
1439
+ if version is not None:
1440
+ headers["If-Match"] = version
1441
+ req = Request(
1442
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1443
+ method="HEAD",
1444
+ params=dict(comp="metadata"),
1445
+ headers=headers,
1446
+ success_codes=(200, 404, 412),
1447
+ )
1448
+ resp = execute_api_request(conf, req)
1449
+ if resp.status == 404:
1450
+ raise FileNotFoundError(f"No such file: '{path}'")
1451
+ if resp.status == 412:
1452
+ return False
1453
+
1454
+ headers = {k: v for k, v in resp.headers.items() if k.startswith("x-ms-meta-")}
1455
+ headers["x-ms-meta-blobfilemtime"] = str(mtime)
1456
+ if version is not None:
1457
+ headers["If-Match"] = version
1458
+ req = Request(
1459
+ url=build_url(account, "/{container}/{blob}", container=container, blob=blob),
1460
+ method="PUT",
1461
+ params=dict(comp="metadata"),
1462
+ headers=headers,
1463
+ success_codes=(200, 404, 412),
1464
+ )
1465
+ resp = execute_api_request(conf, req)
1466
+ if resp.status == 404:
1467
+ raise FileNotFoundError(f"No such file: '{path}'")
1468
+ return resp.status == 200
1469
+
1470
+
1471
+ def dirname(conf: Config, path: str) -> str:
1472
+ account, container, obj = split_path(path)
1473
+ obj = strip_slashes(obj)
1474
+ if "/" in obj:
1475
+ obj = "/".join(obj.split("/")[:-1])
1476
+ return combine_path(conf, account, container, obj)
1477
+ else:
1478
+ return combine_path(conf, account, container, "")[:-1]
1479
+
1480
+
1481
+ def remote_copy(conf: Config, src: str, dst: str, return_md5: bool) -> Optional[str]:
1482
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob
1483
+ dst_account, dst_container, dst_blob = split_path(dst)
1484
+ src_account, src_container, src_blob = split_path(src)
1485
+
1486
+ def build_req() -> Request:
1487
+ src_url = build_url(
1488
+ src_account, "/{container}/{blob}", container=src_container, blob=src_blob
1489
+ )
1490
+ if src_account != dst_account:
1491
+ # the signed url can expire, so technically we should get the sas_token and build the signed url
1492
+ # each time we build a new request
1493
+ sas_token = sas_token_manager.get_token(conf=conf, key=(src_account, src_container))
1494
+ # if we don't get a token, it's likely we have anonymous access to the container
1495
+ # if we do get a token, the container is likely private and we need to use
1496
+ # a signed url as the source
1497
+ if sas_token is not None:
1498
+ src_url, _ = generate_signed_url(key=sas_token, url=src_url)
1499
+ req = Request(
1500
+ url=build_url(
1501
+ dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob
1502
+ ),
1503
+ method="PUT",
1504
+ headers={"x-ms-copy-source": src_url},
1505
+ success_codes=(202, 404, 409, INVALID_HOSTNAME_STATUS),
1506
+ )
1507
+ return create_api_request(
1508
+ req, auth=access_token_manager.get_token(conf=conf, key=(dst_account, dst_container))
1509
+ )
1510
+
1511
+ copy_id = None
1512
+ copy_status = None
1513
+ etag = None
1514
+
1515
+ # start the copy, waiting for any existing copies to finish
1516
+ backoff_generator = common.exponential_sleep_generator()
1517
+ for backoff in backoff_generator:
1518
+ resp = common.execute_request(conf, build_req)
1519
+ if resp.status == 202:
1520
+ copy_id = resp.headers["x-ms-copy-id"]
1521
+ copy_status = resp.headers["x-ms-copy-status"]
1522
+ etag = resp.headers["etag"]
1523
+ break
1524
+ elif resp.status == INVALID_HOSTNAME_STATUS:
1525
+ raise FileNotFoundError(
1526
+ f"Source container or destination container not found: src='{src}' dst='{dst}'"
1527
+ )
1528
+ elif resp.status == 404:
1529
+ if resp.headers["x-ms-error-code"] == "ContainerNotFound":
1530
+ raise FileNotFoundError(
1531
+ f"Source container or destination container not found: src='{src}' dst='{dst}'"
1532
+ )
1533
+
1534
+ raise FileNotFoundError(f"Source file not found: '{src}'")
1535
+ elif resp.status == 409:
1536
+ result = xml.parse(resp.data)
1537
+ if result["Error"]["Code"] != "PendingCopyOperation":
1538
+ raise RequestFailure.create_from_request_response(
1539
+ message=f"unexpected status {resp.status}", request=build_req(), response=resp
1540
+ )
1541
+ # if we got a pending copy operation, continue to wait
1542
+ else:
1543
+ raise Error(f"unhandled status {resp.status}")
1544
+ time.sleep(backoff)
1545
+
1546
+ # wait for potentially async copy operation to finish
1547
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob
1548
+ # pending, success, aborted, failed
1549
+ backoff_generator = common.exponential_sleep_generator()
1550
+ while copy_status == "pending":
1551
+ time.sleep(next(backoff_generator))
1552
+ req = Request(
1553
+ url=build_url(
1554
+ dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob
1555
+ ),
1556
+ method="GET",
1557
+ )
1558
+ resp = execute_api_request(conf, req)
1559
+ if resp.headers["x-ms-copy-id"] != copy_id:
1560
+ raise Error("Copy id mismatch")
1561
+ etag = resp.headers["etag"]
1562
+ copy_status = resp.headers["x-ms-copy-status"]
1563
+ if copy_status != "success":
1564
+ raise Error(f"Invalid copy status: '{copy_status}'")
1565
+ if return_md5:
1566
+ # if the file is the same one that we just copied, return the stored MD5
1567
+ st = maybe_stat(conf, dst)
1568
+ if st is not None and st.version == etag:
1569
+ return st.md5
1570
+ return
1571
+
1572
+
1573
+ def join_paths(conf: Config, a: str, b: str) -> str:
1574
+ if not a.endswith("/"):
1575
+ a += "/"
1576
+
1577
+ account, container, obj = split_path(a)
1578
+ obj = path_join(obj, b)
1579
+ if obj.startswith("/"):
1580
+ obj = obj[1:]
1581
+ return combine_path(conf, account, container, obj)
1582
+
1583
+
1584
+ def _put_block_from_url(
1585
+ conf: Config, src: str, start: int, size: int, dst: str, block_id: str
1586
+ ) -> None:
1587
+ src_account, src_container, src_blob = split_path(src)
1588
+ dst_account, dst_container, dst_blob = split_path(dst)
1589
+
1590
+ src_url = build_url(src_account, "/{container}/{blob}", container=src_container, blob=src_blob)
1591
+
1592
+ dst_url = build_url(dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob)
1593
+
1594
+ def build_req() -> Request:
1595
+ # the signed url can expire, so technically we should get the sas_token and build the signed url
1596
+ # each time we build a new request
1597
+ sas_token = sas_token_manager.get_token(conf=conf, key=(src_account, src_container))
1598
+ # if we don't get a token, it's likely we have anonymous access to the container
1599
+ # if we do get a token, the container is likely private and we need to use
1600
+ # a signed url as the source
1601
+ if sas_token is None:
1602
+ copy_src_url = src_url
1603
+ else:
1604
+ copy_src_url, _ = generate_signed_url(key=sas_token, url=src_url)
1605
+ req = Request(
1606
+ url=dst_url,
1607
+ method="PUT",
1608
+ params=dict(comp="block", blockid=block_id),
1609
+ headers={
1610
+ "Content-Length": "0",
1611
+ "x-ms-copy-source": copy_src_url,
1612
+ "x-ms-source-range": common.calc_range(start=start, end=start + size),
1613
+ },
1614
+ success_codes=(201, 404, INVALID_HOSTNAME_STATUS),
1615
+ )
1616
+ return create_api_request(
1617
+ req, auth=access_token_manager.get_token(conf=conf, key=(dst_account, dst_container))
1618
+ )
1619
+
1620
+ resp = common.execute_request(conf, build_req)
1621
+ if resp.status == 404:
1622
+ raise FileNotFoundError(
1623
+ f"Source file/container or destination container not found: src='{src}' dst='{dst}'"
1624
+ )
1625
+ elif resp.status == INVALID_HOSTNAME_STATUS:
1626
+ raise FileNotFoundError(
1627
+ f"Source container or destination container not found: src='{src}' dst='{dst}'"
1628
+ )
1629
+
1630
+
1631
+ def parallel_remote_copy(
1632
+ conf: Config,
1633
+ executor: concurrent.futures.Executor,
1634
+ src: str,
1635
+ dst: str,
1636
+ return_md5: bool,
1637
+ dst_version: Optional[str],
1638
+ ) -> Optional[str]:
1639
+ # for whatever reason, put block from url is faster than copy blob when you run multiple requests in parallel
1640
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url
1641
+
1642
+ st = maybe_stat(conf, src)
1643
+ if st is None:
1644
+ raise FileNotFoundError(f"The system cannot find the path specified: '{src}'")
1645
+
1646
+ md5_digest = None
1647
+ if st.md5 is not None:
1648
+ md5_digest = binascii.unhexlify(st.md5)
1649
+ upload_id = rng.randint(0, 2**47 - 1)
1650
+ block_ids = []
1651
+ min_block_size = st.size // BLOCK_COUNT_LIMIT
1652
+ assert min_block_size <= MAX_BLOCK_SIZE
1653
+ part_size = max(conf.azure_write_chunk_size, min_block_size)
1654
+ i = 0
1655
+ start = 0
1656
+ futures = []
1657
+ while start < st.size:
1658
+ block_id = _block_index_to_block_id(i, upload_id)
1659
+ future = executor.submit(
1660
+ _put_block_from_url, conf, src, start, min(part_size, st.size - start), dst, block_id
1661
+ )
1662
+ futures.append(future)
1663
+ block_ids.append(block_id)
1664
+ i += 1
1665
+ start += part_size
1666
+ for future in futures:
1667
+ future.result()
1668
+
1669
+ dst_account, dst_container, dst_blob = split_path(dst)
1670
+ dst_url = build_url(dst_account, "/{container}/{blob}", container=dst_container, blob=dst_blob)
1671
+
1672
+ _finalize_blob(
1673
+ conf=conf,
1674
+ path=dst,
1675
+ url=dst_url,
1676
+ block_ids=block_ids,
1677
+ md5_digest=md5_digest,
1678
+ version=dst_version,
1679
+ )
1680
+ return (
1681
+ binascii.hexlify(md5_digest).decode("utf8")
1682
+ if (return_md5 and md5_digest is not None)
1683
+ else None
1684
+ )
1685
+
1686
+
1687
+ access_token_manager = TokenManager(_get_access_token, "azure_access")
1688
+
1689
+ sas_token_manager = TokenManager(_get_sas_token, "azure_sas")
videollama2/lib/python3.10/site-packages/blobfile/_context.py ADDED
@@ -0,0 +1,1518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime
2
+ from __future__ import annotations
3
+
4
+ import binascii
5
+ import collections
6
+ import concurrent.futures
7
+ import contextlib
8
+ import hashlib
9
+ import io
10
+ import itertools
11
+ import math
12
+ import multiprocessing as mp
13
+ import os
14
+ import re
15
+ import shutil
16
+ import stat as stat_module
17
+ import tempfile
18
+ import time
19
+ import urllib.parse
20
+ from functools import partial
21
+ from types import ModuleType
22
+ from typing import (
23
+ Any,
24
+ BinaryIO,
25
+ Callable,
26
+ Iterator,
27
+ List,
28
+ Literal,
29
+ NamedTuple,
30
+ Optional,
31
+ Sequence,
32
+ TextIO,
33
+ Tuple,
34
+ Union,
35
+ cast,
36
+ overload,
37
+ )
38
+
39
+ import filelock
40
+ import urllib3
41
+
42
+ from blobfile import _azure as azure
43
+ from blobfile import _common as common
44
+ from blobfile import _gcp as gcp
45
+ from blobfile._common import (
46
+ CHUNK_SIZE,
47
+ DEFAULT_CONNECTION_POOL_MAX_SIZE,
48
+ DEFAULT_MAX_CONNECTION_POOL_COUNT,
49
+ Config,
50
+ DirEntry,
51
+ Error,
52
+ RemoteOrLocalPath,
53
+ Request,
54
+ RestartableStreamingWriteFailure,
55
+ Stat,
56
+ get_log_threshold_for_error,
57
+ path_to_str,
58
+ )
59
+
60
+ # https://cloud.google.com/storage/docs/naming
61
+ # https://www.w3.org/TR/xml/#charsets
62
+ INVALID_CHARS = set().union(range(0x0, 0x9)).union(range(0xB, 0xE)).union(range(0xE, 0x20))
63
+
64
+ DEFAULT_AZURE_WRITE_CHUNK_SIZE = 8 * 2**20
65
+ DEFAULT_GOOGLE_WRITE_CHUNK_SIZE = 8 * 2**20
66
+ DEFAULT_RETRY_LOG_THRESHOLD = 0
67
+ DEFAULT_RETRY_COMMON_LOG_THRESHOLD = 2
68
+ DEFAULT_CONNECT_TIMEOUT = 10
69
+ DEFAULT_READ_TIMEOUT = 30
70
+ DEFAULT_BUFFER_SIZE = 8 * 2**20
71
+
72
+
73
+ def _execute_fn_and_ignore_result(fn: Callable[..., object], *args: Any):
74
+ fn(*args)
75
+
76
+
77
+ class Context:
78
+ def __init__(self, conf: Config):
79
+ self._conf = conf
80
+
81
+ def copy(
82
+ self,
83
+ src: RemoteOrLocalPath,
84
+ dst: RemoteOrLocalPath,
85
+ overwrite: bool = False,
86
+ parallel: bool = False,
87
+ parallel_executor: Optional[concurrent.futures.Executor] = None,
88
+ return_md5: bool = False,
89
+ dst_version: Optional[str] = None,
90
+ ) -> Optional[str]:
91
+ src = path_to_str(src)
92
+ dst = path_to_str(dst)
93
+ # it would be best to check isdir() for remote paths, but that would
94
+ # involve 2 extra network requests, so just do this test instead
95
+ if _guess_isdir(src):
96
+ raise IsADirectoryError(f"Is a directory: '{src}'")
97
+ if _guess_isdir(dst):
98
+ raise IsADirectoryError(f"Is a directory: '{dst}'")
99
+
100
+ if not overwrite:
101
+ if self.exists(dst):
102
+ raise FileExistsError(
103
+ f"Destination '{dst}' already exists and overwrite is disabled"
104
+ )
105
+
106
+ if dst_version is not None:
107
+ assert _is_azure_path(
108
+ dst
109
+ ), f"Destination version was specified, but destination path {dst} does not support a version check"
110
+
111
+ if parallel:
112
+ copy_fn = None
113
+ if (_is_azure_path(src) or _is_gcp_path(src)) and _is_local_path(dst):
114
+ copy_fn = _parallel_download
115
+
116
+ if _is_local_path(src) and _is_azure_path(dst):
117
+ copy_fn = partial(azure.parallel_upload, dst_version=dst_version)
118
+
119
+ if _is_local_path(src) and _is_gcp_path(dst):
120
+ copy_fn = gcp.parallel_upload
121
+
122
+ if _is_azure_path(src) and _is_azure_path(dst):
123
+ src_account, _, _ = azure.split_path(src)
124
+ dst_account, _, _ = azure.split_path(dst)
125
+ if src_account != dst_account:
126
+ # normal remote copy is pretty fast and doesn't benefit from parallelization when used within
127
+ # a storage account
128
+ copy_fn = partial(azure.parallel_remote_copy, dst_version=dst_version)
129
+
130
+ if copy_fn is not None:
131
+ if parallel_executor is None:
132
+ with concurrent.futures.ProcessPoolExecutor(
133
+ mp_context=mp.get_context(self._conf.multiprocessing_start_method)
134
+ ) as executor:
135
+ return copy_fn(self._conf, executor, src, dst, return_md5=return_md5)
136
+ else:
137
+ return copy_fn(self._conf, parallel_executor, src, dst, return_md5=return_md5)
138
+
139
+ # special case cloud to cloud copy, don't download the file
140
+ if _is_gcp_path(src) and _is_gcp_path(dst):
141
+ return gcp.remote_copy(self._conf, src=src, dst=dst, return_md5=return_md5)
142
+
143
+ if _is_azure_path(src) and _is_azure_path(dst):
144
+ # support could be added here for this but it's currently missing
145
+ assert (
146
+ dst_version is None
147
+ ), f"Destination version was specified, but destination path {dst} does not support a version check"
148
+ return azure.remote_copy(self._conf, src=src, dst=dst, return_md5=return_md5)
149
+
150
+ for attempt, backoff in enumerate(common.exponential_sleep_generator()):
151
+ try:
152
+ with self.BlobFile(src, "rb", streaming=True) as src_f, self.BlobFile(
153
+ dst, "wb", streaming=True, version=dst_version
154
+ ) as dst_f:
155
+ m = hashlib.md5()
156
+ while True:
157
+ block = src_f.read(CHUNK_SIZE)
158
+ if block == b"":
159
+ break
160
+ if return_md5:
161
+ m.update(block)
162
+ dst_f.write(block)
163
+ if return_md5:
164
+ return m.hexdigest()
165
+ else:
166
+ return
167
+ except RestartableStreamingWriteFailure as err:
168
+ # currently this is the only type of failure we retry, since we can re-read the source
169
+ # stream from the beginning
170
+ # if this failure occurs, the upload must be restarted from the beginning
171
+ # https://cloud.google.com/storage/docs/resumable-uploads#practices
172
+ # https://github.com/googleapis/gcs-resumable-upload/issues/15#issuecomment-249324122
173
+ if self._conf.retry_limit is not None and attempt >= self._conf.retry_limit:
174
+ raise
175
+
176
+ if attempt >= get_log_threshold_for_error(self._conf, str(err)):
177
+ self._conf.log_callback(
178
+ f"error {err} when executing a streaming write to {dst} attempt {attempt}, sleeping for {backoff:.1f} seconds before retrying"
179
+ )
180
+ time.sleep(backoff)
181
+
182
+ def exists(self, path: RemoteOrLocalPath) -> bool:
183
+ path = path_to_str(path)
184
+ if _is_local_path(path):
185
+ return os.path.exists(path)
186
+ elif _is_gcp_path(path):
187
+ st = gcp.maybe_stat(self._conf, path)
188
+ if st is not None:
189
+ return True
190
+ return self.isdir(path)
191
+ elif _is_azure_path(path):
192
+ st = azure.maybe_stat(self._conf, path)
193
+ if st is not None:
194
+ return True
195
+ return self.isdir(path)
196
+ else:
197
+ raise Error(f"Unrecognized path: '{path}'")
198
+
199
+ def basename(self, path: RemoteOrLocalPath) -> str:
200
+ path = path_to_str(path)
201
+ if _is_gcp_path(path):
202
+ _, obj = gcp.split_path(path)
203
+ return obj.split("/")[-1]
204
+ elif _is_azure_path(path):
205
+ _, _, obj = azure.split_path(path)
206
+ return obj.split("/")[-1]
207
+ else:
208
+ return os.path.basename(path)
209
+
210
+ def glob(self, pattern: str, parallel: bool = False) -> Iterator[str]:
211
+ if _is_local_path(pattern):
212
+ # scanglob currently does an os.stat for each matched file
213
+ # until scanglob can be implemented directly on scandir
214
+ # this code is here to avoid that
215
+ if "?" in pattern or "[" in pattern or "]" in pattern:
216
+ raise Error("Advanced glob queries are not supported")
217
+ yield from _local_glob(pattern)
218
+ else:
219
+ for entry in self.scanglob(pattern=pattern, parallel=parallel):
220
+ yield entry.path
221
+
222
+ def scanglob(
223
+ self, pattern: str, parallel: bool = False, shard_prefix_length: int = 0
224
+ ) -> Iterator[DirEntry]:
225
+ if "?" in pattern or "[" in pattern or "]" in pattern:
226
+ raise Error("Advanced glob queries are not supported")
227
+
228
+ if _is_local_path(pattern):
229
+ for filepath in _local_glob(pattern):
230
+ # doing a stat call for each file isn't the most efficient
231
+ # iglob uses os.scandir internally, but doesn't expose the information from that, so we'd
232
+ # need to re-implement local glob
233
+ # we could make the behavior with remote glob more consistent though if we did that
234
+ s = os.stat(filepath)
235
+ is_dir = stat_module.S_ISDIR(s.st_mode)
236
+ yield DirEntry(
237
+ path=filepath,
238
+ name=self.basename(filepath),
239
+ is_dir=is_dir,
240
+ is_file=not is_dir,
241
+ stat=None
242
+ if is_dir
243
+ else Stat(
244
+ size=s.st_size, mtime=s.st_mtime, ctime=s.st_ctime, md5=None, version=None
245
+ ),
246
+ )
247
+ elif _is_gcp_path(pattern) or _is_azure_path(pattern):
248
+ if "*" not in pattern:
249
+ entry = _get_entry(self._conf, pattern)
250
+ if entry is not None:
251
+ yield entry
252
+ return
253
+
254
+ if _is_gcp_path(pattern):
255
+ bucket, blob_prefix = gcp.split_path(pattern)
256
+ if "*" in bucket:
257
+ raise Error("Wildcards cannot be used in bucket name")
258
+ root = gcp.combine_path(bucket, "")
259
+ else:
260
+ account, container, blob_prefix = azure.split_path(pattern)
261
+ if "*" in account or "*" in container:
262
+ raise Error("Wildcards cannot be used in account or container")
263
+ root = azure.combine_path(self._conf, account, container, "")
264
+
265
+ if shard_prefix_length == 0:
266
+ initial_tasks = [_GlobTask("", _split_path(blob_prefix))]
267
+ else:
268
+ assert (
269
+ parallel
270
+ ), "You probably want to use parallel=True if you are setting shard_prefix_length > 0"
271
+ initial_tasks = []
272
+ valid_chars = [
273
+ i for i in range(256) if i not in INVALID_CHARS.union([ord("/"), ord("*")])
274
+ ]
275
+ pattern_prefix, pattern_suffix = blob_prefix.split("*", maxsplit=1)
276
+ for repeat in range(1, shard_prefix_length + 1):
277
+ for chars in itertools.product(valid_chars, repeat=repeat):
278
+ prefix = ""
279
+ for c in chars:
280
+ prefix += chr(c)
281
+ # we need to check for exact matches for shorter prefix lengths
282
+ # if we only searched for prefixes of length `shard_prefix_length`
283
+ # we would skip shorter names, for instance "a" would be skipped if we
284
+ # we had `shard_prefix_length=2`
285
+ # instead we check for an exact match for everything shorter than
286
+ # our `shard_prefix_length`
287
+ exact = repeat != shard_prefix_length
288
+ if exact:
289
+ pat = pattern_prefix + prefix
290
+ else:
291
+ pat = pattern_prefix + prefix + "*" + pattern_suffix
292
+ initial_tasks.append(_GlobTask("", _split_path(pat)))
293
+
294
+ if parallel:
295
+ mp_ctx = mp.get_context(self._conf.multiprocessing_start_method)
296
+ tasks = mp_ctx.Queue()
297
+ for t in initial_tasks:
298
+ tasks.put(t)
299
+ tasks_enqueued = len(initial_tasks)
300
+ results = mp_ctx.Queue()
301
+
302
+ tasks_done = 0
303
+ with mp_ctx.Pool(
304
+ initializer=_glob_worker, initargs=(self._conf, root, tasks, results)
305
+ ):
306
+ while tasks_done < tasks_enqueued:
307
+ r = results.get()
308
+ if isinstance(r, _GlobEntry):
309
+ yield r.entry
310
+ elif isinstance(r, _GlobTask):
311
+ tasks.put(r)
312
+ tasks_enqueued += 1
313
+ elif isinstance(r, _GlobTaskComplete):
314
+ tasks_done += 1
315
+ else:
316
+ raise Error("Invalid result")
317
+ else:
318
+ dq: collections.deque[_GlobTask] = collections.deque()
319
+ for t in initial_tasks:
320
+ dq.append(t)
321
+ while len(dq) > 0:
322
+ t = dq.popleft()
323
+ for r in _process_glob_task(conf=self._conf, root=root, t=t):
324
+ if isinstance(r, _GlobEntry):
325
+ yield r.entry
326
+ else:
327
+ dq.append(r)
328
+ else:
329
+ raise Error(f"Unrecognized path '{pattern}'")
330
+
331
+ def isdir(self, path: RemoteOrLocalPath) -> bool:
332
+ path = path_to_str(path)
333
+ if _is_local_path(path):
334
+ return os.path.isdir(path)
335
+ elif _is_gcp_path(path):
336
+ return gcp.isdir(self._conf, path)
337
+ elif _is_azure_path(path):
338
+ return azure.isdir(self._conf, path)
339
+ else:
340
+ raise Error(f"Unrecognized path: '{path}'")
341
+
342
+ def listdir(self, path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[str]:
343
+ path = path_to_str(path)
344
+ for entry in self.scandir(path, shard_prefix_length=shard_prefix_length):
345
+ yield entry.name
346
+
347
+ def scandir(self, path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[DirEntry]:
348
+ path = path_to_str(path)
349
+ if (_is_gcp_path(path) or _is_azure_path(path)) and not path.endswith("/"):
350
+ path += "/"
351
+ if not self.exists(path):
352
+ raise FileNotFoundError(f"The system cannot find the path specified: '{path}'")
353
+ if not self.isdir(path):
354
+ raise NotADirectoryError(f"The directory name is invalid: '{path}'")
355
+ if _is_local_path(path):
356
+ for de in os.scandir(path):
357
+ if de.is_dir():
358
+ yield DirEntry(
359
+ name=de.name,
360
+ path=os.path.abspath(de.path),
361
+ is_dir=True,
362
+ is_file=False,
363
+ stat=None,
364
+ )
365
+ else:
366
+ s = de.stat()
367
+ yield DirEntry(
368
+ name=de.name,
369
+ path=os.path.abspath(de.path),
370
+ is_dir=False,
371
+ is_file=True,
372
+ stat=Stat(
373
+ size=s.st_size,
374
+ mtime=s.st_mtime,
375
+ ctime=s.st_ctime,
376
+ md5=None,
377
+ version=None,
378
+ ),
379
+ )
380
+ elif _is_gcp_path(path) or _is_azure_path(path):
381
+ if shard_prefix_length == 0:
382
+ yield from _list_blobs_in_dir(conf=self._conf, prefix=path, exclude_prefix=True)
383
+ else:
384
+ mp_ctx = mp.get_context(self._conf.multiprocessing_start_method)
385
+ prefixes = mp_ctx.Queue()
386
+ items = mp_ctx.Queue()
387
+ tasks_enqueued = 0
388
+
389
+ valid_chars = [i for i in range(256) if i not in INVALID_CHARS and i != ord("/")]
390
+ for repeat in range(1, shard_prefix_length + 1):
391
+ for chars in itertools.product(valid_chars, repeat=repeat):
392
+ prefix = ""
393
+ for c in chars:
394
+ prefix += chr(c)
395
+ # we need to check for exact matches for shorter prefix lengths
396
+ # if we only searched for prefixes of length `shard_prefix_length`
397
+ # we would skip shorter names, for instance "a" would be skipped if we
398
+ # we had `shard_prefix_length=2`
399
+ # instead we check for an exact match for everything shorter than
400
+ # our `shard_prefix_length`
401
+ exact = repeat != shard_prefix_length
402
+ prefixes.put((path, prefix, exact))
403
+ tasks_enqueued += 1
404
+
405
+ tasks_done = 0
406
+ with mp_ctx.Pool(
407
+ initializer=_sharded_listdir_worker, initargs=(self._conf, prefixes, items)
408
+ ):
409
+ while tasks_done < tasks_enqueued:
410
+ entry = items.get()
411
+ if entry is None:
412
+ tasks_done += 1
413
+ continue
414
+ yield entry
415
+ else:
416
+ raise Error(f"Unrecognized path: '{path}'")
417
+
418
+ def makedirs(self, path: RemoteOrLocalPath) -> None:
419
+ path = path_to_str(path)
420
+ if _is_local_path(path):
421
+ os.makedirs(path, exist_ok=True)
422
+ elif _is_gcp_path(path):
423
+ gcp.mkdirfile(self._conf, path)
424
+ elif _is_azure_path(path):
425
+ azure.mkdirfile(self._conf, path)
426
+ else:
427
+ raise Error(f"Unrecognized path: '{path}'")
428
+
429
+ def remove(self, path: RemoteOrLocalPath) -> None:
430
+ path = path_to_str(path)
431
+ if _is_local_path(path):
432
+ os.remove(path)
433
+ elif _is_gcp_path(path):
434
+ if path.endswith("/"):
435
+ raise IsADirectoryError(f"Is a directory: '{path}'")
436
+ ok = gcp.remove(self._conf, path)
437
+ if not ok:
438
+ raise FileNotFoundError(f"The system cannot find the path specified: '{path}'")
439
+ elif _is_azure_path(path):
440
+ if path.endswith("/"):
441
+ raise IsADirectoryError(f"Is a directory: '{path}'")
442
+ ok = azure.remove(self._conf, path)
443
+ if not ok:
444
+ raise FileNotFoundError(f"The system cannot find the path specified: '{path}'")
445
+ else:
446
+ raise Error(f"Unrecognized path: '{path}'")
447
+
448
+ def rmdir(self, path: RemoteOrLocalPath) -> None:
449
+ path = path_to_str(path)
450
+ if _is_local_path(path):
451
+ os.rmdir(path)
452
+ return
453
+
454
+ # directories in blob storage are different from normal directories
455
+ # a directory exists if there are any blobs that have that directory as a prefix
456
+ # when the last blob with that prefix is deleted, the directory no longer exists
457
+ # except in the case when there is a blob with a name ending in a slash
458
+ # representing an empty directory
459
+
460
+ # to make this more usable it is not an error to delete a directory that does
461
+ # not exist, but is still an error to delete a non-empty one
462
+ if not path.endswith("/"):
463
+ path += "/"
464
+
465
+ if _is_gcp_path(path):
466
+ _, blob = gcp.split_path(path)
467
+ elif _is_azure_path(path):
468
+ _, _, blob = azure.split_path(path)
469
+ else:
470
+ raise Error(f"Unrecognized path: '{path}'")
471
+
472
+ if blob == "":
473
+ raise Error(f"Cannot delete bucket: '{path}'")
474
+ it = self.listdir(path)
475
+ try:
476
+ next(it)
477
+ except FileNotFoundError:
478
+ # this directory does not exist
479
+ return
480
+ except StopIteration:
481
+ # this directory exists and is empty
482
+ pass
483
+ else:
484
+ # this directory exists but is not empty
485
+ raise OSError(f"The directory is not empty: '{path}'")
486
+
487
+ if _is_gcp_path(path):
488
+ bucket, blob = gcp.split_path(path)
489
+ req = Request(
490
+ url=gcp.build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob),
491
+ method="DELETE",
492
+ success_codes=(204,),
493
+ )
494
+ gcp.execute_api_request(self._conf, req)
495
+ elif _is_azure_path(path):
496
+ account, container, blob = azure.split_path(path)
497
+ req = Request(
498
+ url=azure.build_url(account, "/{container}/{blob}", container=container, blob=blob),
499
+ method="DELETE",
500
+ success_codes=(202,),
501
+ )
502
+ azure.execute_api_request(self._conf, req)
503
+ else:
504
+ raise Error(f"Unrecognized path: '{path}'")
505
+
506
+ def stat(self, path: RemoteOrLocalPath) -> Stat:
507
+ path = path_to_str(path)
508
+ if _is_local_path(path):
509
+ s = os.stat(path)
510
+ return Stat(size=s.st_size, mtime=s.st_mtime, ctime=s.st_ctime, md5=None, version=None)
511
+ elif _is_gcp_path(path):
512
+ st = gcp.maybe_stat(self._conf, path)
513
+ if st is None:
514
+ raise FileNotFoundError(f"No such file: '{path}'")
515
+ return st
516
+ elif _is_azure_path(path):
517
+ st = azure.maybe_stat(self._conf, path)
518
+ if st is None:
519
+ raise FileNotFoundError(f"No such file: '{path}'")
520
+ return st
521
+ else:
522
+ raise Error(f"Unrecognized path: '{path}'")
523
+
524
+ def set_mtime(
525
+ self, path: RemoteOrLocalPath, mtime: float, version: Optional[str] = None
526
+ ) -> bool:
527
+ path = path_to_str(path)
528
+ if _is_local_path(path):
529
+ assert version is None
530
+ os.utime(path, times=(mtime, mtime))
531
+ return True
532
+ elif _is_gcp_path(path):
533
+ return gcp.set_mtime(self._conf, path=path, mtime=mtime, version=version)
534
+ elif _is_azure_path(path):
535
+ return azure.set_mtime(self._conf, path=path, mtime=mtime, version=version)
536
+ else:
537
+ raise Error(f"Unrecognized path: '{path}'")
538
+
539
+ def rmtree(
540
+ self,
541
+ path: RemoteOrLocalPath,
542
+ parallel: bool = False,
543
+ parallel_executor: Optional[concurrent.futures.Executor] = None,
544
+ ) -> None:
545
+ path = path_to_str(path)
546
+ if not self.isdir(path):
547
+ raise NotADirectoryError(f"The directory name is invalid: '{path}'")
548
+
549
+ if _is_local_path(path):
550
+ shutil.rmtree(path)
551
+ elif _is_gcp_path(path) or _is_azure_path(path):
552
+ if not path.endswith("/"):
553
+ path += "/"
554
+
555
+ if _is_gcp_path(path):
556
+
557
+ def request_generator():
558
+ bucket, blob = gcp.split_path(path)
559
+ for entry in gcp.list_blobs(self._conf, path):
560
+ entry_slash_path = _get_slash_path(entry)
561
+ entry_bucket, entry_blob = gcp.split_path(entry_slash_path)
562
+ assert entry_bucket == bucket and entry_blob.startswith(blob)
563
+ req = Request(
564
+ url=gcp.build_url(
565
+ "/storage/v1/b/{bucket}/o/{object}",
566
+ bucket=bucket,
567
+ object=entry_blob,
568
+ ),
569
+ method="DELETE",
570
+ # 404 is allowed in case a failed request successfully deleted the file
571
+ # before erroring out
572
+ success_codes=(204, 404),
573
+ )
574
+ yield req
575
+
576
+ fn = gcp.execute_api_request
577
+
578
+ elif _is_azure_path(path):
579
+
580
+ def request_generator():
581
+ account, container, blob = azure.split_path(path)
582
+ for entry in azure.list_blobs(self._conf, path):
583
+ entry_slash_path = _get_slash_path(entry)
584
+ entry_account, entry_container, entry_blob = azure.split_path(
585
+ entry_slash_path
586
+ )
587
+ assert (
588
+ entry_account == account
589
+ and entry_container == container
590
+ and entry_blob.startswith(blob)
591
+ )
592
+ req = Request(
593
+ url=azure.build_url(
594
+ account, "/{container}/{blob}", container=container, blob=entry_blob
595
+ ),
596
+ method="DELETE",
597
+ # 404 is allowed in case a failed request successfully deleted the file
598
+ # before erroring out
599
+ success_codes=(202, 404),
600
+ )
601
+ yield req
602
+
603
+ fn = azure.execute_api_request
604
+ else:
605
+ raise Error(f"Unrecognized path: '{path}'")
606
+
607
+ if parallel:
608
+ if parallel_executor is None:
609
+ executor = concurrent.futures.ProcessPoolExecutor(
610
+ mp_context=mp.get_context(self._conf.multiprocessing_start_method)
611
+ )
612
+ context = executor
613
+ else:
614
+ executor = parallel_executor
615
+ context = contextlib.nullcontext()
616
+
617
+ futures = []
618
+ with context:
619
+ for req in request_generator():
620
+ f = executor.submit(_execute_fn_and_ignore_result, fn, self._conf, req)
621
+ futures.append(f)
622
+ for f in futures:
623
+ f.result()
624
+ else:
625
+ for req in request_generator():
626
+ fn(self._conf, req)
627
+ else:
628
+ raise Error(f"Unrecognized path: '{path}'")
629
+
630
+ def walk(
631
+ self,
632
+ top: RemoteOrLocalPath,
633
+ topdown: bool = True,
634
+ onerror: Optional[Callable[[OSError], None]] = None,
635
+ ) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]:
636
+ top = path_to_str(top)
637
+ if not self.isdir(top):
638
+ return
639
+
640
+ if _is_local_path(top):
641
+ top = os.path.normpath(top)
642
+ for root, dirnames, filenames in os.walk(top=top, topdown=topdown, onerror=onerror):
643
+ assert isinstance(root, str)
644
+ if root.endswith(os.sep):
645
+ root = root[:-1]
646
+ yield (root, sorted(dirnames), sorted(filenames))
647
+ elif _is_gcp_path(top) or _is_azure_path(top):
648
+ top = _normalize_path(self._conf, top)
649
+ if not top.endswith("/"):
650
+ top += "/"
651
+ if topdown:
652
+ dq: collections.deque[str] = collections.deque()
653
+ dq.append(top)
654
+ while len(dq) > 0:
655
+ cur = dq.popleft()
656
+ assert cur.endswith("/")
657
+ if _is_gcp_path(top):
658
+ it = gcp.list_blobs(self._conf, cur, delimiter="/")
659
+ elif _is_azure_path(top):
660
+ it = azure.list_blobs(self._conf, cur, delimiter="/")
661
+ else:
662
+ raise Error(f"Unrecognized path: '{top}'")
663
+ dirnames = []
664
+ filenames = []
665
+ for entry in it:
666
+ entry_path = _get_slash_path(entry)
667
+ if entry_path == cur:
668
+ continue
669
+ if entry.is_dir:
670
+ dirnames.append(entry.name)
671
+ else:
672
+ filenames.append(entry.name)
673
+ yield (_strip_slash(cur), dirnames, filenames)
674
+ dq.extend(self.join(cur, dirname) + "/" for dirname in dirnames)
675
+ else:
676
+ if _is_gcp_path(top):
677
+ it = gcp.list_blobs(self._conf, top)
678
+ elif _is_azure_path(top):
679
+ it = azure.list_blobs(self._conf, top)
680
+ else:
681
+ raise Error(f"Unrecognized path: '{top}'")
682
+
683
+ cur = []
684
+ dirnames_stack = [[]]
685
+ filenames_stack = [[]]
686
+ for entry in it:
687
+ entry_slash_path = _get_slash_path(entry)
688
+ if entry_slash_path == top:
689
+ continue
690
+ relpath = entry_slash_path[len(top) :]
691
+ parts = relpath.split("/")
692
+ dirpath = parts[:-1]
693
+ if dirpath != cur:
694
+ # pop directories from the current path until we match the prefix of this new path
695
+ while cur != dirpath[: len(cur)]:
696
+ yield (top + "/".join(cur), dirnames_stack.pop(), filenames_stack.pop())
697
+ cur.pop()
698
+ # push directories from the new path until the current path matches it
699
+ while cur != dirpath:
700
+ dirname = dirpath[len(cur)]
701
+ cur.append(dirname)
702
+ filenames_stack.append([])
703
+ # add this to child dir to the list of dirs for the parent
704
+ dirnames_stack[-1].append(dirname)
705
+ dirnames_stack.append([])
706
+ if entry.is_file:
707
+ filenames_stack[-1].append(entry.name)
708
+ while len(cur) > 0:
709
+ yield (top + "/".join(cur), dirnames_stack.pop(), filenames_stack.pop())
710
+ cur.pop()
711
+ yield (_strip_slash(top), dirnames_stack.pop(), filenames_stack.pop())
712
+ assert len(dirnames_stack) == 0 and len(filenames_stack) == 0
713
+ else:
714
+ raise Error(f"Unrecognized path: '{top}'")
715
+
716
+ def dirname(self, path: RemoteOrLocalPath) -> str:
717
+ path = path_to_str(path)
718
+ if _is_gcp_path(path):
719
+ return gcp.dirname(self._conf, path)
720
+ elif _is_azure_path(path):
721
+ return azure.dirname(self._conf, path)
722
+ else:
723
+ return os.path.dirname(path)
724
+
725
+ def join(self, a: RemoteOrLocalPath, *args: str) -> str:
726
+ a = path_to_str(a)
727
+ out = a
728
+ for b in args:
729
+ out = _join2(self._conf, out, b)
730
+ return out
731
+
732
+ def get_url(self, path: RemoteOrLocalPath) -> Tuple[str, Optional[float]]:
733
+ path = path_to_str(path)
734
+ if _is_gcp_path(path):
735
+ return gcp.get_url(self._conf, path)
736
+ elif _is_azure_path(path):
737
+ return azure.get_url(self._conf, path)
738
+ elif _is_local_path(path):
739
+ return f"file://{path}", None
740
+ else:
741
+ raise Error(f"Unrecognized path: '{path}'")
742
+
743
+ def md5(self, path: RemoteOrLocalPath) -> str:
744
+ path = path_to_str(path)
745
+ if _is_gcp_path(path):
746
+ st = gcp.maybe_stat(self._conf, path)
747
+ if st is None:
748
+ raise FileNotFoundError(f"No such file: '{path}'")
749
+
750
+ h = st.md5
751
+ if h is not None:
752
+ return h
753
+
754
+ # this is probably a composite object, calculate the md5 and store it on the file if the file has not changed
755
+ with self.BlobFile(path, "rb") as f:
756
+ result = common.block_md5(f).hex()
757
+
758
+ assert st.version is not None
759
+ gcp.maybe_update_md5(self._conf, path, st.version, result)
760
+ return result
761
+ elif _is_azure_path(path):
762
+ st = azure.maybe_stat(self._conf, path)
763
+ if st is None:
764
+ raise FileNotFoundError(f"No such file: '{path}'")
765
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties
766
+ h = st.md5
767
+ if h is None:
768
+ # md5 is missing, calculate it and store it on file if the file has not changed
769
+ with self.BlobFile(path, "rb") as f:
770
+ h = common.block_md5(f).hex()
771
+ assert st.version is not None
772
+ azure.maybe_update_md5(self._conf, path, st.version, h)
773
+ return h
774
+ else:
775
+ with self.BlobFile(path, "rb") as f:
776
+ return common.block_md5(f).hex()
777
+
778
+ def last_version_seen(self, file: TextIO | BinaryIO) -> Optional[str]:
779
+ actual: object
780
+ actual = file
781
+ if isinstance(actual, io.TextIOWrapper):
782
+ actual = actual.buffer
783
+ if isinstance(actual, (io.BufferedReader, io.BufferedWriter)):
784
+ actual = actual.raw
785
+ if not isinstance(actual, (azure.StreamingReadFile, azure.StreamingWriteFile)):
786
+ raise ValueError("File was not an Azure BlobFile opened in streaming mode")
787
+ return actual._version # pyright: ignore[reportPrivateUsage]
788
+
789
+ def read_text(self, path: RemoteOrLocalPath) -> str:
790
+ with self.BlobFile(path, "r") as f:
791
+ return f.read()
792
+
793
+ def read_bytes(self, path: RemoteOrLocalPath) -> bytes:
794
+ with self.BlobFile(path, "rb") as f:
795
+ return f.read()
796
+
797
+ def write_text(self, path: RemoteOrLocalPath, text: str) -> None:
798
+ with self.BlobFile(path, "w") as f:
799
+ f.write(text)
800
+
801
+ def write_bytes(self, path: RemoteOrLocalPath, data: bytes) -> None:
802
+ with self.BlobFile(path, "wb") as f:
803
+ f.write(data)
804
+
805
+ @overload
806
+ def BlobFile(
807
+ self,
808
+ path: RemoteOrLocalPath,
809
+ mode: Literal["rb", "wb", "ab"],
810
+ streaming: Optional[bool] = ...,
811
+ buffer_size: Optional[int] = ...,
812
+ cache_dir: Optional[str] = ...,
813
+ file_size: Optional[int] = None,
814
+ version: Optional[str] = None,
815
+ ) -> BinaryIO:
816
+ ...
817
+
818
+ @overload
819
+ def BlobFile(
820
+ self,
821
+ path: RemoteOrLocalPath,
822
+ mode: Literal["r", "w", "a"] = ...,
823
+ streaming: Optional[bool] = ...,
824
+ buffer_size: Optional[int] = ...,
825
+ cache_dir: Optional[str] = ...,
826
+ file_size: Optional[int] = None,
827
+ version: Optional[str] = None,
828
+ ) -> TextIO:
829
+ ...
830
+
831
+ def BlobFile(
832
+ self,
833
+ path: RemoteOrLocalPath,
834
+ mode: Literal["r", "rb", "w", "wb", "a", "ab"] = "r",
835
+ streaming: Optional[bool] = None,
836
+ buffer_size: Optional[int] = None,
837
+ cache_dir: Optional[str] = None,
838
+ file_size: Optional[int] = None,
839
+ version: Optional[str] = None,
840
+ ):
841
+ """
842
+ Open a local or remote file for reading or writing
843
+
844
+ Args:
845
+ path: local or remote path
846
+ mode: one of "r", "rb", "w", "wb", "a", "ab" indicating the mode to open the file in
847
+ streaming: the default for `streaming` is `True` when `mode` is in `"r", "rb"` and `False` when `mode` is in `"w", "wb", "a", "ab"`.
848
+ * `streaming=True`:
849
+ * Reading is done without downloading the entire remote file.
850
+ * 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.
851
+ * Appending is not implemented.
852
+ * `streaming=False`:
853
+ * Reading is done by downloading the remote file to a local file during the constructor.
854
+ * Writing is done by uploading the file on `close()` or during destruction.
855
+ * Appending is done by downloading the file during construction and uploading on `close()` or during destruction.
856
+ buffer_size: number of bytes to buffer, this can potentially make reading more efficient.
857
+ 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.
858
+ 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.
859
+ 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"
860
+
861
+ Returns:
862
+ A file-like object
863
+ """
864
+ path = path_to_str(path)
865
+ if _guess_isdir(path):
866
+ raise IsADirectoryError(f"Is a directory: '{path}'")
867
+
868
+ if streaming is None:
869
+ streaming = mode in ("r", "rb")
870
+
871
+ if file_size is not None:
872
+ assert mode in ("r", "rb"), "Can only specify file_size when reading"
873
+
874
+ if version:
875
+ assert not _is_local_path(path), "Cannot specify version when writing to local file"
876
+ # we check for gcp later to raise a NotImplementedError instead
877
+
878
+ if _is_local_path(path) and "w" in mode:
879
+ # local filesystems require that intermediate directories exist, but this is not required by the
880
+ # remote filesystems
881
+ # for consistency, automatically create local intermediate directories
882
+ if self.dirname(path) != "":
883
+ self.makedirs(self.dirname(path))
884
+
885
+ if buffer_size is None:
886
+ buffer_size = self._conf.default_buffer_size
887
+
888
+ if streaming:
889
+ if mode not in ("w", "wb", "r", "rb"):
890
+ raise Error(f"Invalid mode for streaming file: '{mode}'")
891
+ if cache_dir is not None:
892
+ raise Error("Cannot specify cache_dir for streaming files")
893
+ if _is_local_path(path):
894
+ f = io.FileIO(path, mode=mode)
895
+ if "r" in mode:
896
+ f = io.BufferedReader(f, buffer_size=buffer_size)
897
+ else:
898
+ f = io.BufferedWriter(f, buffer_size=buffer_size)
899
+ elif _is_gcp_path(path):
900
+ if version:
901
+ raise NotImplementedError("Cannot specify version for GCP files")
902
+ if mode in ("w", "wb"):
903
+ f = gcp.StreamingWriteFile(self._conf, path)
904
+ elif mode in ("r", "rb"):
905
+ f = gcp.StreamingReadFile(self._conf, path, size=file_size)
906
+ f = io.BufferedReader(f, buffer_size=buffer_size)
907
+ else:
908
+ raise Error(f"Unsupported mode: '{mode}'")
909
+ elif _is_azure_path(path):
910
+ if mode in ("w", "wb"):
911
+ f = azure.StreamingWriteFile(self._conf, path, version)
912
+ elif mode in ("r", "rb"):
913
+ f = azure.StreamingReadFile(self._conf, path, size=file_size, version=version)
914
+ f = io.BufferedReader(f, buffer_size=buffer_size)
915
+ else:
916
+ raise Error(f"Unsupported mode: '{mode}'")
917
+ else:
918
+ raise Error(f"Unrecognized path: '{path}'")
919
+
920
+ # this should be a protocol so we don't have to cast
921
+ # but the standard library does not seem to have a file-like protocol
922
+ binary_f = cast(BinaryIO, f)
923
+ if "b" in mode:
924
+ return binary_f
925
+ else:
926
+ text_f = io.TextIOWrapper(binary_f, encoding="utf8")
927
+ # TextIOWrapper bypasses buffering on purpose: https://bugs.python.org/issue13393
928
+ # Example: https://gist.github.com/christopher-hesse/b4aab4f6f9bcba597d079f3363dfab2c
929
+ #
930
+ # This happens when TextIOWrapper calls f.read1(CHUNK_SIZE)
931
+ # https://github.com/python/cpython/blob/3d17c045b4c3d09b72bbd95ed78af1ae6f0d98d2/Modules/_io/textio.c#L1854
932
+ # and BufferedReader only reads the requested size, not the buffer_size
933
+ # https://github.com/python/cpython/blob/8666356280084f0426c28a981341f72eaaacd006/Modules/_io/bufferedio.c#L945
934
+ #
935
+ # The workaround appears to be to set the _CHUNK_SIZE property or monkey patch binary_f.read1 to call binary_f.read
936
+ if hasattr(text_f, "_CHUNK_SIZE"):
937
+ setattr(text_f, "_CHUNK_SIZE", buffer_size)
938
+ return cast(TextIO, text_f)
939
+ else:
940
+ remote_path = None
941
+ tmp_dir = None
942
+ if mode not in ("w", "wb", "r", "rb", "a", "ab"):
943
+ raise Error(f"Invalid mode: '{mode}'")
944
+
945
+ if cache_dir is not None and mode not in ("r", "rb"):
946
+ raise Error("cache_dir only supported in read mode")
947
+
948
+ local_filename = self.basename(path)
949
+ if local_filename == "":
950
+ local_filename = "local.tmp"
951
+ if _is_gcp_path(path) or _is_azure_path(path):
952
+ remote_path = path
953
+ if mode in ("a", "ab"):
954
+ tmp_dir = tempfile.mkdtemp()
955
+ local_path = self.join(tmp_dir, local_filename)
956
+ if self.exists(remote_path):
957
+ self.copy(remote_path, local_path)
958
+ elif mode in ("r", "rb"):
959
+ if cache_dir is None:
960
+ tmp_dir = tempfile.mkdtemp()
961
+ local_path = self.join(tmp_dir, local_filename)
962
+ self.copy(remote_path, local_path)
963
+ else:
964
+ if not _is_local_path(cache_dir):
965
+ raise Error(f"cache_dir must be a local path: '{cache_dir}'")
966
+ self.makedirs(cache_dir)
967
+ path_md5 = hashlib.md5(path.encode("utf8")).hexdigest()
968
+ lock_path = self.join(cache_dir, f"{path_md5}.lock")
969
+ tmp_path = self.join(cache_dir, f"{path_md5}.tmp")
970
+ with filelock.FileLock(lock_path):
971
+ remote_version = ""
972
+ # get some sort of consistent remote hash so we can check for a local file
973
+ if _is_gcp_path(path):
974
+ st = gcp.maybe_stat(self._conf, path)
975
+ if st is None:
976
+ raise FileNotFoundError(f"No such file: '{path}'")
977
+ assert st.version is not None
978
+ remote_version = st.version
979
+ remote_hash = st.md5
980
+ elif _is_azure_path(path):
981
+ # in the azure case the remote md5 may not exist
982
+ # this duplicates some of md5() because we want more control
983
+ st = azure.maybe_stat(self._conf, path)
984
+ if st is None:
985
+ raise FileNotFoundError(f"No such file: '{path}'")
986
+ assert st.version is not None
987
+ remote_version = st.version
988
+ remote_hash = st.md5
989
+ else:
990
+ raise Error(f"Unrecognized path: '{path}'")
991
+
992
+ perform_copy = False
993
+ if remote_hash is None:
994
+ # there is no remote md5, copy the file
995
+ # and attempt to update the md5
996
+ perform_copy = True
997
+ else:
998
+ expected_local_path = self.join(
999
+ cache_dir, remote_hash, local_filename
1000
+ )
1001
+ perform_copy = not self.exists(expected_local_path)
1002
+
1003
+ if perform_copy:
1004
+ local_hexdigest = self.copy(
1005
+ remote_path, tmp_path, overwrite=True, return_md5=True
1006
+ )
1007
+ assert local_hexdigest is not None, "failed to return md5"
1008
+ # the file we downloaded may not match the remote file because
1009
+ # the remote file changed while we were downloading it
1010
+ # in this case make sure we don't cache it under the wrong md5
1011
+ local_path = self.join(cache_dir, local_hexdigest, local_filename)
1012
+ os.makedirs(self.dirname(local_path), exist_ok=True)
1013
+ if os.path.exists(local_path):
1014
+ # the file is already here, nevermind
1015
+ os.remove(tmp_path)
1016
+ else:
1017
+ os.replace(tmp_path, local_path)
1018
+
1019
+ if remote_hash is None:
1020
+ if _is_azure_path(path):
1021
+ azure.maybe_update_md5(
1022
+ self._conf, path, remote_version, local_hexdigest
1023
+ )
1024
+ elif _is_gcp_path(path):
1025
+ gcp.maybe_update_md5(
1026
+ self._conf, path, remote_version, local_hexdigest
1027
+ )
1028
+ else:
1029
+ assert remote_hash is not None
1030
+ local_path = self.join(cache_dir, remote_hash, local_filename)
1031
+ else:
1032
+ tmp_dir = tempfile.mkdtemp()
1033
+ local_path = self.join(tmp_dir, local_filename)
1034
+ elif _is_local_path(path):
1035
+ local_path = path
1036
+ else:
1037
+ raise Error(f"Unrecognized path: '{path}'")
1038
+
1039
+ f = _ProxyFile(
1040
+ ctx=self,
1041
+ local_path=local_path,
1042
+ mode=mode,
1043
+ tmp_dir=tmp_dir,
1044
+ remote_path=remote_path,
1045
+ version=version,
1046
+ )
1047
+ if "r" in mode:
1048
+ f = io.BufferedReader(f, buffer_size=buffer_size)
1049
+ else:
1050
+ f = io.BufferedWriter(f, buffer_size=buffer_size)
1051
+ binary_f = cast(BinaryIO, f)
1052
+ if "b" in mode:
1053
+ return binary_f
1054
+ else:
1055
+ text_f = io.TextIOWrapper(binary_f, encoding="utf8")
1056
+ return cast(TextIO, text_f)
1057
+
1058
+
1059
+ def default_log_fn(msg: str) -> None:
1060
+ print(f"blobfile: {msg}")
1061
+
1062
+
1063
+ def _is_gcp_path(path: str) -> bool:
1064
+ url = urllib.parse.urlparse(path)
1065
+ return url.scheme == "gs"
1066
+
1067
+
1068
+ def _is_azure_path(path: str) -> bool:
1069
+ url = urllib.parse.urlparse(path)
1070
+ return (
1071
+ url.scheme == "https" and url.netloc.endswith(".blob.core.windows.net")
1072
+ ) or url.scheme == "az"
1073
+
1074
+
1075
+ def _get_module(path: str) -> Optional[ModuleType]:
1076
+ if _is_gcp_path(path):
1077
+ return gcp
1078
+ elif _is_azure_path(path):
1079
+ return azure
1080
+ else:
1081
+ return None
1082
+
1083
+
1084
+ def _is_local_path(path: str) -> bool:
1085
+ return _get_module(path) is None
1086
+
1087
+
1088
+ def _download_chunk(
1089
+ conf: Config, src: str, dst: str, start: int, size: int, src_file_size: int
1090
+ ) -> None:
1091
+ ctx = Context(conf)
1092
+ with ctx.BlobFile(src, "rb", file_size=src_file_size) as src_f:
1093
+ src_f.seek(start)
1094
+ # open output file such that we can write directly to the correct range
1095
+ with open(dst, "rb+") as dst_f:
1096
+ dst_f.seek(start)
1097
+ bytes_read = 0
1098
+ while True:
1099
+ n = min(CHUNK_SIZE, size - bytes_read)
1100
+ assert n >= 0
1101
+ block = src_f.read(n)
1102
+ if block == b"":
1103
+ if bytes_read != size:
1104
+ raise Error(
1105
+ f"read wrong number of bytes from file `{src}`, expected {size} but read {bytes_read}"
1106
+ )
1107
+ break
1108
+ dst_f.write(block)
1109
+ bytes_read += len(block)
1110
+
1111
+
1112
+ def _parallel_download(
1113
+ conf: Config, executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool
1114
+ ) -> Optional[str]:
1115
+ ctx = Context(conf=conf)
1116
+
1117
+ s = ctx.stat(src)
1118
+
1119
+ # pre-allocate output file
1120
+ if os.path.dirname(dst) != "":
1121
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
1122
+ with open(dst, "wb") as f:
1123
+ if s.size > 0:
1124
+ f.seek(s.size - 1)
1125
+ f.write(b"\0")
1126
+
1127
+ max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1)
1128
+ part_size = max(math.ceil(s.size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE)
1129
+ start = 0
1130
+ futures = []
1131
+ while start < s.size:
1132
+ future = executor.submit(
1133
+ _download_chunk, conf, src, dst, start, min(part_size, s.size - start), s.size
1134
+ )
1135
+ futures.append(future)
1136
+ start += part_size
1137
+ for future in futures:
1138
+ future.result()
1139
+
1140
+ if return_md5:
1141
+ with ctx.BlobFile(dst, "rb") as f:
1142
+ return binascii.hexlify(common.block_md5(f)).decode("utf8")
1143
+
1144
+
1145
+ def _string_overlap(s1: str, s2: str) -> int:
1146
+ length = min(len(s1), len(s2))
1147
+ for i in range(length):
1148
+ if s1[i] != s2[i]:
1149
+ return i
1150
+ return length
1151
+
1152
+
1153
+ def _split_path(path: str) -> List[str]:
1154
+ # a/b/c => a/, b/, c
1155
+ # a/b/ => a/, b/
1156
+ # /a/b/c => /, a/, b/, c
1157
+ parts = []
1158
+ part = ""
1159
+ for c in path:
1160
+ part += c
1161
+ if c == "/":
1162
+ parts.append(part)
1163
+ part = ""
1164
+ if part != "":
1165
+ parts.append(part)
1166
+ return parts
1167
+
1168
+
1169
+ def _expand_implicit_dirs(root: str, it: Iterator[DirEntry]) -> Iterator[DirEntry]:
1170
+ # blob storage does not always have definitions for each intermediate dir
1171
+ # if we have a listing like
1172
+ # gs://test/a/b
1173
+ # gs://test/a/b/c/d
1174
+ # then we emit an entry "gs://test/a/b/c" for the implicit dir "c"
1175
+ # requires that iterator return objects in sorted order
1176
+ if _is_gcp_path(root):
1177
+ entry_from_dirpath = gcp.entry_from_dirpath
1178
+ elif _is_azure_path(root):
1179
+ entry_from_dirpath = azure.entry_from_dirpath
1180
+ else:
1181
+ raise Error(f"Unrecognized path '{root}'")
1182
+
1183
+ previous_path = root
1184
+ for entry in it:
1185
+ # find the overlap between the previous_path and the current
1186
+ entry_slash_path = _get_slash_path(entry)
1187
+ offset = _string_overlap(previous_path, entry_slash_path)
1188
+ relpath = entry_slash_path[offset:]
1189
+ cur = entry_slash_path[:offset]
1190
+ for part in _split_path(relpath)[:-1]:
1191
+ cur += part
1192
+ yield entry_from_dirpath(cur)
1193
+ yield entry
1194
+ # assert entry_slash_path.encode("utf_16_be") >= previous_path.encode("utf_16_be")
1195
+ previous_path = entry_slash_path
1196
+
1197
+
1198
+ def _compile_pattern(s: str, sep: str = "/"):
1199
+ tokens = [t for t in re.split("([*]+)", s) if t != ""]
1200
+ regexp = ""
1201
+ for tok in tokens:
1202
+ if tok == "*":
1203
+ regexp += f"[^{sep}]*"
1204
+ elif tok == "**":
1205
+ regexp += ".*"
1206
+ else:
1207
+ regexp += re.escape(tok)
1208
+ return re.compile(regexp + f"{sep}?$")
1209
+
1210
+
1211
+ def _glob_full(conf: Config, pattern: str) -> Iterator[DirEntry]:
1212
+ prefix, _, _ = pattern.partition("*")
1213
+
1214
+ re_pattern = _compile_pattern(pattern)
1215
+
1216
+ for entry in _expand_implicit_dirs(root=prefix, it=_list_blobs(conf=conf, path=prefix)):
1217
+ entry_slash_path = _get_slash_path(entry)
1218
+ if bool(re_pattern.match(entry_slash_path)):
1219
+ if entry_slash_path == prefix and entry.is_dir:
1220
+ # we matched the parent directory
1221
+ continue
1222
+ yield entry
1223
+
1224
+
1225
+ class _GlobTask(NamedTuple):
1226
+ cur: str
1227
+ rem: Sequence[str]
1228
+
1229
+
1230
+ class _GlobEntry(NamedTuple):
1231
+ entry: DirEntry
1232
+
1233
+
1234
+ class _GlobTaskComplete(NamedTuple):
1235
+ pass
1236
+
1237
+
1238
+ def _process_glob_task(
1239
+ conf: Config, root: str, t: _GlobTask
1240
+ ) -> Iterator[Union[_GlobTask, _GlobEntry]]:
1241
+ cur = t.cur + t.rem[0]
1242
+ rem = t.rem[1:]
1243
+ if "**" in cur:
1244
+ for entry in _glob_full(conf, root + cur + "".join(rem)):
1245
+ yield _GlobEntry(entry)
1246
+ elif "*" in cur:
1247
+ re_pattern = _compile_pattern(root + cur)
1248
+ prefix, _, _ = cur.partition("*")
1249
+ path = root + prefix
1250
+ for entry in _list_blobs(conf=conf, path=path, delimiter="/"):
1251
+ entry_slash_path = _get_slash_path(entry)
1252
+ # in the case of dirname/* we should not return the path dirname/
1253
+ if entry_slash_path == path and entry.is_dir:
1254
+ # we matched the parent directory
1255
+ continue
1256
+ if bool(re_pattern.match(entry_slash_path)):
1257
+ if len(rem) == 0:
1258
+ yield _GlobEntry(entry)
1259
+ else:
1260
+ assert entry_slash_path.startswith(root)
1261
+ yield _GlobTask(entry_slash_path[len(root) :], rem)
1262
+ else:
1263
+ if len(rem) == 0:
1264
+ path = root + cur
1265
+ entry = _get_entry(conf, path)
1266
+ if entry is not None:
1267
+ yield _GlobEntry(entry)
1268
+ else:
1269
+ yield _GlobTask(cur, rem)
1270
+
1271
+
1272
+ def _glob_worker(
1273
+ conf: Config,
1274
+ root: str,
1275
+ tasks: mp.Queue[_GlobTask],
1276
+ results: mp.Queue[Union[_GlobEntry, _GlobTask, _GlobTaskComplete]],
1277
+ ) -> None:
1278
+ while True:
1279
+ t = tasks.get()
1280
+ for r in _process_glob_task(conf, root=root, t=t):
1281
+ results.put(r)
1282
+ results.put(_GlobTaskComplete())
1283
+
1284
+
1285
+ def _local_glob(pattern: str) -> Iterator[str]:
1286
+ normalized_pattern = os.path.normpath(pattern)
1287
+ if pattern.endswith("/") or pattern.endswith("\\"):
1288
+ # normpath will remove a trailing separator
1289
+ # but these affect the output of the glob
1290
+ normalized_pattern += os.sep
1291
+
1292
+ if "*" in normalized_pattern:
1293
+ prefix = normalized_pattern.split("*")[0]
1294
+ if prefix.endswith(os.sep):
1295
+ base_dir = os.path.abspath(prefix)
1296
+ if not base_dir.endswith(os.sep):
1297
+ # if base_dir is the root directory it will already have a separator
1298
+ base_dir += os.sep
1299
+ pattern_suffix = normalized_pattern[len(prefix) :]
1300
+ else:
1301
+ dirpath = os.path.dirname(prefix)
1302
+ base_dir = os.path.abspath(dirpath)
1303
+ # prefix dirpath pattern_suffix
1304
+ # /a/b /a /b
1305
+ # a/c a /c
1306
+ # b "" ""
1307
+ # "" "" ""
1308
+ if len(dirpath) == 0:
1309
+ pattern_suffix = os.sep + normalized_pattern
1310
+ else:
1311
+ pattern_suffix = normalized_pattern[len(dirpath) :]
1312
+ full_pattern = base_dir + pattern_suffix
1313
+ regexp = _compile_pattern(full_pattern, sep=os.sep)
1314
+ for root, dirnames, filenames in os.walk(base_dir):
1315
+ paths = [os.path.join(root, dirname + os.sep) for dirname in dirnames]
1316
+ paths += [os.path.join(root, filename) for filename in filenames]
1317
+ for path in paths:
1318
+ if re.match(regexp, path):
1319
+ if path.endswith(os.sep):
1320
+ path = path[:-1]
1321
+ yield path
1322
+ else:
1323
+ path = os.path.abspath(pattern)
1324
+ if os.path.exists(path):
1325
+ if path.endswith(os.sep):
1326
+ path = path[:-1]
1327
+ yield path
1328
+
1329
+
1330
+ def _strip_slash(path: str) -> str:
1331
+ if path.endswith("/"):
1332
+ return path[:-1]
1333
+ else:
1334
+ return path
1335
+
1336
+
1337
+ def _guess_isdir(path: str) -> bool:
1338
+ """
1339
+ Guess if a path is a directory without performing network requests
1340
+ """
1341
+ if _is_local_path(path) and os.path.isdir(path):
1342
+ return True
1343
+ elif (_is_gcp_path(path) or _is_azure_path(path)) and path.endswith("/"):
1344
+ return True
1345
+ return False
1346
+
1347
+
1348
+ def _list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]:
1349
+ params = {}
1350
+ if delimiter is not None:
1351
+ params["delimiter"] = delimiter
1352
+
1353
+ if _is_gcp_path(path):
1354
+ yield from gcp.list_blobs(conf, path, delimiter=delimiter)
1355
+ elif _is_azure_path(path):
1356
+ yield from azure.list_blobs(conf, path, delimiter=delimiter)
1357
+ else:
1358
+ raise Error(f"Unrecognized path: '{path}'")
1359
+
1360
+
1361
+ def _get_slash_path(entry: DirEntry) -> str:
1362
+ return entry.path + "/" if entry.is_dir else entry.path
1363
+
1364
+
1365
+ def _normalize_path(conf: Config, path: str) -> str:
1366
+ # convert paths to the canonical format
1367
+ if _is_azure_path(path):
1368
+ return azure.combine_path(conf, *azure.split_path(path))
1369
+ return path
1370
+
1371
+
1372
+ def _list_blobs_in_dir(conf: Config, prefix: str, exclude_prefix: bool) -> Iterator[DirEntry]:
1373
+ # the prefix check doesn't work without normalization
1374
+ normalized_prefix = _normalize_path(conf, prefix)
1375
+ for entry in _list_blobs(conf=conf, path=normalized_prefix, delimiter="/"):
1376
+ if exclude_prefix and _get_slash_path(entry) == normalized_prefix:
1377
+ continue
1378
+ yield entry
1379
+
1380
+
1381
+ def _get_entry(conf: Config, path: str) -> Optional[DirEntry]:
1382
+ ctx = Context(conf)
1383
+ if _is_gcp_path(path):
1384
+ st = gcp.maybe_stat(conf, path)
1385
+ if st is not None:
1386
+ if path.endswith("/"):
1387
+ return gcp.entry_from_dirpath(path)
1388
+ else:
1389
+ return gcp.entry_from_path_stat(path, st)
1390
+ if ctx.isdir(path):
1391
+ return gcp.entry_from_dirpath(path)
1392
+ elif _is_azure_path(path):
1393
+ st = azure.maybe_stat(conf, path)
1394
+ if st is not None:
1395
+ if path.endswith("/"):
1396
+ return azure.entry_from_dirpath(path)
1397
+ else:
1398
+ return azure.entry_from_path_stat(path, st)
1399
+ if ctx.isdir(path):
1400
+ return azure.entry_from_dirpath(path)
1401
+ else:
1402
+ raise Error(f"Unrecognized path: '{path}'")
1403
+
1404
+ return None
1405
+
1406
+
1407
+ def _sharded_listdir_worker(
1408
+ conf: Config, prefixes: mp.Queue[Tuple[str, str, bool]], items: mp.Queue[Optional[DirEntry]]
1409
+ ) -> None:
1410
+ while True:
1411
+ base, prefix, exact = prefixes.get(True)
1412
+ if exact:
1413
+ path = base + prefix
1414
+ entry = _get_entry(conf, path)
1415
+ if entry is not None:
1416
+ items.put(entry)
1417
+ else:
1418
+ it = _list_blobs_in_dir(conf, base + prefix, exclude_prefix=False)
1419
+ for entry in it:
1420
+ items.put(entry)
1421
+ items.put(None) # indicate that we have finished this path
1422
+
1423
+
1424
+ def _join2(conf: Config, a: str, b: str) -> str:
1425
+ if _is_local_path(a):
1426
+ return os.path.join(a, b)
1427
+ elif _is_gcp_path(a):
1428
+ return gcp.join_paths(conf, a, b)
1429
+ elif _is_azure_path(a):
1430
+ return azure.join_paths(conf, a, b)
1431
+ else:
1432
+ raise Error(f"Unrecognized path: '{a}'")
1433
+
1434
+
1435
+ class _ProxyFile(io.FileIO):
1436
+ def __init__(
1437
+ self,
1438
+ ctx: Context,
1439
+ local_path: str,
1440
+ mode: Literal["r", "rb", "w", "wb", "a", "ab"],
1441
+ tmp_dir: Optional[str],
1442
+ remote_path: Optional[str],
1443
+ version: Optional[str],
1444
+ ) -> None:
1445
+ super().__init__(local_path, mode=mode)
1446
+ self._ctx = ctx
1447
+ self._mode = mode
1448
+ self._tmp_dir = tmp_dir
1449
+ self._local_path = local_path
1450
+ self._remote_path = remote_path
1451
+ self._closed = False
1452
+ self._version = version
1453
+
1454
+ def close(self) -> None:
1455
+ if not hasattr(self, "_closed") or self._closed:
1456
+ return
1457
+
1458
+ super().close()
1459
+ try:
1460
+ if self._remote_path is not None and self._mode in ("w", "wb", "a", "ab"):
1461
+ self._ctx.copy(
1462
+ self._local_path, self._remote_path, overwrite=True, dst_version=self._version
1463
+ )
1464
+ finally:
1465
+ # if the copy fails, still cleanup our local temp file so it is not leaked
1466
+ if self._tmp_dir is not None:
1467
+ os.remove(self._local_path)
1468
+ os.rmdir(self._tmp_dir)
1469
+ self._closed = True
1470
+
1471
+
1472
+ def create_context(
1473
+ *,
1474
+ log_callback: Callable[[str], None] = default_log_fn,
1475
+ connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE,
1476
+ max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT,
1477
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs
1478
+ # the chunk size determines the maximum size of an individual blob
1479
+ azure_write_chunk_size: int = DEFAULT_AZURE_WRITE_CHUNK_SIZE,
1480
+ google_write_chunk_size: int = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE,
1481
+ retry_log_threshold: int = DEFAULT_RETRY_LOG_THRESHOLD,
1482
+ retry_common_log_threshold: int = DEFAULT_RETRY_COMMON_LOG_THRESHOLD,
1483
+ retry_limit: Optional[int] = None,
1484
+ connect_timeout: Optional[int] = DEFAULT_CONNECT_TIMEOUT,
1485
+ read_timeout: Optional[int] = DEFAULT_READ_TIMEOUT,
1486
+ output_az_paths: bool = True,
1487
+ use_azure_storage_account_key_fallback: bool = False,
1488
+ get_http_pool: Optional[Callable[[], urllib3.PoolManager]] = None,
1489
+ use_streaming_read: bool = False,
1490
+ default_buffer_size: int = DEFAULT_BUFFER_SIZE,
1491
+ get_deadline: Optional[Callable[[], float]] = None,
1492
+ save_access_token_to_disk: bool = True,
1493
+ multiprocessing_start_method: str = "spawn",
1494
+ ):
1495
+ """
1496
+ Same argument as configure(), but returns a Context object that has all the blobfile methods on it.
1497
+ """
1498
+ conf = Config(
1499
+ log_callback=log_callback,
1500
+ connection_pool_max_size=connection_pool_max_size,
1501
+ max_connection_pool_count=max_connection_pool_count,
1502
+ azure_write_chunk_size=azure_write_chunk_size,
1503
+ retry_log_threshold=retry_log_threshold,
1504
+ retry_common_log_threshold=retry_common_log_threshold,
1505
+ retry_limit=retry_limit,
1506
+ google_write_chunk_size=google_write_chunk_size,
1507
+ connect_timeout=connect_timeout,
1508
+ read_timeout=read_timeout,
1509
+ output_az_paths=output_az_paths,
1510
+ use_azure_storage_account_key_fallback=use_azure_storage_account_key_fallback,
1511
+ get_http_pool=get_http_pool,
1512
+ use_streaming_read=use_streaming_read,
1513
+ default_buffer_size=default_buffer_size,
1514
+ get_deadline=get_deadline,
1515
+ save_access_token_to_disk=save_access_token_to_disk,
1516
+ multiprocessing_start_method=multiprocessing_start_method,
1517
+ )
1518
+ return Context(conf=conf)
videollama2/lib/python3.10/site-packages/blobfile/_gcp.py ADDED
@@ -0,0 +1,786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import binascii
3
+ import concurrent.futures
4
+ import datetime
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ import platform
10
+ import socket
11
+ import time
12
+ import urllib.parse
13
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple
14
+
15
+ import urllib3
16
+
17
+ from blobfile import _common as common
18
+ from blobfile._common import (
19
+ GCP_BASE_URL,
20
+ BaseStreamingReadFile,
21
+ BaseStreamingWriteFile,
22
+ Config,
23
+ DirEntry,
24
+ Error,
25
+ FileBody,
26
+ Request,
27
+ RequestFailure,
28
+ RestartableStreamingWriteFailure,
29
+ Stat,
30
+ TokenManager,
31
+ path_join,
32
+ strip_slashes,
33
+ )
34
+
35
+ MAX_EXPIRATION = 7 * 24 * 60 * 60
36
+ OAUTH_TOKEN = "oauth_token"
37
+ ANONYMOUS = "anonymous"
38
+
39
+
40
+ def _is_gce_instance() -> bool:
41
+ try:
42
+ socket.getaddrinfo("metadata.google.internal", 80)
43
+ except socket.gaierror:
44
+ return False
45
+ return True
46
+
47
+
48
+ def _b64encode(s: bytes) -> bytes:
49
+ return base64.urlsafe_b64encode(s)
50
+
51
+
52
+ def _sign(private_key: str, msg: bytes) -> bytes:
53
+ from Cryptodome.Hash import SHA256
54
+ from Cryptodome.PublicKey import RSA
55
+ from Cryptodome.Signature import pkcs1_15
56
+
57
+ key = RSA.import_key(private_key)
58
+ h = SHA256.new(msg)
59
+ return pkcs1_15.new(key).sign(h)
60
+
61
+
62
+ def _create_jwt(private_key: str, data: Mapping[str, Any]) -> bytes:
63
+ header_b64 = _b64encode(json.dumps({"alg": "RS256", "typ": "JWT"}).encode("utf8"))
64
+ body_b64 = _b64encode(json.dumps(data).encode("utf8"))
65
+ to_sign = header_b64 + b"." + body_b64
66
+ signature_b64 = _b64encode(_sign(private_key, to_sign))
67
+ return header_b64 + b"." + body_b64 + b"." + signature_b64
68
+
69
+
70
+ def _create_token_request(client_email: str, private_key: str, scopes: List[str]) -> Request:
71
+ # https://developers.google.com/identity/protocols/OAuth2ServiceAccount
72
+ now = time.time()
73
+ claim_set = {
74
+ "iss": client_email,
75
+ "scope": " ".join(scopes),
76
+ "aud": "https://www.googleapis.com/oauth2/v4/token",
77
+ "exp": now + 60 * 60,
78
+ "iat": now,
79
+ }
80
+ data = {
81
+ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
82
+ "assertion": _create_jwt(private_key, claim_set),
83
+ }
84
+ return Request(
85
+ url="https://www.googleapis.com/oauth2/v4/token",
86
+ method="POST",
87
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
88
+ data=urllib.parse.urlencode(data).encode("utf8"),
89
+ )
90
+
91
+
92
+ def _refresh_access_token_request(
93
+ client_id: str, client_secret: str, refresh_token: str
94
+ ) -> Request:
95
+ # https://developers.google.com/identity/protocols/OAuth2WebServer#offline
96
+ data = {
97
+ "grant_type": "refresh_token",
98
+ "refresh_token": refresh_token,
99
+ "client_id": client_id,
100
+ "client_secret": client_secret,
101
+ }
102
+ return Request(
103
+ url="https://www.googleapis.com/oauth2/v4/token",
104
+ method="POST",
105
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
106
+ data=urllib.parse.urlencode(data).encode("utf8"),
107
+ )
108
+
109
+
110
+ def _load_credentials() -> Dict[str, Any]:
111
+ if "GOOGLE_APPLICATION_CREDENTIALS" in os.environ:
112
+ creds_path = os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
113
+ if not os.path.exists(creds_path):
114
+ raise Error(
115
+ f"credentials not found at {creds_path} specified by environment variable 'GOOGLE_APPLICATION_CREDENTIALS'"
116
+ )
117
+ with open(creds_path) as f:
118
+ return json.load(f)
119
+ if platform.system() == "Windows":
120
+ # https://www.jhanley.com/google-cloud-application-default-credentials/
121
+ default_creds_path = os.path.join(
122
+ os.environ["APPDATA"], "gcloud/application_default_credentials.json"
123
+ )
124
+ else:
125
+ default_creds_path = os.path.join(
126
+ os.environ["HOME"], ".config/gcloud/application_default_credentials.json"
127
+ )
128
+
129
+ if os.path.exists(default_creds_path):
130
+ with open(default_creds_path) as f:
131
+ return json.load(f)
132
+ return {}
133
+
134
+
135
+ def _create_access_token_request(creds: Dict[str, Any], scopes: List[str]) -> Request:
136
+ if "private_key" in creds:
137
+ # looks like GCS does not support the no-oauth flow https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
138
+ return _create_token_request(creds["client_email"], creds["private_key"], scopes)
139
+ elif "refresh_token" in creds:
140
+ return _refresh_access_token_request(
141
+ refresh_token=creds["refresh_token"],
142
+ client_id=creds["client_id"],
143
+ client_secret=creds["client_secret"],
144
+ )
145
+ else:
146
+ raise Error("Credentials not recognized")
147
+
148
+
149
+ def build_url(template: str, **data: str) -> str:
150
+ return common.build_url(GCP_BASE_URL, template, **data)
151
+
152
+
153
+ def create_api_request(req: Request, auth: Tuple[str, str]) -> Request:
154
+ if req.headers is None:
155
+ headers = {}
156
+ else:
157
+ headers = dict(req.headers).copy()
158
+
159
+ if req.params is None:
160
+ params = {}
161
+ else:
162
+ params = dict(req.params).copy()
163
+
164
+ kind, token = auth
165
+ if kind == OAUTH_TOKEN:
166
+ headers["Authorization"] = f"Bearer {token}"
167
+ elif kind == ANONYMOUS:
168
+ pass
169
+ else:
170
+ raise Error(f"unrecognized auth kind `{kind}`")
171
+
172
+ data = req.data
173
+ if data is not None and isinstance(data, dict):
174
+ data = json.dumps(data).encode("utf8")
175
+ assert "Content-Type" not in headers
176
+ headers["Content-Type"] = "application/json"
177
+ return Request(
178
+ method=req.method,
179
+ url=req.url,
180
+ params=params,
181
+ headers=headers,
182
+ data=data,
183
+ preload_content=req.preload_content,
184
+ success_codes=tuple(req.success_codes),
185
+ retry_codes=tuple(req.retry_codes),
186
+ )
187
+
188
+
189
+ def generate_signed_url(
190
+ bucket: str,
191
+ name: str,
192
+ expiration: float,
193
+ method: str = "GET",
194
+ params: Optional[Mapping[str, str]] = None,
195
+ headers: Optional[Mapping[str, str]] = None,
196
+ ) -> Tuple[str, Optional[float]]:
197
+ if params is None:
198
+ p = {}
199
+ else:
200
+ p = dict(params).copy()
201
+
202
+ if headers is None:
203
+ h = {}
204
+ else:
205
+ h = dict(headers).copy()
206
+
207
+ # https://cloud.google.com/storage/docs/access-control/signing-urls-manually
208
+ creds = _load_credentials()
209
+ if "private_key" not in creds:
210
+ raise Error(
211
+ "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"
212
+ )
213
+
214
+ if expiration > MAX_EXPIRATION:
215
+ raise Error(f"Expiration can't be longer than {MAX_EXPIRATION} seconds.")
216
+
217
+ escaped_object_name = urllib.parse.quote(name, safe="")
218
+ canonical_uri = f"/{bucket}/{escaped_object_name}"
219
+
220
+ datetime_now = datetime.datetime.now(tz=datetime.timezone.utc)
221
+ request_timestamp = datetime_now.strftime("%Y%m%dT%H%M%SZ")
222
+ datestamp = datetime_now.strftime("%Y%m%d")
223
+
224
+ credential_scope = f"{datestamp}/auto/storage/goog4_request"
225
+ credential = f"{creds['client_email']}/{credential_scope}"
226
+ h["host"] = "storage.googleapis.com"
227
+
228
+ canonical_headers = ""
229
+ ordered_headers = sorted(h.items())
230
+ for k, v in ordered_headers:
231
+ lower_k = str(k).lower()
232
+ strip_v = str(v).lower()
233
+ canonical_headers += f"{lower_k}:{strip_v}\n"
234
+
235
+ signed_headers_parts = []
236
+ for k, _ in ordered_headers:
237
+ lower_k = str(k).lower()
238
+ signed_headers_parts.append(lower_k)
239
+ signed_headers = ";".join(signed_headers_parts)
240
+
241
+ p["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256"
242
+ p["X-Goog-Credential"] = credential
243
+ p["X-Goog-Date"] = request_timestamp
244
+ p["X-Goog-Expires"] = str(expiration)
245
+ p["X-Goog-SignedHeaders"] = signed_headers
246
+
247
+ canonical_query_string_parts = []
248
+ ordered_params = sorted(p.items())
249
+ for k, v in ordered_params:
250
+ encoded_k = urllib.parse.quote(str(k), safe="")
251
+ encoded_v = urllib.parse.quote(str(v), safe="")
252
+ canonical_query_string_parts.append(f"{encoded_k}={encoded_v}")
253
+ canonical_query_string = "&".join(canonical_query_string_parts)
254
+
255
+ canonical_request = "\n".join(
256
+ [
257
+ method,
258
+ canonical_uri,
259
+ canonical_query_string,
260
+ canonical_headers,
261
+ signed_headers,
262
+ "UNSIGNED-PAYLOAD",
263
+ ]
264
+ )
265
+
266
+ canonical_request_hash = hashlib.sha256(canonical_request.encode()).hexdigest()
267
+
268
+ string_to_sign = "\n".join(
269
+ ["GOOG4-RSA-SHA256", request_timestamp, credential_scope, canonical_request_hash]
270
+ )
271
+
272
+ signature = binascii.hexlify(_sign(creds["private_key"], string_to_sign.encode("utf8"))).decode(
273
+ "utf8"
274
+ )
275
+ host_name = "https://storage.googleapis.com"
276
+ signed_url = f"{host_name}{canonical_uri}?{canonical_query_string}&X-Goog-Signature={signature}"
277
+ return signed_url, expiration
278
+
279
+
280
+ def isdir(conf: Config, path: str) -> bool:
281
+ if not path.endswith("/"):
282
+ path += "/"
283
+ bucket, blob = split_path(path)
284
+ if blob == "":
285
+ req = Request(
286
+ url=build_url("/storage/v1/b/{bucket}", bucket=bucket),
287
+ method="GET",
288
+ success_codes=(200, 404),
289
+ )
290
+ resp = execute_api_request(conf, req)
291
+ return resp.status == 200
292
+ else:
293
+ req = Request(
294
+ url=build_url("/storage/v1/b/{bucket}/o", bucket=bucket),
295
+ method="GET",
296
+ params=dict(prefix=blob, delimiter="/", maxResults="1"),
297
+ success_codes=(200, 404),
298
+ )
299
+ resp = execute_api_request(conf, req)
300
+ if resp.status == 404:
301
+ return False
302
+ result = json.loads(resp.data)
303
+ return "items" in result or "prefixes" in result
304
+
305
+
306
+ def mkdirfile(conf: Config, path: str) -> None:
307
+ if not path.endswith("/"):
308
+ path += "/"
309
+ bucket, blob = split_path(path)
310
+ req = Request(
311
+ url=build_url("/upload/storage/v1/b/{bucket}/o", bucket=bucket),
312
+ method="POST",
313
+ params=dict(uploadType="media", name=blob),
314
+ success_codes=(200, 400),
315
+ )
316
+ resp = execute_api_request(conf, req)
317
+ if resp.status == 400:
318
+ raise Error(f"Unable to create directory, bucket does not exist: '{path}'")
319
+
320
+
321
+ def split_path(path: str) -> Tuple[str, str]:
322
+ if not path.startswith("gs://"):
323
+ raise Error(f"Invalid path: '{path}'")
324
+ path = path[len("gs://") :]
325
+ bucket, _, obj = path.partition("/")
326
+ if bucket == "":
327
+ raise Error(f"Invalid path: '{path}'")
328
+ return bucket, obj
329
+
330
+
331
+ def combine_path(bucket: str, obj: str) -> str:
332
+ return f"gs://{bucket}/{obj}"
333
+
334
+
335
+ def get_md5(metadata: Mapping[str, Any]) -> Optional[str]:
336
+ if "md5Hash" in metadata:
337
+ return base64.b64decode(metadata["md5Hash"]).hex()
338
+
339
+ if "metadata" in metadata and "md5" in metadata["metadata"]:
340
+ # fallback to our custom hash if this is a composite object that is lacking the md5Hash field
341
+ return metadata["metadata"]["md5"]
342
+
343
+ return None
344
+
345
+
346
+ def _parse_timestamp(text: str) -> float:
347
+ return datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f%z").timestamp()
348
+
349
+
350
+ def make_stat(item: Mapping[str, Any]) -> Stat:
351
+ if "metadata" in item and "blobfile-mtime" in item["metadata"]:
352
+ mtime = float(item["metadata"]["blobfile-mtime"])
353
+ else:
354
+ mtime = _parse_timestamp(item["updated"])
355
+ return Stat(
356
+ size=int(item["size"]),
357
+ mtime=mtime,
358
+ ctime=_parse_timestamp(item["timeCreated"]),
359
+ md5=get_md5(item),
360
+ version=item["generation"],
361
+ )
362
+
363
+
364
+ def _get_access_token(conf: Config, key: Any) -> Tuple[Any, float]:
365
+ if os.environ.get("BLOBFILE_FORCE_GOOGLE_ANONYMOUS_AUTH", "0") == "1":
366
+ return (ANONYMOUS, ""), float("inf")
367
+
368
+ now = time.time()
369
+
370
+ # https://github.com/googleapis/google-auth-library-java/blob/master/README.md#application-default-credentials
371
+ creds = _load_credentials()
372
+ if len(creds) > 0:
373
+
374
+ def build_req() -> Request:
375
+ req = _create_access_token_request(
376
+ creds=creds, scopes=["https://www.googleapis.com/auth/devstorage.full_control"]
377
+ )
378
+ req.success_codes = (200, 400)
379
+ return req
380
+
381
+ resp = common.execute_request(conf, build_req)
382
+ result = json.loads(resp.data)
383
+ if resp.status == 400:
384
+ error = result["error"]
385
+ description = result.get("error_description", "<missing description>")
386
+ msg = f"Error with google credentials: [{error}] {description}"
387
+ if error == "invalid_grant":
388
+ if description.startswith("Invalid JWT:"):
389
+ msg += "\nPlease verify that your system clock is correct."
390
+ elif description == "Bad Request":
391
+ 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`"
392
+ raise Error(msg)
393
+ assert resp.status == 200
394
+ return (OAUTH_TOKEN, result["access_token"]), now + float(result["expires_in"])
395
+ elif os.environ.get("NO_GCE_CHECK", "false").lower() != "true" and _is_gce_instance():
396
+ # see if the metadata server has a token for us
397
+ def build_req() -> Request:
398
+ return Request(
399
+ method="GET",
400
+ url="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token",
401
+ headers={"Metadata-Flavor": "Google"},
402
+ )
403
+
404
+ resp = common.execute_request(conf, build_req)
405
+ result = json.loads(resp.data)
406
+ return (OAUTH_TOKEN, result["access_token"]), now + float(result["expires_in"])
407
+ else:
408
+ return (ANONYMOUS, ""), float("inf")
409
+
410
+
411
+ def execute_api_request(conf: Config, req: Request) -> "urllib3.BaseHTTPResponse":
412
+ def build_req() -> Request:
413
+ return create_api_request(req, auth=access_token_manager.get_token(conf, key=""))
414
+
415
+ return common.execute_request(conf, build_req)
416
+
417
+
418
+ class StreamingReadFile(BaseStreamingReadFile):
419
+ def __init__(self, conf: Config, path: str, size: Optional[int]) -> None:
420
+ if size is None:
421
+ st = maybe_stat(conf, path)
422
+ if st is None:
423
+ raise FileNotFoundError(f"No such file or bucket: '{path}'")
424
+ size = st.size
425
+ super().__init__(conf=conf, path=path, size=size)
426
+
427
+ def _request_chunk(
428
+ self, streaming: bool, start: int, end: Optional[int] = None
429
+ ) -> "urllib3.BaseHTTPResponse":
430
+ bucket, name = split_path(self._path)
431
+ req = Request(
432
+ url=build_url("/storage/v1/b/{bucket}/o/{name}", bucket=bucket, name=name),
433
+ method="GET",
434
+ params=dict(alt="media"),
435
+ headers={"Range": common.calc_range(start=start, end=end)},
436
+ success_codes=(206, 416),
437
+ # if we are streaming the data, make
438
+ # sure we don't preload it
439
+ preload_content=not streaming,
440
+ )
441
+ return execute_api_request(self._conf, req)
442
+
443
+
444
+ class StreamingWriteFile(BaseStreamingWriteFile):
445
+ def __init__(self, conf: Config, path: str) -> None:
446
+ bucket, name = split_path(path)
447
+ req = Request(
448
+ url=build_url("/upload/storage/v1/b/{bucket}/o?uploadType=resumable", bucket=bucket),
449
+ method="POST",
450
+ data=dict(name=name),
451
+ success_codes=(200, 400, 404),
452
+ )
453
+ resp = execute_api_request(conf, req)
454
+ if resp.status in (400, 404):
455
+ raise FileNotFoundError(f"No such file or bucket: '{path}'")
456
+ self._upload_url = resp.headers["Location"]
457
+ # https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload
458
+ assert conf.google_write_chunk_size % (256 * 1024) == 0
459
+ super().__init__(conf=conf, chunk_size=conf.google_write_chunk_size)
460
+
461
+ def _upload_chunk(self, chunk: memoryview, finalize: bool) -> None:
462
+ offset = self._offset
463
+
464
+ if len(chunk) == 0 and finalize:
465
+ self._upload_piece(offset, chunk, finalize)
466
+ return
467
+
468
+ start = 0
469
+ while start < len(chunk):
470
+ end = start + self._conf.google_write_chunk_size
471
+ last_piece = end >= len(chunk)
472
+ piece = chunk[start:end]
473
+ self._upload_piece(offset, piece, finalize and last_piece)
474
+ start = end
475
+ offset += len(piece)
476
+
477
+ def _upload_piece(self, offset: int, piece: memoryview, finalize: bool) -> None:
478
+ start = offset
479
+ end = offset + len(piece) - 1
480
+
481
+ total_size = "*"
482
+ if finalize:
483
+ total_size = offset + len(piece)
484
+
485
+ headers = {
486
+ "Content-Type": "application/octet-stream",
487
+ "Content-Range": f"bytes {start}-{end}/{total_size}",
488
+ }
489
+ if len(piece) == 0 and finalize:
490
+ # this is not mentioned in the docs but appears to be allowed
491
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
492
+ headers["Content-Range"] = f"bytes */{total_size}"
493
+
494
+ req = Request(
495
+ url=self._upload_url,
496
+ data=piece,
497
+ headers=headers,
498
+ method="PUT",
499
+ success_codes=(200, 201) if finalize else (308,),
500
+ )
501
+
502
+ try:
503
+ execute_api_request(self._conf, req)
504
+ except RequestFailure as e:
505
+ # https://cloud.google.com/storage/docs/resumable-uploads#practices
506
+ if e.response_status in (404, 410):
507
+ raise RestartableStreamingWriteFailure(
508
+ message=e.message,
509
+ request_string=e.request_string,
510
+ response_status=e.response_status,
511
+ error=e.error,
512
+ error_description=e.error_description,
513
+ )
514
+ else:
515
+ raise
516
+
517
+
518
+ def maybe_stat(conf: Config, path: str) -> Optional[Stat]:
519
+ bucket, blob = split_path(path)
520
+ if blob == "":
521
+ return None
522
+ req = Request(
523
+ url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob),
524
+ method="GET",
525
+ success_codes=(200, 404),
526
+ )
527
+ resp = execute_api_request(conf, req)
528
+ if resp.status != 200:
529
+ return None
530
+ return make_stat(json.loads(resp.data))
531
+
532
+
533
+ def remove(conf: Config, path: str) -> bool:
534
+ bucket, blob = split_path(path)
535
+ if blob == "":
536
+ raise FileNotFoundError(f"The system cannot find the path specified: '{path}'")
537
+ req = Request(
538
+ url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob),
539
+ method="DELETE",
540
+ success_codes=(204, 404),
541
+ )
542
+ resp = execute_api_request(conf, req)
543
+ return resp.status == 204
544
+
545
+
546
+ def maybe_update_md5(conf: Config, path: str, generation: str, hexdigest: str) -> bool:
547
+ bucket, blob = split_path(path)
548
+ req = Request(
549
+ url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob),
550
+ method="PATCH",
551
+ params=dict(ifGenerationMatch=generation),
552
+ # it looks like we can't set the underlying md5Hash, only the metadata fields
553
+ data=dict(metadata={"md5": hexdigest}),
554
+ success_codes=(200, 404, 412),
555
+ )
556
+
557
+ resp = execute_api_request(conf, req)
558
+ return resp.status == 200
559
+
560
+
561
+ def _upload_part(conf: Config, path: str, start: int, size: int, dst: str) -> str:
562
+ bucket, blob = split_path(dst)
563
+ req = Request(
564
+ url=build_url("/upload/storage/v1/b/{bucket}/o", bucket=bucket),
565
+ method="POST",
566
+ params=dict(uploadType="media", name=blob),
567
+ data=FileBody(path, start=start, end=start + size),
568
+ success_codes=(200,),
569
+ )
570
+ resp = execute_api_request(conf, req)
571
+ metadata = json.loads(resp.data)
572
+ return metadata["generation"]
573
+
574
+
575
+ def _delete_part(conf: Config, bucket: str, name: str) -> None:
576
+ req = Request(
577
+ url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=name),
578
+ method="DELETE",
579
+ success_codes=(204, 404),
580
+ )
581
+ execute_api_request(conf, req)
582
+
583
+
584
+ def parallel_upload(
585
+ conf: Config, executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool
586
+ ) -> Optional[str]:
587
+ with open(src, "rb") as f:
588
+ md5_digest = common.block_md5(f)
589
+
590
+ hexdigest = binascii.hexlify(md5_digest).decode("utf8")
591
+
592
+ s = os.stat(src)
593
+ if s.st_size == 0:
594
+ # write an empty file, the normal upload requires at least one part
595
+ with StreamingWriteFile(conf, dst) as f:
596
+ pass
597
+ return hexdigest if return_md5 else None
598
+
599
+ dstbucket, dstname = split_path(dst)
600
+ source_objects = []
601
+ object_names = []
602
+ max_workers = getattr(executor, "_max_workers", os.cpu_count() or 1)
603
+ part_size = max(math.ceil(s.st_size / max_workers), common.PARALLEL_COPY_MINIMUM_PART_SIZE)
604
+ i = 0
605
+ start = 0
606
+ futures = []
607
+ while start < s.st_size:
608
+ suffix = f".part.{i}"
609
+ future = executor.submit(
610
+ _upload_part, conf, src, start, min(part_size, s.st_size - start), dst + suffix
611
+ )
612
+ futures.append(future)
613
+ object_names.append(dstname + suffix)
614
+ i += 1
615
+ start += part_size
616
+ for name, future in zip(object_names, futures):
617
+ generation = future.result()
618
+ source_objects.append(
619
+ {
620
+ "name": name,
621
+ "generation": generation,
622
+ "objectPreconditions": {"ifGenerationMatch": generation},
623
+ }
624
+ )
625
+
626
+ req = Request(
627
+ url=build_url(
628
+ "/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose",
629
+ destinationBucket=dstbucket,
630
+ destinationObject=dstname,
631
+ ),
632
+ method="POST",
633
+ data={"sourceObjects": source_objects},
634
+ success_codes=(200,),
635
+ )
636
+ resp = execute_api_request(conf, req)
637
+ metadata = json.loads(resp.data)
638
+ maybe_update_md5(conf, dst, metadata["generation"], hexdigest)
639
+
640
+ # delete parts in parallel
641
+ delete_futures = []
642
+ for name in object_names:
643
+ future = executor.submit(_delete_part, conf, dstbucket, name)
644
+ delete_futures.append(future)
645
+ for future in delete_futures:
646
+ future.result()
647
+
648
+ return hexdigest if return_md5 else None
649
+
650
+
651
+ def _create_page_iterator(
652
+ conf: Config, url: str, method: str, params: Mapping[str, str]
653
+ ) -> Iterator[Dict[str, Any]]:
654
+ p = dict(params).copy()
655
+
656
+ while True:
657
+ req = Request(url=url, method=method, params=p, success_codes=(200, 404))
658
+ resp = execute_api_request(conf, req)
659
+ if resp.status == 404:
660
+ return
661
+ result = json.loads(resp.data)
662
+ yield result
663
+ if "nextPageToken" not in result:
664
+ break
665
+ p["pageToken"] = result["nextPageToken"]
666
+
667
+
668
+ def list_blobs(conf: Config, path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]:
669
+ params = {}
670
+ if delimiter is not None:
671
+ params["delimiter"] = delimiter
672
+
673
+ bucket, prefix = split_path(path)
674
+ it = _create_page_iterator(
675
+ conf=conf,
676
+ url=build_url("/storage/v1/b/{bucket}/o", bucket=bucket),
677
+ method="GET",
678
+ params=dict(prefix=prefix, **params),
679
+ )
680
+ for result in it:
681
+ yield from _get_entries(bucket, result)
682
+
683
+
684
+ def _get_entries(bucket: str, result: Mapping[str, Any]) -> Iterator[DirEntry]:
685
+ if "prefixes" in result:
686
+ for p in result["prefixes"]:
687
+ path = combine_path(bucket, p)
688
+ yield entry_from_dirpath(path)
689
+ if "items" in result:
690
+ for item in result["items"]:
691
+ path = combine_path(bucket, item["name"])
692
+ if item["name"].endswith("/"):
693
+ yield entry_from_dirpath(path)
694
+ else:
695
+ yield entry_from_path_stat(path, make_stat(item))
696
+
697
+
698
+ def entry_from_dirpath(path: str) -> DirEntry:
699
+ if path.endswith("/"):
700
+ path = path[:-1]
701
+ _, obj = split_path(path)
702
+ name = obj.split("/")[-1]
703
+ return DirEntry(name=name, path=path, is_dir=True, is_file=False, stat=None)
704
+
705
+
706
+ def entry_from_path_stat(path: str, stat: Stat) -> DirEntry:
707
+ assert not path.endswith("/")
708
+ _, obj = split_path(path)
709
+ name = obj.split("/")[-1]
710
+ return DirEntry(name=name, path=path, is_dir=False, is_file=True, stat=stat)
711
+
712
+
713
+ def get_url(conf: Config, path: str) -> Tuple[str, Optional[float]]:
714
+ bucket, blob = split_path(path)
715
+ return generate_signed_url(bucket, blob, expiration=MAX_EXPIRATION)
716
+
717
+
718
+ def set_mtime(conf: Config, path: str, mtime: float, version: Optional[str] = None) -> bool:
719
+ bucket, blob = split_path(path)
720
+ params = None
721
+ if version is not None:
722
+ params = dict(ifGenerationMatch=version)
723
+ req = Request(
724
+ url=build_url("/storage/v1/b/{bucket}/o/{object}", bucket=bucket, object=blob),
725
+ method="PATCH",
726
+ params=params,
727
+ data=dict(metadata={"blobfile-mtime": str(mtime)}),
728
+ success_codes=(200, 404, 412),
729
+ )
730
+ resp = execute_api_request(conf, req)
731
+ if resp.status == 404:
732
+ raise FileNotFoundError(f"No such file: '{path}'")
733
+ return resp.status == 200
734
+
735
+
736
+ def dirname(conf: Config, path: str) -> str:
737
+ bucket, obj = split_path(path)
738
+ obj = strip_slashes(obj)
739
+ if "/" in obj:
740
+ obj = "/".join(obj.split("/")[:-1])
741
+ return combine_path(bucket, obj)
742
+ else:
743
+ return combine_path(bucket, "")[:-1]
744
+
745
+
746
+ def remote_copy(conf: Config, src: str, dst: str, return_md5: bool) -> Optional[str]:
747
+ srcbucket, srcname = split_path(src)
748
+ dstbucket, dstname = split_path(dst)
749
+ params = {}
750
+ while True:
751
+ req = Request(
752
+ url=build_url(
753
+ "/storage/v1/b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}",
754
+ sourceBucket=srcbucket,
755
+ sourceObject=srcname,
756
+ destinationBucket=dstbucket,
757
+ destinationObject=dstname,
758
+ ),
759
+ method="POST",
760
+ params=params,
761
+ success_codes=(200, 404),
762
+ )
763
+ resp = execute_api_request(conf, req)
764
+ if resp.status == 404:
765
+ raise FileNotFoundError(f"Source file not found: '{src}'")
766
+ result = json.loads(resp.data)
767
+ if result["done"]:
768
+ if return_md5:
769
+ return get_md5(result["resource"])
770
+ else:
771
+ return
772
+ params["rewriteToken"] = result["rewriteToken"]
773
+
774
+
775
+ def join_paths(conf: Config, a: str, b: str) -> str:
776
+ if not a.endswith("/"):
777
+ a += "/"
778
+
779
+ bucket, obj = split_path(a)
780
+ obj = path_join(obj, b)
781
+ if obj.startswith("/"):
782
+ obj = obj[1:]
783
+ return combine_path(bucket, obj)
784
+
785
+
786
+ access_token_manager = TokenManager(_get_access_token, "gcp")
videollama2/lib/python3.10/site-packages/blobfile/_ops.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime
2
+ from __future__ import annotations
3
+
4
+ import concurrent.futures
5
+ from typing import (
6
+ BinaryIO,
7
+ Callable,
8
+ Iterator,
9
+ Literal,
10
+ Optional,
11
+ Sequence,
12
+ TextIO,
13
+ Tuple,
14
+ overload,
15
+ )
16
+
17
+ import urllib3
18
+
19
+ from blobfile._common import DirEntry, RemoteOrLocalPath, Stat
20
+ from blobfile._context import (
21
+ DEFAULT_AZURE_WRITE_CHUNK_SIZE,
22
+ DEFAULT_BUFFER_SIZE,
23
+ DEFAULT_CONNECT_TIMEOUT,
24
+ DEFAULT_CONNECTION_POOL_MAX_SIZE,
25
+ DEFAULT_GOOGLE_WRITE_CHUNK_SIZE,
26
+ DEFAULT_MAX_CONNECTION_POOL_COUNT,
27
+ DEFAULT_READ_TIMEOUT,
28
+ DEFAULT_RETRY_COMMON_LOG_THRESHOLD,
29
+ DEFAULT_RETRY_LOG_THRESHOLD,
30
+ create_context,
31
+ default_log_fn,
32
+ )
33
+
34
+ default_context = create_context()
35
+
36
+
37
+ def configure(
38
+ *,
39
+ log_callback: Callable[[str], None] = default_log_fn,
40
+ connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE,
41
+ max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT,
42
+ # https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs
43
+ # the chunk size determines the maximum size of an individual blob
44
+ azure_write_chunk_size: int = DEFAULT_AZURE_WRITE_CHUNK_SIZE,
45
+ google_write_chunk_size: int = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE,
46
+ retry_log_threshold: int = DEFAULT_RETRY_LOG_THRESHOLD,
47
+ retry_common_log_threshold: int = DEFAULT_RETRY_COMMON_LOG_THRESHOLD,
48
+ retry_limit: Optional[int] = None,
49
+ connect_timeout: Optional[int] = DEFAULT_CONNECT_TIMEOUT,
50
+ read_timeout: Optional[int] = DEFAULT_READ_TIMEOUT,
51
+ output_az_paths: bool = True,
52
+ use_azure_storage_account_key_fallback: bool = False,
53
+ get_http_pool: Optional[Callable[[], urllib3.PoolManager]] = None,
54
+ use_streaming_read: bool = False,
55
+ default_buffer_size: int = DEFAULT_BUFFER_SIZE,
56
+ save_access_token_to_disk: bool = True,
57
+ multiprocessing_start_method: str = "spawn",
58
+ ) -> None:
59
+ """
60
+ log_callback: a log callback function `log(msg: string)` to use instead of printing to stdout
61
+ connection_pool_max_size: the max size for each per-host connection pool
62
+ max_connection_pool_count: the maximum count of per-host connection pools
63
+ azure_write_chunk_size: the size of blocks to write to Azure Storage blobs, can be set to a maximum of 100MB
64
+ 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
65
+ retry_log_threshold: set a retry count threshold above which to log failures to the log callback function
66
+ 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
67
+ 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
68
+ output_az_paths: output `az://` paths instead of using the `https://` for azure
69
+ 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
70
+ get_http_pool: a function that returns a `urllib3.PoolManager` to be used for requests
71
+ 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)
72
+ default_buffer_size: the default buffer size to use for reading files (and writing local files)
73
+ 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).
74
+ multiprocessing_start_method: the start method to use when creating processes for parallel work
75
+ """
76
+ global default_context
77
+ default_context = create_context(
78
+ log_callback=log_callback,
79
+ connection_pool_max_size=connection_pool_max_size,
80
+ max_connection_pool_count=max_connection_pool_count,
81
+ azure_write_chunk_size=azure_write_chunk_size,
82
+ retry_log_threshold=retry_log_threshold,
83
+ retry_common_log_threshold=retry_common_log_threshold,
84
+ retry_limit=retry_limit,
85
+ google_write_chunk_size=google_write_chunk_size,
86
+ connect_timeout=connect_timeout,
87
+ read_timeout=read_timeout,
88
+ output_az_paths=output_az_paths,
89
+ use_azure_storage_account_key_fallback=use_azure_storage_account_key_fallback,
90
+ get_http_pool=get_http_pool,
91
+ use_streaming_read=use_streaming_read,
92
+ default_buffer_size=default_buffer_size,
93
+ save_access_token_to_disk=save_access_token_to_disk,
94
+ multiprocessing_start_method=multiprocessing_start_method,
95
+ )
96
+
97
+
98
+ def copy(
99
+ src: RemoteOrLocalPath,
100
+ dst: RemoteOrLocalPath,
101
+ overwrite: bool = False,
102
+ parallel: bool = False,
103
+ parallel_executor: Optional[concurrent.futures.Executor] = None,
104
+ return_md5: bool = False,
105
+ dst_version: Optional[str] = None,
106
+ ) -> Optional[str]:
107
+ """
108
+ Copy a file from one path to another
109
+
110
+ If both paths are on the same blob storage, this will perform a remote copy operation without downloading
111
+ the contents locally.
112
+
113
+ If `overwrite` is `False` (the default), an exception will be raised if the destination
114
+ path exists.
115
+
116
+ 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`.
117
+
118
+ 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()`.
119
+
120
+ If `return_md5` is set to `True`, an md5 will be calculated during the copy and returned if available,
121
+ or else None will be returned.
122
+
123
+ 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()`)
124
+ """
125
+ return default_context.copy(
126
+ src=src,
127
+ dst=dst,
128
+ overwrite=overwrite,
129
+ parallel=parallel,
130
+ parallel_executor=parallel_executor,
131
+ return_md5=return_md5,
132
+ dst_version=dst_version,
133
+ )
134
+
135
+
136
+ def exists(path: RemoteOrLocalPath) -> bool:
137
+ """
138
+ Return true if that path exists (either as a file or a directory)
139
+ """
140
+ return default_context.exists(path=path)
141
+
142
+
143
+ def basename(path: RemoteOrLocalPath) -> str:
144
+ """
145
+ Get the filename component of the path
146
+
147
+ For GCS, this is the part after the bucket
148
+ """
149
+ return default_context.basename(path=path)
150
+
151
+
152
+ def glob(pattern: str, parallel: bool = False) -> Iterator[str]:
153
+ """
154
+ Find files and directories matching a pattern. Supports * and **
155
+
156
+ For local paths, this function uses glob.glob() which has special handling for * and **
157
+ 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.
158
+
159
+ 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.
160
+
161
+ You can set `parallel=True` to use multiple processes to perform the glob. It's likely
162
+ that the results will no longer be in order.
163
+ """
164
+ return default_context.glob(pattern=pattern, parallel=parallel)
165
+
166
+
167
+ def scanglob(
168
+ pattern: str, parallel: bool = False, shard_prefix_length: int = 0
169
+ ) -> Iterator[DirEntry]:
170
+ """
171
+ Same as `glob`, but returns `DirEntry` objects instead of strings
172
+ """
173
+ return default_context.scanglob(
174
+ pattern=pattern, parallel=parallel, shard_prefix_length=shard_prefix_length
175
+ )
176
+
177
+
178
+ def isdir(path: RemoteOrLocalPath) -> bool:
179
+ """
180
+ Return true if a path is an existing directory
181
+ """
182
+ return default_context.isdir(path=path)
183
+
184
+
185
+ def listdir(path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[str]:
186
+ """
187
+ Returns an iterator of the contents of the directory at `path`
188
+
189
+ If your filenames are uniformly distributed (like hashes) then you can use `shard_prefix_length`
190
+ to query them more quickly. `shard_prefix_length` will do multiple queries in parallel,
191
+ querying each possible prefix independently.
192
+
193
+ Using `shard_prefix_length` will only consider prefixes that are not unusual characters
194
+ (mostly these are ascii values < 0x20) some of these could technically show up in a path.
195
+ """
196
+ return default_context.listdir(path=path, shard_prefix_length=shard_prefix_length)
197
+
198
+
199
+ def scandir(path: RemoteOrLocalPath, shard_prefix_length: int = 0) -> Iterator[DirEntry]:
200
+ """
201
+ Same as `listdir`, but returns `DirEntry` objects instead of strings
202
+ """
203
+ return default_context.scandir(path=path, shard_prefix_length=shard_prefix_length)
204
+
205
+
206
+ def makedirs(path: RemoteOrLocalPath) -> None:
207
+ """
208
+ Make any directories necessary to ensure that path is a directory
209
+ """
210
+ return default_context.makedirs(path=path)
211
+
212
+
213
+ def remove(path: RemoteOrLocalPath) -> None:
214
+ """
215
+ Remove a file at the given path
216
+ """
217
+ return default_context.remove(path=path)
218
+
219
+
220
+ def rmdir(path: RemoteOrLocalPath) -> None:
221
+ """
222
+ Remove an empty directory at the given path
223
+ """
224
+ return default_context.rmdir(path=path)
225
+
226
+
227
+ def stat(path: RemoteOrLocalPath) -> Stat:
228
+ """
229
+ Stat a file or object representing a directory, returns a Stat object
230
+ """
231
+ return default_context.stat(path=path)
232
+
233
+
234
+ def set_mtime(path: RemoteOrLocalPath, mtime: float, version: Optional[str] = None) -> bool:
235
+ """
236
+ Set the mtime for a path, returns True on success
237
+
238
+ A version can be specified (as returned by `stat()`) to only update the mtime if the
239
+ version matches
240
+ """
241
+ return default_context.set_mtime(path=path, mtime=mtime, version=version)
242
+
243
+
244
+ def rmtree(
245
+ path: RemoteOrLocalPath,
246
+ parallel: bool = False,
247
+ parallel_executor: Optional[concurrent.futures.Executor] = None,
248
+ ) -> None:
249
+ """
250
+ Delete a directory tree
251
+ """
252
+ return default_context.rmtree(path=path, parallel=parallel, parallel_executor=parallel_executor)
253
+
254
+
255
+ def walk(
256
+ top: RemoteOrLocalPath,
257
+ topdown: bool = True,
258
+ onerror: Optional[Callable[[OSError], None]] = None,
259
+ ) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]:
260
+ """
261
+ Walk a directory tree in a similar manner to os.walk
262
+ """
263
+ return default_context.walk(top=top, topdown=topdown, onerror=onerror)
264
+
265
+
266
+ def dirname(path: RemoteOrLocalPath) -> str:
267
+ """
268
+ Get the directory name of the path
269
+
270
+ On GCS, the root directory is gs://<bucket name>/
271
+ On Azure Storage, the root directory is https://<account>.blob.core.windows.net/<container>/
272
+ """
273
+ return default_context.dirname(path=path)
274
+
275
+
276
+ def join(a: RemoteOrLocalPath, *args: str) -> str:
277
+ """
278
+ Join file paths, if a path is an absolute path, it will replace the entire path component of previous paths
279
+ """
280
+ return default_context.join(a, *args)
281
+
282
+
283
+ def get_url(path: RemoteOrLocalPath) -> Tuple[str, Optional[float]]:
284
+ """
285
+ Get a URL for the given path that a browser could open
286
+ """
287
+ return default_context.get_url(path=path)
288
+
289
+
290
+ def md5(path: RemoteOrLocalPath) -> str:
291
+ """
292
+ Get the MD5 hash for a file in hexdigest format.
293
+
294
+ For GCS this will look up the MD5 in the blob's metadata, unless it's a composite object, in which case
295
+ it must be calculated by downloading the file.
296
+ For Azure this can look up the MD5 if it's available, otherwise it must calculate it.
297
+ For local paths, this must always calculate the MD5.
298
+ """
299
+ return default_context.md5(path=path)
300
+
301
+
302
+ def last_version_seen(file: TextIO | BinaryIO) -> Optional[str]:
303
+ """
304
+ Get the last seen version of a file opened with `BlobFile`
305
+ """
306
+ return default_context.last_version_seen(file=file)
307
+
308
+
309
+ def read_text(path: RemoteOrLocalPath) -> str:
310
+ """
311
+ Read the contents of a file as text
312
+ """
313
+ return default_context.read_text(path=path)
314
+
315
+
316
+ def read_bytes(path: RemoteOrLocalPath) -> bytes:
317
+ """
318
+ Read the contents of a file as bytes
319
+ """
320
+ return default_context.read_bytes(path=path)
321
+
322
+
323
+ def write_text(path: RemoteOrLocalPath, text: str) -> None:
324
+ """
325
+ Write text to a file
326
+ """
327
+ return default_context.write_text(path=path, text=text)
328
+
329
+
330
+ def write_bytes(path: RemoteOrLocalPath, data: bytes) -> None:
331
+ """
332
+ Write bytes to a file
333
+ """
334
+ return default_context.write_bytes(path=path, data=data)
335
+
336
+
337
+ @overload
338
+ def BlobFile(
339
+ path: RemoteOrLocalPath,
340
+ mode: Literal["rb", "wb", "ab"],
341
+ streaming: Optional[bool] = ...,
342
+ buffer_size: int = ...,
343
+ cache_dir: Optional[str] = ...,
344
+ file_size: Optional[int] = None,
345
+ version: Optional[str] = None,
346
+ ) -> BinaryIO:
347
+ ...
348
+
349
+
350
+ @overload
351
+ def BlobFile(
352
+ path: RemoteOrLocalPath,
353
+ mode: Literal["r", "w", "a"] = ...,
354
+ streaming: Optional[bool] = ...,
355
+ buffer_size: int = ...,
356
+ cache_dir: Optional[str] = ...,
357
+ file_size: Optional[int] = None,
358
+ version: Optional[str] = None,
359
+ ) -> TextIO:
360
+ ...
361
+
362
+
363
+ def BlobFile(
364
+ path: RemoteOrLocalPath,
365
+ mode: Literal["r", "rb", "w", "wb", "a", "ab"] = "r",
366
+ streaming: Optional[bool] = None,
367
+ buffer_size: Optional[int] = None,
368
+ cache_dir: Optional[str] = None,
369
+ file_size: Optional[int] = None,
370
+ version: Optional[str] = None,
371
+ ):
372
+ """
373
+ Open a local or remote file for reading or writing
374
+
375
+ Args:
376
+ path local or remote path
377
+ mode: one of "r", "rb", "w", "wb", "a", "ab" indicating the mode to open the file in
378
+ streaming: the default for `streaming` is `True` when `mode` is in `"r", "rb"` and `False` when `mode` is in `"w", "wb", "a", "ab"`.
379
+ * `streaming=True`:
380
+ * Reading is done without downloading the entire remote file.
381
+ * 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.
382
+ * Appending is not implemented.
383
+ * `streaming=False`:
384
+ * Reading is done by downloading the remote file to a local file during the constructor.
385
+ * Writing is done by uploading the file on `close()` or during destruction.
386
+ * Appending is done by downloading the file during construction and uploading on `close()` or during destruction.
387
+ buffer_size: number of bytes to buffer, this can potentially make reading more efficient.
388
+ 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.
389
+
390
+ Returns:
391
+ A file-like object
392
+ """
393
+ return default_context.BlobFile(
394
+ path=path,
395
+ mode=mode,
396
+ streaming=streaming,
397
+ buffer_size=buffer_size,
398
+ cache_dir=cache_dir,
399
+ file_size=file_size,
400
+ version=version,
401
+ )
videollama2/lib/python3.10/site-packages/blobfile/_ops_test.py ADDED
@@ -0,0 +1,1675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/tensorflow/tensorflow/issues/27023
2
+ import datetime
3
+ import warnings
4
+
5
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
6
+ warnings.filterwarnings("ignore", category=FutureWarning)
7
+
8
+ import random
9
+ import string
10
+ import tempfile
11
+ import os
12
+ import contextlib
13
+ import json
14
+ import urllib.request
15
+ import hashlib
16
+ import time
17
+ import subprocess as sp
18
+ import multiprocessing as mp
19
+ import platform
20
+ import pickle
21
+ import zipfile
22
+ import re
23
+ import unittest.mock
24
+
25
+ import pytest
26
+ import numpy as np
27
+
28
+ import blobfile as bf
29
+ from blobfile import _ops as ops, _azure as azure, _common as common
30
+
31
+ GCS_TEST_BUCKET = os.getenv("GCS_TEST_BUCKET", "csh-test-3")
32
+ AS_TEST_ACCOUNT = os.getenv("AS_TEST_ACCOUNT", "cshteststorage2")
33
+ AS_TEST_ACCOUNT2 = os.getenv("AS_TEST_ACCOUNT2", "cshteststorage3")
34
+ AS_TEST_CONTAINER = os.getenv("AS_TEST_CONTAINER", "testcontainer2")
35
+ AS_TEST_CONTAINER2 = os.getenv("AS_TEST_CONTAINER2", "testcontainer3")
36
+ AS_INVALID_ACCOUNT = f"{AS_TEST_ACCOUNT}-does-not-exist"
37
+ AS_EXTERNAL_ACCOUNT = "cshteststorage4"
38
+
39
+ AZURE_VALID_CONTAINER = f"az://{AS_TEST_ACCOUNT}/{AS_TEST_CONTAINER}"
40
+ AZURE_INVALID_CONTAINER = f"az://{AS_TEST_ACCOUNT}/{AS_TEST_CONTAINER}-does-not-exist"
41
+ AZURE_INVALID_CONTAINER_NO_ACCOUNT = f"az://{AS_INVALID_ACCOUNT}/{AS_TEST_CONTAINER}"
42
+ GCS_VALID_BUCKET = f"gs://{GCS_TEST_BUCKET}"
43
+ GCS_INVALID_BUCKET = f"gs://{GCS_TEST_BUCKET}-does-not-exist"
44
+
45
+ AZURE_PUBLIC_URL = (
46
+ f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png"
47
+ )
48
+ AZURE_PUBLIC_URL_HEADER = b"\x89PNG"
49
+
50
+
51
+ @pytest.fixture(scope="session", autouse=True)
52
+ def setup_gcloud_auth():
53
+ # only run this for our docker tests, this tells gcloud to use the credentials supplied by the
54
+ # test running script
55
+ if platform.system() == "Linux" and "GOOGLE_APPLICATION_CREDENTIALS" in os.environ:
56
+ sp.run(
57
+ [
58
+ "gcloud",
59
+ "auth",
60
+ "activate-service-account",
61
+ f"--key-file={os.environ['GOOGLE_APPLICATION_CREDENTIALS']}",
62
+ ]
63
+ )
64
+ yield
65
+
66
+
67
+ @contextlib.contextmanager
68
+ def chdir(path):
69
+ original_path = os.getcwd()
70
+ os.chdir(path)
71
+ yield
72
+ os.chdir(original_path)
73
+
74
+
75
+ @contextlib.contextmanager
76
+ def _get_temp_local_path():
77
+ with tempfile.TemporaryDirectory() as tmpdir:
78
+ assert isinstance(tmpdir, str)
79
+ path = os.path.join(tmpdir, "file.name")
80
+ yield path
81
+
82
+
83
+ @contextlib.contextmanager
84
+ def _get_temp_gcs_path():
85
+ try:
86
+ from tensorflow.io import gfile
87
+ except ImportError:
88
+ pytest.skip("tensorflow not installed")
89
+
90
+ path = f"gs://{GCS_TEST_BUCKET}/" + "".join(
91
+ random.choice(string.ascii_lowercase) for i in range(16)
92
+ )
93
+ gfile.mkdir(path)
94
+ yield path + "/file.name"
95
+ gfile.rmtree(path)
96
+
97
+
98
+ @contextlib.contextmanager
99
+ def _get_temp_as_path(account=AS_TEST_ACCOUNT, container=AS_TEST_CONTAINER):
100
+ random_id = "".join(random.choice(string.ascii_lowercase) for i in range(16))
101
+ path = f"https://{account}.blob.core.windows.net/{container}/" + random_id
102
+ yield path + "/file.name"
103
+ cmd = [
104
+ "az",
105
+ "storage",
106
+ "blob",
107
+ "delete-batch",
108
+ "--account-name",
109
+ account,
110
+ "--source",
111
+ container,
112
+ "--pattern",
113
+ f"{random_id}/*",
114
+ "--auth-mode",
115
+ "login",
116
+ ]
117
+ sp.run(cmd, check=True, shell=platform.system() == "Windows", timeout=30)
118
+
119
+
120
+ def _write_contents(path, contents):
121
+ if ".blob.core.windows.net" in path or path.startswith("az://"):
122
+ with tempfile.TemporaryDirectory() as tmpdir:
123
+ assert isinstance(tmpdir, str)
124
+ account, container, blob = azure.split_path(path)
125
+ filepath = os.path.join(tmpdir, "tmp")
126
+ with open(filepath, "wb") as f:
127
+ f.write(contents)
128
+ cmd = [
129
+ "az",
130
+ "storage",
131
+ "blob",
132
+ "upload",
133
+ "--overwrite",
134
+ "--account-name",
135
+ account,
136
+ "--container-name",
137
+ container,
138
+ "--name",
139
+ blob,
140
+ "--file",
141
+ filepath,
142
+ "--auth-mode",
143
+ "login",
144
+ ]
145
+ sp.run(
146
+ cmd,
147
+ check=True,
148
+ shell=platform.system() == "Windows",
149
+ stdout=sp.DEVNULL,
150
+ stderr=sp.DEVNULL,
151
+ timeout=30,
152
+ )
153
+ else:
154
+ try:
155
+ from tensorflow.io import gfile
156
+ except ImportError:
157
+ pytest.skip("tensorflow not installed")
158
+
159
+ with gfile.GFile(path, "wb") as f:
160
+ f.write(contents)
161
+
162
+
163
+ def _read_contents(path):
164
+ if ".blob.core.windows.net" in path:
165
+ with tempfile.TemporaryDirectory() as tmpdir:
166
+ assert isinstance(tmpdir, str)
167
+ account, container, blob = azure.split_path(path)
168
+ filepath = os.path.join(tmpdir, "tmp")
169
+ cmd = [
170
+ "az",
171
+ "storage",
172
+ "blob",
173
+ "download",
174
+ "--account-name",
175
+ account,
176
+ "--container-name",
177
+ container,
178
+ "--name",
179
+ blob,
180
+ "--file",
181
+ filepath,
182
+ "--auth-mode",
183
+ "login",
184
+ ]
185
+ sp.run(
186
+ cmd,
187
+ check=True,
188
+ shell=platform.system() == "Windows",
189
+ stdout=sp.DEVNULL,
190
+ stderr=sp.DEVNULL,
191
+ timeout=30,
192
+ )
193
+ with open(filepath, "rb") as f:
194
+ return f.read()
195
+ else:
196
+ from tensorflow.io import gfile
197
+
198
+ with gfile.GFile(path, "rb") as f:
199
+ return f.read()
200
+
201
+
202
+ def test_basename():
203
+ testcases = [
204
+ ("/", ""),
205
+ ("a/", ""),
206
+ ("a", "a"),
207
+ ("a/b", "b"),
208
+ ("", ""),
209
+ ("gs://a", ""),
210
+ ("gs://a/", ""),
211
+ ("gs://a/b/", ""),
212
+ ("gs://a/b", "b"),
213
+ ("gs://a/b/c/test.filename", "test.filename"),
214
+ ("https://a.blob.core.windows.net/b", ""),
215
+ ("https://a.blob.core.windows.net/b/", ""),
216
+ ("https://a.blob.core.windows.net/b/c/", ""),
217
+ ("https://a.blob.core.windows.net/b/c", "c"),
218
+ ("https://a.blob.core.windows.net/b/c/test.filename", "test.filename"),
219
+ ]
220
+ for input_, desired_output in testcases:
221
+ actual_output = bf.basename(input_)
222
+ assert desired_output == actual_output
223
+
224
+
225
+ def test_dirname():
226
+ b = bf.create_context(output_az_paths=False)
227
+ testcases = [
228
+ ("a", ""),
229
+ ("a/b", "a"),
230
+ ("a/b/c", "a/b"),
231
+ ("a/b/c/", "a/b/c"),
232
+ ("a/b/c/////", "a/b/c"),
233
+ ("", ""),
234
+ ("gs://a", "gs://a"),
235
+ ("gs://a/", "gs://a"),
236
+ ("gs://a/////", "gs://a"),
237
+ ("gs://a/b", "gs://a"),
238
+ ("gs://a/b/c/test.filename", "gs://a/b/c"),
239
+ ("gs://a/b/c/", "gs://a/b"),
240
+ ("gs://a/b/c/////", "gs://a/b"),
241
+ ("https://a.blob.core.windows.net/container", "https://a.blob.core.windows.net/container"),
242
+ ("https://a.blob.core.windows.net/container/", "https://a.blob.core.windows.net/container"),
243
+ (
244
+ "https://a.blob.core.windows.net/container/////",
245
+ "https://a.blob.core.windows.net/container",
246
+ ),
247
+ (
248
+ "https://a.blob.core.windows.net/container/b",
249
+ "https://a.blob.core.windows.net/container",
250
+ ),
251
+ (
252
+ "https://a.blob.core.windows.net/container/b/c/test.filename",
253
+ "https://a.blob.core.windows.net/container/b/c",
254
+ ),
255
+ (
256
+ "https://a.blob.core.windows.net/container/b/c/",
257
+ "https://a.blob.core.windows.net/container/b",
258
+ ),
259
+ (
260
+ "https://a.blob.core.windows.net/container/b/c//////",
261
+ "https://a.blob.core.windows.net/container/b",
262
+ ),
263
+ ]
264
+ for input_, desired_output in testcases:
265
+ actual_output = b.dirname(input_)
266
+ assert desired_output == actual_output, f"{input_}"
267
+
268
+
269
+ def test_join():
270
+ b = bf.create_context(output_az_paths=False)
271
+ testcases = [
272
+ ("a", "b", "a/b"),
273
+ ("a/b", "c", "a/b/c"),
274
+ ("a/b/", "c", "a/b/c"),
275
+ ("a/b/", "c/", "a/b/c/"),
276
+ ("a/b/", "/c/", "/c/"),
277
+ ("", "", ""),
278
+ ("gs://a/b/c", "d0123456789-._~!$&'()*+,:=@;", "gs://a/b/c/d0123456789-._~!$&'()*+,:=@;"),
279
+ ("gs://a", "b", "gs://a/b"),
280
+ ("gs://a/b", "c", "gs://a/b/c"),
281
+ ("gs://a/b/", "c", "gs://a/b/c"),
282
+ ("gs://a/b/", "c/", "gs://a/b/c/"),
283
+ ("gs://a/b/", "/c/", "gs://a/c/"),
284
+ ("gs://a/b/", "../c", "gs://a/c"),
285
+ ("gs://a/b/", "../c/", "gs://a/c/"),
286
+ ("gs://a/b/", "../../c/", "gs://a/c/"),
287
+ (
288
+ "https://a.blob.core.windows.net/container",
289
+ "b",
290
+ "https://a.blob.core.windows.net/container/b",
291
+ ),
292
+ (
293
+ "https://a.blob.core.windows.net/container/b",
294
+ "c",
295
+ "https://a.blob.core.windows.net/container/b/c",
296
+ ),
297
+ (
298
+ "https://a.blob.core.windows.net/container/b/",
299
+ "c",
300
+ "https://a.blob.core.windows.net/container/b/c",
301
+ ),
302
+ (
303
+ "https://a.blob.core.windows.net/container/b/",
304
+ "c/",
305
+ "https://a.blob.core.windows.net/container/b/c/",
306
+ ),
307
+ (
308
+ "https://a.blob.core.windows.net/container/b/",
309
+ "/c/",
310
+ "https://a.blob.core.windows.net/container/c/",
311
+ ),
312
+ (
313
+ "https://a.blob.core.windows.net/container/b/",
314
+ "../c",
315
+ "https://a.blob.core.windows.net/container/c",
316
+ ),
317
+ (
318
+ "https://a.blob.core.windows.net/container/b/",
319
+ "../c/",
320
+ "https://a.blob.core.windows.net/container/c/",
321
+ ),
322
+ (
323
+ "https://a.blob.core.windows.net/container/b/",
324
+ "../../c/",
325
+ "https://a.blob.core.windows.net/container/c/",
326
+ ),
327
+ ("gs://test/a/b", "c:d", "gs://test/a/b/c:d"),
328
+ ("gs://test/a/b", "c:d;", "gs://test/a/b/c:d;"),
329
+ ]
330
+ for input_a, input_b, desired_output in testcases:
331
+ actual_output = b.join(input_a, input_b)
332
+ assert desired_output == actual_output, f"{input_a} {input_b}"
333
+ # also make sure az:// urls work
334
+ if "blob.core.windows.net" in input_a:
335
+ az_input_a = _convert_https_to_az(input_a)
336
+ actual_output = b.join(az_input_a, input_b)
337
+ assert desired_output == actual_output, f"{az_input_a} {input_b}"
338
+
339
+
340
+ def _convert_https_to_az(path):
341
+ return path.replace("https://", "az://").replace(".blob.core.windows.net", "")
342
+
343
+
344
+ def _convert_az_to_https(path):
345
+ return re.sub(r"^az://(.*?)/", r"https://\1.blob.core.windows.net/", path)
346
+
347
+
348
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
349
+ def test_get_url(ctx):
350
+ contents = b"meow!"
351
+ with ctx() as path:
352
+ _write_contents(path, contents)
353
+ url, _ = bf.get_url(path)
354
+ assert urllib.request.urlopen(url).read() == contents
355
+
356
+
357
+ def test_azure_public_get_url():
358
+ contents = urllib.request.urlopen(AZURE_PUBLIC_URL).read()
359
+ assert contents.startswith(AZURE_PUBLIC_URL_HEADER)
360
+ url, _ = bf.get_url(AZURE_PUBLIC_URL)
361
+ assert urllib.request.urlopen(url).read() == contents
362
+
363
+
364
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
365
+ @pytest.mark.parametrize("streaming", [True, False])
366
+ def test_read_write(ctx, streaming):
367
+ contents = b"meow!\npurr\n"
368
+ with ctx() as path:
369
+ path = bf.join(path, "a folder", "a.file")
370
+ bf.makedirs(bf.dirname(path))
371
+ with bf.BlobFile(path, "wb", streaming=streaming) as w:
372
+ w.write(contents)
373
+ assert w.tell() == len(contents)
374
+ with bf.BlobFile(path, "rb", streaming=streaming) as r:
375
+ assert r.read() == contents
376
+ assert r.tell() == len(contents)
377
+ with bf.BlobFile(path, "rb", streaming=streaming) as r:
378
+ lines = list(r)
379
+ assert b"".join(lines) == contents
380
+
381
+
382
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
383
+ def test_zipfile(ctx):
384
+ contents = b"meow!\npurr\n"
385
+ with ctx() as path:
386
+ with bf.BlobFile(path, "wb", streaming=True) as f:
387
+ with zipfile.ZipFile(f, "w") as zf:
388
+ with zf.open("eggs.txt", "w") as myfile:
389
+ myfile.write(contents)
390
+
391
+ with bf.BlobFile(path, "rb", streaming=True) as f:
392
+ with zipfile.ZipFile(f, "r") as zf:
393
+ with zf.open("eggs.txt", "r") as myfile:
394
+ assert myfile.read() == contents
395
+
396
+
397
+ def test_az_path():
398
+ contents = b"meow!\npurr\n"
399
+ with _get_temp_as_path() as path:
400
+ path = _convert_https_to_az(path)
401
+ path = bf.join(path, "a folder", "a.file")
402
+ path = _convert_https_to_az(path)
403
+ bf.makedirs(_convert_https_to_az(bf.dirname(path)))
404
+ with bf.BlobFile(path, "wb") as w:
405
+ w.write(contents)
406
+ with bf.BlobFile(path, "rb") as r:
407
+ assert r.read() == contents
408
+ with bf.BlobFile(path, "rb") as r:
409
+ lines = list(r)
410
+ assert b"".join(lines) == contents
411
+
412
+
413
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
414
+ def test_append(ctx):
415
+ contents = b"meow!\n"
416
+ additional_contents = b"purr\n"
417
+ with ctx() as path:
418
+ with bf.BlobFile(path, "ab", streaming=False) as w:
419
+ w.write(contents)
420
+ with bf.BlobFile(path, "ab", streaming=False) as w:
421
+ w.write(additional_contents)
422
+ with bf.BlobFile(path, "rb") as r:
423
+ assert r.read() == contents + additional_contents
424
+
425
+
426
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
427
+ def test_stat(ctx):
428
+ contents = b"meow!"
429
+ with ctx() as path:
430
+ _write_contents(path, contents)
431
+ s = bf.stat(path)
432
+ assert s.size == len(contents)
433
+ assert abs(time.time() - s.mtime) <= 30
434
+
435
+
436
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
437
+ def test_set_mtime(ctx):
438
+ contents = b"meow!"
439
+ with ctx() as path:
440
+ _write_contents(path, contents)
441
+ s = bf.stat(path)
442
+ assert abs(time.time() - s.mtime) <= 30
443
+ new_mtime = 1
444
+ assert bf.set_mtime(path, new_mtime)
445
+ assert bf.stat(path).mtime == new_mtime
446
+
447
+
448
+ @pytest.mark.parametrize("ctx", [_get_temp_as_path])
449
+ def test_azure_metadata(ctx):
450
+ # make sure metadata is preserved when opening a file for writing
451
+ # which clears uncommitted blocks
452
+ contents = b"meow!"
453
+
454
+ with ctx() as path:
455
+ with bf.BlobFile(path, "wb") as f:
456
+ f.write(contents)
457
+
458
+ bf.set_mtime(path, 1)
459
+ time.sleep(5)
460
+ with bf.BlobFile(path, "wb", streaming=True) as f:
461
+ st = bf.stat(path)
462
+ assert st.mtime == 1
463
+
464
+
465
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
466
+ def test_remove(ctx):
467
+ contents = b"meow!"
468
+ with ctx() as path:
469
+ _write_contents(path, contents)
470
+ assert bf.exists(path)
471
+ bf.remove(path)
472
+ assert not bf.exists(path)
473
+
474
+
475
+ @pytest.mark.parametrize(
476
+ # don't test local path because that has slightly different behavior
477
+ "ctx",
478
+ [_get_temp_gcs_path, _get_temp_as_path],
479
+ )
480
+ def test_rmdir(ctx):
481
+ contents = b"meow!"
482
+ with ctx() as path:
483
+ dirpath = bf.dirname(path)
484
+ # this is an error for a local path but not for a blob path
485
+ bf.rmdir(bf.join(dirpath, "fakedirname"))
486
+ new_dirpath = bf.join(dirpath, "dirname")
487
+ bf.makedirs(new_dirpath)
488
+ assert bf.exists(new_dirpath)
489
+ bf.rmdir(new_dirpath)
490
+ assert not bf.exists(new_dirpath)
491
+
492
+ # double delete is fine
493
+ bf.rmdir(new_dirpath)
494
+
495
+ # implicit dir
496
+ new_filepath = bf.join(dirpath, "dirname", "name")
497
+ _write_contents(new_filepath, contents)
498
+ with pytest.raises(OSError):
499
+ # not empty dir
500
+ bf.rmdir(new_dirpath)
501
+ bf.remove(new_filepath)
502
+ bf.rmdir(new_dirpath)
503
+
504
+
505
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
506
+ def test_makedirs(ctx):
507
+ contents = b"meow!"
508
+ with ctx() as path:
509
+ dirpath = bf.join(path, "x", "x", "x")
510
+ bf.makedirs(dirpath)
511
+ assert bf.exists(dirpath)
512
+ _write_contents(bf.join(dirpath, "testfile"), contents)
513
+
514
+
515
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
516
+ def test_isdir(ctx):
517
+ contents = b"meow!"
518
+ with ctx() as path:
519
+ assert not bf.isdir(path)
520
+ _write_contents(path, contents)
521
+ assert not bf.isdir(path)
522
+
523
+ dirpath = path + ".dir"
524
+ bf.makedirs(dirpath)
525
+ assert bf.isdir(dirpath)
526
+ assert not bf.isdir(dirpath[:-1])
527
+
528
+ filepath = bf.join(path + ".otherdir", "subdir", "file.name")
529
+ if "://" not in path:
530
+ # implicit directory
531
+ bf.makedirs(bf.dirname(filepath))
532
+ dirpath = bf.dirname(bf.dirname(filepath))
533
+ _write_contents(filepath, contents)
534
+ assert bf.isdir(dirpath)
535
+ assert not bf.isdir(dirpath[:-1])
536
+
537
+
538
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
539
+ def test_listdir(ctx):
540
+ contents = b"meow!"
541
+ with ctx() as path:
542
+ dirpath = bf.dirname(path)
543
+ bf.makedirs(dirpath)
544
+ a_path = bf.join(dirpath, "a")
545
+ with bf.BlobFile(a_path, "wb") as w:
546
+ w.write(contents)
547
+ b_path = bf.join(dirpath, "b")
548
+ with bf.BlobFile(b_path, "wb") as w:
549
+ w.write(contents)
550
+ bf.makedirs(bf.join(dirpath, "c"))
551
+ expected = ["a", "b", "c"]
552
+ assert sorted(list(bf.listdir(dirpath))) == expected
553
+ dirpath = _convert_https_to_az(dirpath)
554
+ assert sorted(list(bf.listdir(dirpath))) == expected
555
+
556
+
557
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
558
+ def test_scandir(ctx):
559
+ contents = b"meow!"
560
+ with ctx() as path:
561
+ dirpath = bf.dirname(path)
562
+ a_path = bf.join(dirpath, "a")
563
+ with bf.BlobFile(a_path, "wb") as w:
564
+ w.write(contents)
565
+ b_path = bf.join(dirpath, "b")
566
+ with bf.BlobFile(b_path, "wb") as w:
567
+ w.write(contents)
568
+ bf.makedirs(bf.join(dirpath, "c"))
569
+ entries = sorted(list(bf.scandir(dirpath)))
570
+ assert [e.name for e in entries] == ["a", "b", "c"]
571
+ assert [e.path for e in entries] == [bf.join(dirpath, name) for name in ["a", "b", "c"]]
572
+ assert [e.is_dir for e in entries] == [False, False, True]
573
+ assert [e.is_file for e in entries] == [True, True, False]
574
+ assert entries[0].stat.size == len(contents)
575
+ assert entries[1].stat.size == len(contents)
576
+ assert entries[2].stat is None
577
+
578
+
579
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
580
+ def test_listdir_sharded(ctx):
581
+ contents = b"meow!"
582
+ with ctx() as path:
583
+ dirpath = bf.dirname(path)
584
+ with bf.BlobFile(bf.join(dirpath, "a"), "wb") as w:
585
+ w.write(contents)
586
+ with bf.BlobFile(bf.join(dirpath, "aa"), "wb") as w:
587
+ w.write(contents)
588
+ with bf.BlobFile(bf.join(dirpath, "b"), "wb") as w:
589
+ w.write(contents)
590
+ with bf.BlobFile(bf.join(dirpath, "ca"), "wb") as w:
591
+ w.write(contents)
592
+ bf.makedirs(bf.join(dirpath, "c"))
593
+ with bf.BlobFile(bf.join(dirpath, "c/a"), "wb") as w:
594
+ w.write(contents)
595
+ # this should also test shard_prefix_length=2 but that takes too long
596
+ assert sorted(list(bf.listdir(dirpath, shard_prefix_length=1))) == [
597
+ "a",
598
+ "aa",
599
+ "b",
600
+ "c",
601
+ "ca",
602
+ ]
603
+
604
+
605
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
606
+ @pytest.mark.parametrize("topdown", [False, True])
607
+ def test_walk(ctx, topdown):
608
+ contents = b"meow!"
609
+ with ctx() as path:
610
+ dirpath = bf.dirname(path)
611
+ a_path = bf.join(dirpath, "a")
612
+ with bf.BlobFile(a_path, "wb") as w:
613
+ w.write(contents)
614
+ bf.makedirs(bf.join(dirpath, "c/d"))
615
+ b_path = bf.join(dirpath, "c/d/b")
616
+ with bf.BlobFile(b_path, "wb") as w:
617
+ w.write(contents)
618
+ expected = [
619
+ (dirpath, ["c"], ["a"]),
620
+ (bf.join(dirpath, "c"), ["d"], []),
621
+ (bf.join(dirpath, "c", "d"), [], ["b"]),
622
+ ]
623
+ if not topdown:
624
+ expected = list(reversed(expected))
625
+ assert list(bf.walk(dirpath, topdown=topdown)) == expected
626
+ dirpath = _convert_https_to_az(dirpath)
627
+ assert list(bf.walk(dirpath, topdown=topdown)) == expected
628
+
629
+
630
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path])
631
+ def test_local_glob(ctx):
632
+ contents = b"meow!"
633
+ with ctx() as path:
634
+ dirpath = bf.dirname(path)
635
+ a_path = bf.join(dirpath, "ab")
636
+ with bf.BlobFile(a_path, "wb") as w:
637
+ w.write(contents)
638
+ b_path = bf.join(dirpath, "bb")
639
+ with bf.BlobFile(b_path, "wb") as w:
640
+ w.write(contents)
641
+
642
+ def assert_listing_equal(path, desired):
643
+ desired = sorted([bf.join(dirpath, p) for p in desired])
644
+ actual = sorted(list(bf.glob(path)))
645
+ assert actual == desired, f"{actual} != {desired}"
646
+
647
+ # example patterns (didn't add tests for all these)
648
+ # /a/b*c
649
+ # /a/*b
650
+ # /a/c*
651
+ # /a/*
652
+ # /a/*/
653
+ # /a/b*c/d
654
+ # a/b*c
655
+ # a/*b
656
+ # a/c*
657
+ # a/b*c/d
658
+ # b*c
659
+ # *c
660
+ # b*
661
+ # *
662
+ # */
663
+ # */a
664
+ with chdir(dirpath):
665
+ assert_listing_equal("ab", ["ab"])
666
+ assert_listing_equal("*b", ["ab", "bb"])
667
+ assert_listing_equal("a*", ["ab"])
668
+ assert_listing_equal("ab*", ["ab"])
669
+ assert_listing_equal("*", ["ab", "bb"])
670
+ assert_listing_equal("bb", ["bb"])
671
+
672
+
673
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
674
+ @pytest.mark.parametrize("parallel", [False, True])
675
+ def test_glob(ctx, parallel):
676
+ contents = b"meow!"
677
+ with ctx() as path:
678
+ dirpath = bf.dirname(path)
679
+ a_path = bf.join(dirpath, "ab")
680
+ with bf.BlobFile(a_path, "wb") as w:
681
+ w.write(contents)
682
+ b_path = bf.join(dirpath, "bb")
683
+ with bf.BlobFile(b_path, "wb") as w:
684
+ w.write(contents)
685
+
686
+ def assert_listing_equal(path, desired):
687
+ desired = sorted([bf.join(dirpath, p) for p in desired])
688
+ actual = sorted(list(bf.glob(path, parallel=parallel)))
689
+ assert actual == desired, f"{actual} != {desired}"
690
+
691
+ assert_listing_equal(bf.join(dirpath, "*b"), ["ab", "bb"])
692
+ assert_listing_equal(bf.join(dirpath, "a*"), ["ab"])
693
+ assert_listing_equal(bf.join(dirpath, "ab*"), ["ab"])
694
+ assert_listing_equal(bf.join(dirpath, "*"), ["ab", "bb"])
695
+ assert_listing_equal(bf.join(dirpath, "bb"), ["bb"])
696
+
697
+ path = bf.join(dirpath, "test.txt")
698
+ with bf.BlobFile(path, "wb") as w:
699
+ w.write(contents)
700
+ path = bf.join(dirpath, "subdir", "test.txt")
701
+ bf.makedirs(bf.dirname(path))
702
+ with bf.BlobFile(path, "wb") as f:
703
+ f.write(contents)
704
+ path = bf.join(dirpath, "subdir", "subsubdir", "test.txt")
705
+ if "://" not in path:
706
+ # implicit directory
707
+ bf.makedirs(bf.dirname(path))
708
+ with bf.BlobFile(path, "wb") as f:
709
+ f.write(contents)
710
+
711
+ assert_listing_equal(bf.join(dirpath, "*/test.txt"), ["subdir/test.txt"])
712
+ assert_listing_equal(bf.join(dirpath, "*/*.txt"), ["subdir/test.txt"])
713
+ assert_listing_equal(
714
+ bf.join(dirpath, "**.txt"), ["test.txt", "subdir/test.txt", "subdir/subsubdir/test.txt"]
715
+ )
716
+ assert_listing_equal(
717
+ bf.join(dirpath, "sub**.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"]
718
+ )
719
+ assert_listing_equal(
720
+ bf.join(dirpath, "subdir/**.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"]
721
+ )
722
+ assert_listing_equal(
723
+ bf.join(dirpath, "**/*.txt"), ["subdir/test.txt", "subdir/subsubdir/test.txt"]
724
+ )
725
+
726
+ assert_listing_equal(bf.join(dirpath, "*/test"), [])
727
+ assert_listing_equal(bf.join(dirpath, "subdir/test.txt"), ["subdir/test.txt"])
728
+
729
+ # directories
730
+ assert_listing_equal(bf.join(dirpath, "*"), ["ab", "bb", "subdir", "test.txt"])
731
+ assert_listing_equal(bf.join(dirpath, "subdir"), ["subdir"])
732
+ assert_listing_equal(bf.join(dirpath, "subdir/"), ["subdir"])
733
+ assert_listing_equal(bf.join(dirpath, "*/"), ["subdir"])
734
+ assert_listing_equal(bf.join(dirpath, "*dir"), ["subdir"])
735
+ assert_listing_equal(bf.join(dirpath, "subdir/*dir"), ["subdir/subsubdir"])
736
+ assert_listing_equal(bf.join(dirpath, "subdir/*dir/"), ["subdir/subsubdir"])
737
+ assert_listing_equal(bf.join(dirpath, "su*ir/*dir/"), ["subdir/subsubdir"])
738
+
739
+
740
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
741
+ def test_scanglob(ctx):
742
+ contents = b"meow!"
743
+ with ctx() as path:
744
+ dirpath = bf.dirname(path)
745
+ a_path = bf.join(dirpath, "ab")
746
+ with bf.BlobFile(a_path, "wb") as w:
747
+ w.write(contents)
748
+ b_path = bf.join(dirpath, "bb")
749
+ with bf.BlobFile(b_path, "wb") as w:
750
+ w.write(contents)
751
+ path = bf.join(dirpath, "test.txt")
752
+ with bf.BlobFile(path, "wb") as w:
753
+ w.write(contents)
754
+ path = bf.join(dirpath, "subdir", "test.txt")
755
+ bf.makedirs(bf.dirname(path))
756
+ with bf.BlobFile(path, "wb") as f:
757
+ f.write(contents)
758
+
759
+ entries = sorted(list(bf.scanglob(bf.join(dirpath, "*b*"))))
760
+ assert entries[0].name == "ab" and entries[0].is_file
761
+ assert entries[1].name == "bb" and entries[1].is_file
762
+ assert entries[2].name == "subdir" and entries[2].is_dir
763
+
764
+ for shard_prefix_length in [0, 1]:
765
+ for pattern in ["*b", "b*", "**", "b**", "**t", "*b*"]:
766
+ normal_entries = sorted(list(bf.scanglob(bf.join(dirpath, pattern))))
767
+ parallel_entries = sorted(
768
+ list(
769
+ bf.scanglob(
770
+ bf.join(dirpath, pattern),
771
+ parallel=True,
772
+ shard_prefix_length=shard_prefix_length,
773
+ )
774
+ )
775
+ )
776
+ assert parallel_entries == normal_entries
777
+
778
+ if "://" in path:
779
+ # ** behaves a bit differently on local paths, so don't check those
780
+ entries = sorted(list(bf.scanglob(bf.join(dirpath, "**"))))
781
+ assert entries[0].name == "ab" and entries[0].is_file
782
+ assert entries[1].name == "bb" and entries[1].is_file
783
+ assert entries[2].name == "subdir" and entries[2].is_dir
784
+
785
+
786
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
787
+ @pytest.mark.parametrize("parallel", [False, True])
788
+ def test_rmtree(ctx, parallel):
789
+ contents = b"meow!"
790
+ with ctx() as path:
791
+ root = bf.dirname(path)
792
+ destroy_path = bf.join(root, "destroy")
793
+ bf.makedirs(destroy_path)
794
+ save_path = bf.join(root, "save")
795
+ bf.makedirs(save_path)
796
+
797
+ # implicit dir
798
+ if "://" not in path:
799
+ bf.makedirs(bf.join(destroy_path, "adir"))
800
+ with bf.BlobFile(bf.join(destroy_path, "adir/b"), "wb") as w:
801
+ w.write(contents)
802
+
803
+ # explicit dir
804
+ bf.makedirs(bf.join(destroy_path, "bdir"))
805
+ with bf.BlobFile(bf.join(destroy_path, "bdir/b"), "wb") as w:
806
+ w.write(contents)
807
+
808
+ bf.makedirs(bf.join(save_path, "somedir"))
809
+ with bf.BlobFile(bf.join(save_path, "somefile"), "wb") as w:
810
+ w.write(contents)
811
+
812
+ def assert_listing_equal(path, desired):
813
+ actual = list(bf.walk(path))
814
+ # ordering of os walk is weird, only compare sorted order
815
+ assert sorted(actual) == sorted(desired), f"{actual} != {desired}"
816
+
817
+ assert_listing_equal(
818
+ root,
819
+ [
820
+ (root, ["destroy", "save"], []),
821
+ (destroy_path, ["adir", "bdir"], []),
822
+ (bf.join(destroy_path, "adir"), [], ["b"]),
823
+ (bf.join(destroy_path, "bdir"), [], ["b"]),
824
+ (save_path, ["somedir"], ["somefile"]),
825
+ (bf.join(save_path, "somedir"), [], []),
826
+ ],
827
+ )
828
+
829
+ bf.rmtree(destroy_path, parallel=parallel)
830
+
831
+ assert_listing_equal(
832
+ root,
833
+ [
834
+ (root, ["save"], []),
835
+ (save_path, ["somedir"], ["somefile"]),
836
+ (bf.join(save_path, "somedir"), [], []),
837
+ ],
838
+ )
839
+
840
+
841
+ @pytest.mark.parametrize("parallel", [False, True])
842
+ def test_copy(parallel):
843
+ for contents in [b"", b"meow!", b"meow!" * (2 * 2**20)]:
844
+ 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(
845
+ account=AS_TEST_ACCOUNT2, container=AS_TEST_CONTAINER2
846
+ ) as as_path3, _get_temp_as_path() as as_path4:
847
+ with pytest.raises(FileNotFoundError):
848
+ bf.copy(gcs_path1, gcs_path2, parallel=parallel)
849
+ with pytest.raises(FileNotFoundError):
850
+ bf.copy(as_path1, as_path2, parallel=parallel)
851
+
852
+ _write_contents(local_path1, contents)
853
+
854
+ testcases = [
855
+ (local_path1, local_path2),
856
+ (local_path1, gcs_path1),
857
+ (gcs_path1, gcs_path2),
858
+ (gcs_path2, as_path1),
859
+ (as_path1, as_path2),
860
+ (as_path2, as_path3),
861
+ (as_path3, local_path3),
862
+ (local_path3, as_path4),
863
+ ]
864
+
865
+ for src, dst in testcases:
866
+ h = bf.copy(src, dst, return_md5=True, parallel=parallel)
867
+ assert h == hashlib.md5(contents).hexdigest()
868
+ assert _read_contents(dst) == contents
869
+ with pytest.raises(FileExistsError):
870
+ bf.copy(src, dst, parallel=parallel)
871
+ bf.copy(src, dst, overwrite=True, parallel=parallel)
872
+ assert _read_contents(dst) == contents
873
+
874
+
875
+ @pytest.mark.parametrize("parallel", [False, True])
876
+ def test_copy_invalid(parallel):
877
+ for contents in [b"", b"meow!", b"meow!" * (2 * 2**20)]:
878
+ with _get_temp_local_path() as local_path, _get_temp_as_path() as as_path1, _get_temp_as_path() as as_path2:
879
+ invalid_container_as_path = _convert_az_to_https(
880
+ bf.join(AZURE_INVALID_CONTAINER, "file.bin")
881
+ )
882
+ invalid_account_as_path = _convert_az_to_https(
883
+ bf.join(AZURE_INVALID_CONTAINER_NO_ACCOUNT, "file.bin")
884
+ )
885
+
886
+ _write_contents(local_path, contents)
887
+ bf.copy(local_path, as_path1, parallel=parallel)
888
+ with pytest.raises(FileNotFoundError, match=invalid_container_as_path):
889
+ bf.copy(local_path, invalid_container_as_path, parallel=parallel)
890
+ with pytest.raises(FileNotFoundError, match=invalid_account_as_path):
891
+ bf.copy(local_path, invalid_account_as_path, parallel=parallel)
892
+
893
+ with pytest.raises(FileNotFoundError, match=invalid_container_as_path):
894
+ bf.copy(as_path1, invalid_container_as_path, parallel=parallel)
895
+ with pytest.raises(FileNotFoundError, match=invalid_account_as_path):
896
+ bf.copy(as_path1, invalid_account_as_path, parallel=parallel)
897
+
898
+ with pytest.raises(FileNotFoundError, match=invalid_container_as_path):
899
+ bf.copy(invalid_container_as_path, as_path2, parallel=parallel)
900
+
901
+ # this fails with a RequestFailure to get the sas token
902
+ # with pytest.raises(FileNotFoundError, match=invalid_account_as_path):
903
+ # bf.copy(invalid_account_as_path, as_path2, parallel=parallel)
904
+
905
+
906
+ # the tests already take awhile and this adds like a minute
907
+ @pytest.mark.slow
908
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
909
+ def test_parallel_copy_large_file(ctx):
910
+ contents = b"meow!" * common.PARALLEL_COPY_MINIMUM_PART_SIZE + b"meow???"
911
+ with ctx() as remote_path:
912
+ with tempfile.TemporaryDirectory() as tmpdir:
913
+ local_path = os.path.join(tmpdir, "test.txt")
914
+ with open(local_path, "wb") as f:
915
+ f.write(contents)
916
+ bf.copy(local_path, remote_path, parallel=True)
917
+
918
+ assert _read_contents(remote_path) == contents
919
+
920
+ with tempfile.TemporaryDirectory() as tmpdir:
921
+ local_path = os.path.join(tmpdir, "test.txt")
922
+ bf.copy(remote_path, local_path, parallel=True)
923
+ assert _read_contents(local_path) == contents
924
+
925
+
926
+ def test_copy_azure_public():
927
+ with _get_temp_as_path() as dst:
928
+ bf.copy(AZURE_PUBLIC_URL, dst)
929
+ assert _read_contents(dst)[:4] == AZURE_PUBLIC_URL_HEADER
930
+
931
+
932
+ def test_gcs_public():
933
+ filepath = "gs://tfds-data/datasets/mnist/3.0.1/dataset_info.json"
934
+ assert bf.exists(filepath)
935
+ assert len(bf.BlobFile(filepath, "rb").read()) > 0
936
+
937
+
938
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
939
+ def test_exists(ctx):
940
+ contents = b"meow!"
941
+ with ctx() as path:
942
+ assert not bf.exists(path)
943
+ _write_contents(path, contents)
944
+ assert bf.exists(path)
945
+
946
+
947
+ def test_concurrent_write_gcs():
948
+ with _get_temp_gcs_path() as path:
949
+ outer_contents = b"miso" * (2**20 + 1)
950
+ inner_contents = b"momo" * (2**20 + 1)
951
+ with bf.BlobFile(path, "wb", streaming=True) as f:
952
+ f.write(outer_contents)
953
+ with bf.BlobFile(path, "wb", streaming=True) as f:
954
+ f.write(inner_contents)
955
+
956
+ # the outer write will finish last and overwrite the inner one
957
+ # the last writer to finish wins with this setup
958
+ with bf.BlobFile(path, "rb") as f:
959
+ assert f.read() == outer_contents
960
+
961
+
962
+ def test_concurrent_write_as():
963
+ with _get_temp_as_path() as path:
964
+ b = bf.create_context(azure_write_chunk_size=2**20)
965
+ outer_contents = b"miso" * (2**20 + 1)
966
+ inner_contents = b"momo" * (2**20 + 1)
967
+ # the inner write will invalidate the outer one, the last writer
968
+ # to start wins with this setup
969
+ with pytest.raises(bf.ConcurrentWriteFailure):
970
+ with b.BlobFile(path, "wb", streaming=True) as f:
971
+ f.write(outer_contents)
972
+ with b.BlobFile(path, "wb", streaming=True) as f:
973
+ f.write(inner_contents)
974
+
975
+ # the outer write will finish last and overwrite the inner one
976
+ with b.BlobFile(path, "rb") as f:
977
+ assert f.read() == inner_contents
978
+
979
+
980
+ @contextlib.contextmanager
981
+ def environ_context():
982
+ env = os.environ.copy()
983
+ yield
984
+ os.environ = env
985
+
986
+
987
+ def test_more_exists():
988
+ testcases = [
989
+ (AZURE_INVALID_CONTAINER, False),
990
+ (AZURE_INVALID_CONTAINER + "/", False),
991
+ (AZURE_INVALID_CONTAINER + "//", False),
992
+ (AZURE_INVALID_CONTAINER + "/invalid.file", False),
993
+ (GCS_INVALID_BUCKET, False),
994
+ (GCS_INVALID_BUCKET + "/", False),
995
+ (GCS_INVALID_BUCKET + "//", False),
996
+ (GCS_INVALID_BUCKET + "/invalid.file", False),
997
+ (AZURE_INVALID_CONTAINER_NO_ACCOUNT, False),
998
+ (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "/", False),
999
+ (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "//", False),
1000
+ (AZURE_INVALID_CONTAINER_NO_ACCOUNT + "/invalid.file", False),
1001
+ (AZURE_VALID_CONTAINER, True),
1002
+ (AZURE_VALID_CONTAINER + "/", True),
1003
+ (AZURE_VALID_CONTAINER + "//", False),
1004
+ (AZURE_VALID_CONTAINER + "/invalid.file", False),
1005
+ (GCS_VALID_BUCKET, True),
1006
+ (GCS_VALID_BUCKET + "/", True),
1007
+ (GCS_VALID_BUCKET + "//", False),
1008
+ (GCS_VALID_BUCKET + "/invalid.file", False),
1009
+ ("/does-not-exist", False),
1010
+ ("/", True),
1011
+ ]
1012
+ for path, should_exist in testcases:
1013
+ assert bf.exists(path) == should_exist
1014
+
1015
+
1016
+ @pytest.mark.parametrize(
1017
+ "base_path", [AZURE_INVALID_CONTAINER_NO_ACCOUNT, AZURE_INVALID_CONTAINER, GCS_INVALID_BUCKET]
1018
+ )
1019
+ def test_invalid_paths(base_path):
1020
+ for suffix in ["", "/", "//", "/invalid.file", "/invalid/dir/"]:
1021
+ path = base_path + suffix
1022
+ print(path)
1023
+ if path.endswith("/"):
1024
+ expected_error = IsADirectoryError
1025
+ else:
1026
+ expected_error = FileNotFoundError
1027
+ list(bf.glob(path))
1028
+ if suffix == "":
1029
+ for pattern in ["*", "**"]:
1030
+ try:
1031
+ list(bf.glob(path + pattern))
1032
+ except bf.Error as e:
1033
+ assert "Wildcards cannot be used" in e.message
1034
+ else:
1035
+ for pattern in ["*", "**"]:
1036
+ list(bf.glob(path + pattern))
1037
+ with pytest.raises(FileNotFoundError):
1038
+ list(bf.listdir(path))
1039
+ assert not bf.exists(path)
1040
+ assert not bf.isdir(path)
1041
+ with pytest.raises(expected_error):
1042
+ bf.remove(path)
1043
+ if suffix in ("", "/"):
1044
+ try:
1045
+ bf.rmdir(path)
1046
+ except bf.Error as e:
1047
+ assert "Cannot delete bucket" in e.message
1048
+ else:
1049
+ bf.rmdir(path)
1050
+ with pytest.raises(NotADirectoryError):
1051
+ bf.rmtree(path)
1052
+ with pytest.raises(FileNotFoundError):
1053
+ bf.stat(path)
1054
+
1055
+ if base_path == AZURE_INVALID_CONTAINER_NO_ACCOUNT:
1056
+ with pytest.raises(bf.Error):
1057
+ bf.get_url(path)
1058
+ else:
1059
+ bf.get_url(path)
1060
+
1061
+ with pytest.raises(FileNotFoundError):
1062
+ bf.md5(path)
1063
+ with pytest.raises(bf.Error):
1064
+ bf.makedirs(path)
1065
+ list(bf.walk(path))
1066
+ with tempfile.TemporaryDirectory() as tmpdir:
1067
+ local_path = os.path.join(tmpdir, "test.txt")
1068
+ with pytest.raises(expected_error):
1069
+ bf.copy(path, local_path)
1070
+ with open(local_path, "w") as f:
1071
+ f.write("meow")
1072
+ with pytest.raises(expected_error):
1073
+ bf.copy(local_path, path)
1074
+ for streaming in [False, True]:
1075
+ with pytest.raises(expected_error):
1076
+ with bf.BlobFile(path, "rb", streaming=streaming) as f:
1077
+ f.read()
1078
+ with pytest.raises(expected_error):
1079
+ with bf.BlobFile(path, "wb", streaming=streaming) as f:
1080
+ f.write(b"meow")
1081
+
1082
+
1083
+ @pytest.mark.parametrize("buffer_size", [1, 100])
1084
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
1085
+ def test_read_stats(buffer_size, ctx):
1086
+ with ctx() as path:
1087
+ contents = b"meow!"
1088
+
1089
+ with bf.BlobFile(path, "wb") as w:
1090
+ w.write(contents)
1091
+
1092
+ with bf.BlobFile(path, "rb", buffer_size=buffer_size) as r:
1093
+ r.read(1)
1094
+
1095
+ if buffer_size == 1:
1096
+ assert r.raw.bytes_read == 1 # type: ignore
1097
+ else:
1098
+ assert r.raw.bytes_read == len(contents) # type: ignore
1099
+
1100
+ with bf.BlobFile(path, "rb", buffer_size=buffer_size) as r:
1101
+ r.read(1)
1102
+ r.seek(4)
1103
+ r.read(1)
1104
+ r.seek(1000000)
1105
+ assert r.read(1) == b""
1106
+
1107
+ if buffer_size == 1:
1108
+ assert r.raw.requests == 2 # type: ignore
1109
+ assert r.raw.bytes_read == 2 # type: ignore
1110
+ else:
1111
+ assert r.raw.requests == 1 # type: ignore
1112
+ assert r.raw.bytes_read == len(contents) # type: ignore
1113
+
1114
+
1115
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
1116
+ def test_cache_dir(ctx):
1117
+ cache_dir = tempfile.mkdtemp()
1118
+ contents = b"meow!"
1119
+ alternative_contents = b"purr!"
1120
+ with ctx() as path:
1121
+ with bf.BlobFile(path, mode="wb") as f:
1122
+ f.write(contents)
1123
+ with bf.BlobFile(path, mode="rb", streaming=False, cache_dir=cache_dir) as f:
1124
+ assert f.read() == contents
1125
+ content_hash = hashlib.md5(contents).hexdigest()
1126
+ cache_path = bf.join(cache_dir, content_hash, bf.basename(path))
1127
+ with open(cache_path, "rb") as f:
1128
+ assert f.read() == contents
1129
+ # alter the cached file to make sure we are not re-reading the remote file
1130
+ with open(cache_path, "wb") as f:
1131
+ f.write(alternative_contents)
1132
+ with bf.BlobFile(path, mode="rb", streaming=False, cache_dir=cache_dir) as f:
1133
+ assert f.read() == alternative_contents
1134
+ with bf.BlobFile(
1135
+ f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat_no_md5.png",
1136
+ mode="rb",
1137
+ streaming=False,
1138
+ cache_dir=cache_dir,
1139
+ ) as f:
1140
+ assert len(f.read()) > 0
1141
+
1142
+
1143
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1144
+ @pytest.mark.parametrize("use_random", [False, True])
1145
+ def test_change_file_size(ctx, use_random):
1146
+ chunk_size = 8 * 2**20
1147
+ long_contents = b"\x00" * chunk_size * 3
1148
+ short_contents = b"\xFF" * chunk_size * 2
1149
+ if use_random:
1150
+ long_contents = os.urandom(len(long_contents))
1151
+ short_contents = os.urandom(len(short_contents))
1152
+ with ctx() as path:
1153
+ # make file shorter
1154
+ with bf.BlobFile(path, "wb") as f:
1155
+ f.write(long_contents)
1156
+ with bf.BlobFile(path, "rb") as f:
1157
+ read_contents = f.read(chunk_size)
1158
+ with bf.BlobFile(path, "wb") as f2:
1159
+ f2.write(short_contents)
1160
+ # close underlying connection
1161
+ f.raw._f = None # type: ignore
1162
+ read_contents += f.read()
1163
+ assert len(f.read()) == 0
1164
+ assert read_contents == long_contents[:chunk_size] + short_contents[chunk_size:]
1165
+
1166
+ # make file longer
1167
+ with bf.BlobFile(path, "wb") as f:
1168
+ f.write(short_contents)
1169
+ with bf.BlobFile(path, "rb") as f:
1170
+ read_contents = f.read(chunk_size)
1171
+ with bf.BlobFile(path, "wb") as f2:
1172
+ f2.write(long_contents)
1173
+ # close underlying connection
1174
+ f.raw._f = None # type: ignore
1175
+ read_contents += f.read()
1176
+ assert len(f.read()) == 0
1177
+ expected = short_contents[:chunk_size] + long_contents[chunk_size : chunk_size * 2]
1178
+ # local files behave differently and read the new contents until the
1179
+ # end of the new file size
1180
+ if not path.startswith("gs://") and not path.startswith("https://"):
1181
+ expected = short_contents[:chunk_size] + long_contents[chunk_size:]
1182
+ assert read_contents == expected
1183
+
1184
+
1185
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1186
+ def test_overwrite_while_reading(ctx):
1187
+ chunk_size = 8 * 2**20
1188
+ contents = b"\x00" * chunk_size * 2
1189
+ alternative_contents = b"\xFF" * chunk_size * 4
1190
+ with ctx() as path:
1191
+ with bf.BlobFile(path, "wb") as f:
1192
+ f.write(contents)
1193
+ with bf.BlobFile(path, "rb") as f:
1194
+ read_contents = f.read(chunk_size)
1195
+ with bf.BlobFile(path, "wb") as f2:
1196
+ f2.write(alternative_contents)
1197
+ # close underlying connection
1198
+ f.raw._f = None # type: ignore
1199
+ read_contents += f.read(chunk_size)
1200
+ assert (
1201
+ read_contents
1202
+ == contents[:chunk_size] + alternative_contents[chunk_size : chunk_size * 2]
1203
+ )
1204
+
1205
+
1206
+ def test_create_local_intermediate_dirs():
1207
+ contents = b"meow"
1208
+ with _get_temp_local_path() as path:
1209
+ dirpath = bf.dirname(path)
1210
+ with chdir(dirpath):
1211
+ for filepath in [
1212
+ bf.join(dirpath, "dirname", "file.name"),
1213
+ bf.join("..", bf.basename(dirpath), "file.name"),
1214
+ "./file.name",
1215
+ "file.name",
1216
+ ]:
1217
+ with bf.BlobFile(filepath, "wb") as f:
1218
+ f.write(contents)
1219
+
1220
+
1221
+ @pytest.mark.parametrize("binary", [True, False])
1222
+ @pytest.mark.parametrize("streaming", [True, False])
1223
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1224
+ def test_more_read_write(binary, streaming, ctx):
1225
+ rng = np.random.RandomState(0)
1226
+
1227
+ with ctx() as path:
1228
+ if binary:
1229
+ read_mode = "rb"
1230
+ write_mode = "wb"
1231
+ else:
1232
+ read_mode = "r"
1233
+ write_mode = "w"
1234
+
1235
+ with bf.BlobFile(path, write_mode, streaming=streaming) as w:
1236
+ pass
1237
+
1238
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1239
+ assert len(r.read()) == 0
1240
+
1241
+ contents = b"meow!"
1242
+ if not binary:
1243
+ contents = contents.decode("utf8")
1244
+
1245
+ with bf.BlobFile(path, write_mode, streaming=streaming) as w:
1246
+ w.write(contents)
1247
+
1248
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1249
+ assert r.read(1) == contents[:1]
1250
+ assert r.read() == contents[1:]
1251
+ assert len(r.read()) == 0
1252
+
1253
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1254
+ for i in range(len(contents)):
1255
+ assert r.read(1) == contents[i : i + 1]
1256
+ assert len(r.read()) == 0
1257
+ assert len(r.read()) == 0
1258
+
1259
+ contents = b"meow!\n\nmew!\n"
1260
+ lines = [b"meow!\n", b"\n", b"mew!\n"]
1261
+ if not binary:
1262
+ contents = contents.decode("utf8")
1263
+ lines = [line.decode("utf8") for line in lines]
1264
+
1265
+ with bf.BlobFile(path, write_mode, streaming=streaming) as w:
1266
+ w.write(contents)
1267
+
1268
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1269
+ assert r.readlines() == lines
1270
+
1271
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1272
+ assert [line for line in r] == lines
1273
+
1274
+ if binary:
1275
+ for size in [2 * 2**20, 12_345_678]:
1276
+ contents = rng.randint(0, 256, size=size, dtype=np.uint8).tobytes()
1277
+
1278
+ with bf.BlobFile(path, write_mode, streaming=streaming) as w:
1279
+ w.write(contents)
1280
+
1281
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1282
+ size = rng.randint(0, 1_000_000)
1283
+ buf = b""
1284
+ while True:
1285
+ b = r.read(size)
1286
+ if b == b"":
1287
+ break
1288
+ buf += b
1289
+ assert buf == contents
1290
+ else:
1291
+ obj = {"a": 1}
1292
+
1293
+ with bf.BlobFile(path, write_mode, streaming=streaming) as w:
1294
+ json.dump(obj, w)
1295
+
1296
+ with bf.BlobFile(path, read_mode, streaming=streaming) as r:
1297
+ assert json.load(r) == obj
1298
+
1299
+
1300
+ @pytest.mark.parametrize("streaming", [True, False])
1301
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1302
+ def test_video(streaming, ctx):
1303
+ try:
1304
+ import av
1305
+ import imageio
1306
+ except ImportError:
1307
+ pytest.skip("av and imageio are required for this test")
1308
+
1309
+ rng = np.random.RandomState(0)
1310
+ shape = (256, 64, 64, 3)
1311
+ video_data = rng.randint(0, 256, size=np.prod(shape), dtype=np.uint8).reshape(shape)
1312
+
1313
+ with ctx() as path:
1314
+ with bf.BlobFile(path, mode="wb", streaming=streaming) as wf:
1315
+ with imageio.get_writer(
1316
+ wf,
1317
+ format="ffmpeg",
1318
+ quality=None,
1319
+ codec="libx264rgb",
1320
+ pixelformat="bgr24",
1321
+ output_params=["-f", "mp4", "-crf", "0"],
1322
+ ) as w:
1323
+ for frame in video_data:
1324
+ w.append_data(frame)
1325
+
1326
+ with bf.BlobFile(path, mode="rb", streaming=streaming) as rf:
1327
+ with imageio.get_reader(rf, format="ffmpeg", input_params=["-f", "mp4"]) as r:
1328
+ for idx, frame in enumerate(r):
1329
+ assert np.array_equal(frame, video_data[idx])
1330
+
1331
+ with bf.BlobFile(path, mode="rb", streaming=streaming) as rf:
1332
+ container = av.open(rf)
1333
+ stream = container.streams.video[0]
1334
+ for idx, frame in enumerate(container.decode(stream)):
1335
+ assert np.array_equal(frame.to_image(), video_data[idx])
1336
+
1337
+
1338
+ # this is pretty slow and docker will often run out of memory
1339
+ @pytest.mark.slow
1340
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1341
+ def test_large_file(ctx):
1342
+ contents = b"0" * 2**32
1343
+ with ctx() as path:
1344
+ with bf.BlobFile(path, "wb", streaming=True) as f:
1345
+ f.write(contents)
1346
+ with bf.BlobFile(path, "rb", streaming=True) as f:
1347
+ assert contents == f.read()
1348
+
1349
+
1350
+ def test_composite_objects():
1351
+ with _get_temp_gcs_path() as remote_path:
1352
+ with _get_temp_local_path() as local_path:
1353
+ contents = b"0" * 2 * 2**20
1354
+ with open(local_path, "wb") as f:
1355
+ f.write(contents)
1356
+
1357
+ def create_composite_file():
1358
+ sp.run(
1359
+ [
1360
+ "gsutil",
1361
+ "-o",
1362
+ "GSUtil:parallel_composite_upload_threshold=1M",
1363
+ "cp",
1364
+ local_path,
1365
+ remote_path,
1366
+ ],
1367
+ check=True,
1368
+ )
1369
+
1370
+ local_md5 = hashlib.md5(contents).hexdigest()
1371
+ create_composite_file()
1372
+ assert bf.stat(remote_path).md5 is None
1373
+ assert local_md5 == bf.md5(remote_path)
1374
+ assert bf.stat(remote_path).md5 == local_md5
1375
+ assert local_md5 == bf.md5(remote_path)
1376
+
1377
+ bf.remove(remote_path)
1378
+ create_composite_file()
1379
+ assert bf.stat(remote_path).md5 is None
1380
+
1381
+ with tempfile.TemporaryDirectory() as tmpdir:
1382
+ with bf.BlobFile(remote_path, "rb", cache_dir=tmpdir, streaming=False) as f:
1383
+ assert f.read() == contents
1384
+ assert bf.stat(remote_path).md5 == local_md5
1385
+
1386
+
1387
+ @pytest.mark.parametrize("ctx", [_get_temp_local_path, _get_temp_gcs_path, _get_temp_as_path])
1388
+ def test_md5(ctx):
1389
+ contents = b"meow!"
1390
+ meow_hash = hashlib.md5(contents).hexdigest()
1391
+
1392
+ with ctx() as path:
1393
+ _write_contents(path, contents)
1394
+ assert bf.md5(path) == meow_hash
1395
+ with bf.BlobFile(path, "wb") as f:
1396
+ f.write(contents)
1397
+ assert bf.md5(path) == meow_hash
1398
+ with bf.BlobFile(path, "wb") as f:
1399
+ f.write(contents)
1400
+ assert bf.md5(path) == meow_hash
1401
+
1402
+
1403
+ @pytest.mark.parametrize("ctx", [_get_temp_as_path])
1404
+ def test_azure_maybe_update_md5(ctx):
1405
+ contents = b"meow!"
1406
+ meow_hash = hashlib.md5(contents).hexdigest()
1407
+ alternative_contents = b"purr"
1408
+ purr_hash = hashlib.md5(alternative_contents).hexdigest()
1409
+
1410
+ with ctx() as path:
1411
+ _write_contents(path, contents)
1412
+ st = azure.maybe_stat(ops.default_context._conf, path)
1413
+ assert azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash)
1414
+ _write_contents(path, alternative_contents)
1415
+ assert not azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash)
1416
+ st = azure.maybe_stat(ops.default_context._conf, path)
1417
+ assert st.md5 == purr_hash
1418
+ bf.remove(path)
1419
+ assert not azure.maybe_update_md5(ops.default_context._conf, path, st.version, meow_hash)
1420
+
1421
+
1422
+ @pytest.mark.parametrize("ctx", [_get_temp_as_path])
1423
+ def test_azure_etags(ctx):
1424
+ contents = b"bark!"
1425
+ alternative_contents = b"ruff"
1426
+
1427
+ with ctx() as path:
1428
+ bf.BlobFile(path, "wb").write(contents)
1429
+ version = bf.stat(path).version
1430
+
1431
+ # test can write a bunch of times on correct version
1432
+ with bf.BlobFile(path, "wb", version=version) as f:
1433
+ # first time should work
1434
+ for _ in range(1000):
1435
+ f.write(alternative_contents)
1436
+
1437
+ version = bf.stat(path).version
1438
+ with bf.BlobFile(path, "wb", version=version) as f:
1439
+ # overwrite it again to match with later in test
1440
+ f.write(alternative_contents)
1441
+
1442
+ new_version = bf.stat(path).version
1443
+ assert new_version != version
1444
+ with pytest.raises(bf.VersionMismatch):
1445
+ with bf.BlobFile(path, "wb", version=version) as f:
1446
+ # second time should fail
1447
+ f.write(contents)
1448
+
1449
+ assert bf.BlobFile(path, "rb").read() == alternative_contents
1450
+
1451
+ bf.remove(path)
1452
+
1453
+
1454
+ @pytest.mark.parametrize("ctx", [_get_temp_as_path])
1455
+ def test_azure_etags_last_version(ctx):
1456
+ part1 = b"hello"
1457
+ part2 = b" world"
1458
+
1459
+ with ctx() as path:
1460
+ try:
1461
+ bf.remove(path)
1462
+ except FileNotFoundError:
1463
+ pass
1464
+
1465
+ with bf.BlobFile(path, "wb", streaming=True) as f:
1466
+ f.write(part1)
1467
+ # This is None if the file did not previously exist.
1468
+ assert bf.last_version_seen(f) is None
1469
+ f.write(part2)
1470
+ written_version = bf.last_version_seen(f)
1471
+ with bf.BlobFile(path, "rb", streaming=True) as f:
1472
+ assert f.read(len(part1)) == part1
1473
+ partial_read_version = bf.last_version_seen(f)
1474
+ assert partial_read_version is not None
1475
+ assert f.read() == part2
1476
+ read_version = bf.last_version_seen(f)
1477
+ assert partial_read_version == read_version
1478
+ assert written_version == read_version
1479
+
1480
+ bf.remove(path)
1481
+
1482
+ data1 = b"hi there"
1483
+ data2 = b"overwrite"
1484
+
1485
+ with bf.BlobFile(path, "wb", streaming=True) as f:
1486
+ f.write(data1)
1487
+ with bf.BlobFile(path, "wb", streaming=True) as f2:
1488
+ f2.write(data2)
1489
+ version1 = bf.last_version_seen(f)
1490
+ version2 = bf.last_version_seen(f2)
1491
+ assert version1 != version2
1492
+
1493
+ with pytest.raises(bf.VersionMismatch):
1494
+ with bf.BlobFile(path, "rb", streaming=True, version=version1) as f:
1495
+ assert f.read() == data1
1496
+
1497
+ with bf.BlobFile(path, "rb", streaming=True) as f:
1498
+ assert f.read() == data2
1499
+ read_version = bf.last_version_seen(f)
1500
+ assert read_version == version2
1501
+
1502
+ bf.remove(path)
1503
+
1504
+ with bf.BlobFile(path, "wb", streaming=True) as f:
1505
+ f.write(b"abcdefgh" * 1024)
1506
+ with bf.BlobFile(path, "rb", streaming=True, buffer_size=16) as f:
1507
+ assert f.read(16) == b"abcdefgh" * 2
1508
+ with bf.BlobFile(path, "wb", streaming=True) as g:
1509
+ g.write(b"ijklmnop" * 1024)
1510
+ with pytest.raises(bf.VersionMismatch):
1511
+ f.read(16)
1512
+
1513
+ bf.remove(path)
1514
+
1515
+
1516
+ @pytest.mark.parametrize("ctx", [_get_temp_as_path])
1517
+ def test_azure_buffer_error_finally(ctx):
1518
+ # Avoid BufferError: Existing exports of data: object cannot be re-sized
1519
+ # See https://github.com/blobfile/blobfile/pull/230
1520
+ @contextlib.contextmanager
1521
+ def trailer_file(fn: str):
1522
+ bfc = bf.create_context(azure_write_chunk_size=1024)
1523
+ with bfc.BlobFile(fn, "wb", streaming=True) as f:
1524
+ try:
1525
+ yield f
1526
+ finally:
1527
+ f.write(b"asdf" * 1024)
1528
+
1529
+ with ctx() as path:
1530
+ with trailer_file(path) as f:
1531
+ with unittest.mock.patch("blobfile._azure.execute_api_request") as mock:
1532
+ mock.side_effect = RuntimeError("asdf")
1533
+ f.write(b"asdf")
1534
+ with pytest.raises(RuntimeError):
1535
+ f.write(b"asdf" * 1024 * 2)
1536
+ assert mock.call_count == 1
1537
+
1538
+
1539
+ def test_azure_timestamp_parsing():
1540
+ timestamp = "Sun, 27 Sep 2009 18:41:57 GMT"
1541
+
1542
+ def ref_parse_timestamp(text: str) -> float:
1543
+ return datetime.datetime.strptime(
1544
+ text.replace("GMT", "Z"), "%a, %d %b %Y %H:%M:%S %z"
1545
+ ).timestamp()
1546
+
1547
+ assert ref_parse_timestamp(timestamp) == azure._parse_timestamp(timestamp)
1548
+
1549
+
1550
+ def _get_http_pool_id(q):
1551
+ q.put(id(ops.default_context._conf.get_http_pool()))
1552
+
1553
+
1554
+ def test_fork():
1555
+ q = mp.Queue()
1556
+ # this reference should keep the old http client alive in the child process
1557
+ # to ensure that a new one does not recycle the memory address
1558
+ http1 = ops.default_context._conf.get_http_pool()
1559
+ parent1 = id(http1)
1560
+ p = mp.Process(target=_get_http_pool_id, args=(q,))
1561
+ p.start()
1562
+ p.join()
1563
+ http2 = ops.default_context._conf.get_http_pool()
1564
+ parent2 = id(http2)
1565
+
1566
+ child = q.get()
1567
+ assert parent1 == parent2
1568
+ assert child != parent1
1569
+
1570
+
1571
+ def test_azure_public_container():
1572
+ for error, path in [
1573
+ (None, f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png"),
1574
+ (
1575
+ bf.Error,
1576
+ f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/private/test_cat.png",
1577
+ ), # an account that exists but with a non-public container
1578
+ (
1579
+ FileNotFoundError,
1580
+ f"https://{AS_INVALID_ACCOUNT}.blob.core.windows.net/publiccontainer/test_cat.png",
1581
+ ), # account that does not exist
1582
+ ]:
1583
+ ctx = contextlib.nullcontext()
1584
+ if error is not None:
1585
+ ctx = pytest.raises(error)
1586
+ with ctx:
1587
+ with bf.BlobFile(path, "rb") as f:
1588
+ contents = f.read()
1589
+ assert contents.startswith(AZURE_PUBLIC_URL_HEADER)
1590
+
1591
+
1592
+ def test_scandir_error():
1593
+ for error, path in [
1594
+ (None, AZURE_VALID_CONTAINER),
1595
+ (FileNotFoundError, AZURE_INVALID_CONTAINER),
1596
+ (FileNotFoundError, AZURE_INVALID_CONTAINER_NO_ACCOUNT),
1597
+ (bf.Error, f"https://{AS_EXTERNAL_ACCOUNT}.blob.core.windows.net/private"),
1598
+ ]:
1599
+ ctx = contextlib.nullcontext()
1600
+ if error is not None:
1601
+ ctx = pytest.raises(error)
1602
+ with ctx:
1603
+ print(path)
1604
+ list(bf.scandir(path))
1605
+
1606
+
1607
+ def test_windowed_file():
1608
+ with _get_temp_local_path() as path:
1609
+ with open(path, "wb") as f:
1610
+ f.write(b"meow")
1611
+
1612
+ with open(path, "rb") as f:
1613
+ f2 = common.WindowedFile(f, start=1, end=3)
1614
+ assert f2.read() == b"eo"
1615
+
1616
+ f2.seek(0)
1617
+ assert f2.read(1) + f2.read(1) + f2.read(1) == b"eo"
1618
+
1619
+ with pytest.raises(AssertionError):
1620
+ f2.seek(-1)
1621
+
1622
+ with pytest.raises(AssertionError):
1623
+ f2.seek(2)
1624
+
1625
+
1626
+ class Deadline:
1627
+ def __init__(self):
1628
+ self._deadline = None
1629
+
1630
+ def set_deadline(self, deadline: float) -> None:
1631
+ self._deadline = deadline
1632
+
1633
+ def get_deadline(self) -> float:
1634
+ return self._deadline
1635
+
1636
+
1637
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
1638
+ def test_deadline(ctx):
1639
+ contents = b"meow"
1640
+ with ctx() as path:
1641
+ _write_contents(path, contents)
1642
+ deadline = Deadline()
1643
+ bf_ctx = bf.create_context(get_deadline=deadline.get_deadline)
1644
+ deadline.set_deadline(time.time() + 5)
1645
+ with bf_ctx.BlobFile(path, "rb") as f:
1646
+ f.read()
1647
+ time.sleep(5)
1648
+ with pytest.raises(bf.DeadlineExceeded):
1649
+ with bf_ctx.BlobFile(path, "rb") as f:
1650
+ f.read()
1651
+ deadline.set_deadline(None)
1652
+ with bf_ctx.BlobFile(path, "rb") as f:
1653
+ f.read()
1654
+
1655
+
1656
+ def test_pickle_config():
1657
+ ctx = ops.create_context()
1658
+ c = ctx._conf
1659
+ pickle.dumps(c)
1660
+ c.get_http_pool()
1661
+ c2 = pickle.loads(pickle.dumps(c))
1662
+ c2.get_http_pool()
1663
+
1664
+
1665
+ @pytest.mark.parametrize("ctx", [_get_temp_gcs_path, _get_temp_as_path])
1666
+ def test_read_with_size(ctx):
1667
+ contents = b"meow!\npurr\n"
1668
+ with ctx() as path:
1669
+ path = bf.join(path, "a folder", "a.file")
1670
+ bf.makedirs(bf.dirname(path))
1671
+ with bf.BlobFile(path, "wb") as w:
1672
+ w.write(contents)
1673
+ with bf.BlobFile(path, "rb", file_size=1) as r:
1674
+ assert r.read() == contents[:1]
1675
+ assert r.tell() == 1
videollama2/lib/python3.10/site-packages/blobfile/_xml.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Slightly faster replacement for xmltodict
3
+ """
4
+
5
+ from typing import Optional, Any, Set, Union, Dict
6
+ from lxml import etree
7
+
8
+
9
+ Element = etree._Element # type: ignore
10
+
11
+
12
+ def parse(document: bytes, repeated_tags: Optional[Set[str]] = None) -> Dict[str, Any]:
13
+ """
14
+ Convert an XML document to a dictionary, like xmltodict.parse but with lxml
15
+ """
16
+ if repeated_tags is None:
17
+ repeated_tags = set()
18
+ root = etree.fromstring(document)
19
+ children = _recursive_dict(root, repeated_tags=repeated_tags)
20
+ return {root.tag: children}
21
+
22
+
23
+ def _recursive_dict(elem: Element, repeated_tags: Set[str]) -> Union[Dict[str, Any], Optional[str]]:
24
+ if len(elem) == 0:
25
+ return elem.text
26
+ else:
27
+ seen_tags = set()
28
+ result = {}
29
+ for child in elem:
30
+ if child.tag in repeated_tags:
31
+ child_list = result.setdefault(child.tag, [])
32
+ child_list.append(_recursive_dict(child, repeated_tags))
33
+ else:
34
+ assert (
35
+ child.tag not in seen_tags
36
+ ), f"Found repeated tag that was not in repeated_tags set: {child.tag}"
37
+ seen_tags.add(child.tag)
38
+ result[child.tag] = _recursive_dict(child, repeated_tags)
39
+ return result
40
+
41
+
42
+ def unparse(data: Dict[str, Any]) -> bytes:
43
+ """
44
+ Convert a dictionary into an XML document, like xmltodict.unparse but with lxml
45
+ """
46
+ root_keys = list(data.keys())
47
+ assert len(root_keys) == 1, f"Must be only one root element, found {root_keys}"
48
+ root = _create_tree(root_keys[0], data[root_keys[0]])
49
+ # xml_declaration=True doesn't work for some reason, it seems
50
+ # to use single quotes that azure doesn't like
51
+ return b'<?xml version="1.0" encoding="utf-8"?>\n' + etree.tostring(root, encoding="utf8")
52
+
53
+
54
+ def _create_tree(name: str, data: Dict[str, Any]) -> Element:
55
+ elem = etree.Element(name)
56
+ for k, v in data.items():
57
+ if isinstance(v, dict):
58
+ elem.append(_create_tree(k, v))
59
+ elif isinstance(v, list):
60
+ for item in v:
61
+ if isinstance(item, str):
62
+ se = etree.Element(k)
63
+ se.text = item
64
+ elem.append(se)
65
+ elif isinstance(item, dict):
66
+ elem.append(_create_tree(k, item))
67
+ else:
68
+ assert False, f"Invalid value item type: {type(item)}"
69
+ else:
70
+ assert isinstance(v, str) or v is None
71
+ se = etree.Element(k)
72
+ if v is None:
73
+ # match xmltodict's behavior and use <Elem></Elem> instead of <Elem />
74
+ se.text = ""
75
+ else:
76
+ se.text = v
77
+ elem.append(se)
78
+ return elem
videollama2/lib/python3.10/site-packages/blobfile/_xml_test.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from typing import Any, Dict
4
+ import xmltodict
5
+ from blobfile import _xml as xml
6
+
7
+ resp = b"""\
8
+ <?xml version="1.0" encoding="utf-8"?>
9
+ <EnumerationResults ContainerName="https://myaccount.blob.core.windows.net/mycontainer">
10
+ <MaxResults>4</MaxResults>
11
+ <Blobs>
12
+ <Blob>
13
+ <Name>blob1.txt</Name>
14
+ <Url>https://myaccount.blob.core.windows.net/mycontainer/blob1.txt</Url>
15
+ <Properties>
16
+ <Last-Modified>Sun, 27 Sep 2009 18:41:57 GMT</Last-Modified>
17
+ <Etag>0x8CAE7D55D050B8B</Etag>
18
+ <Content-Length>8</Content-Length>
19
+ <Content-Type>text/html</Content-Type>
20
+ <Content-Encoding />
21
+ <Content-Language>en-US</Content-Language>
22
+ <Content-MD5 />
23
+ <Cache-Control>no-cache</Cache-Control>
24
+ <BlobType>BlockBlob</BlobType>
25
+ <LeaseStatus>unlocked</LeaseStatus>
26
+ </Properties>
27
+ </Blob>
28
+ <Blob>
29
+ <Name>blob2.txt</Name>
30
+ <Url>https://myaccount.blob.core.windows.net/mycontainer/blob2.txt</Url>
31
+ <Properties>
32
+ <Last-Modified>Sun, 27 Sep 2009 12:18:50 GMT</Last-Modified>
33
+ <Etag>0x8CAE7D55CF6C339</Etag>
34
+ <Content-Length>100</Content-Length>
35
+ <Content-Type>text/html</Content-Type>
36
+ <Content-Encoding />
37
+ <Content-Language>en-US</Content-Language>
38
+ <Content-MD5 />
39
+ <Cache-Control>no-cache</Cache-Control>
40
+ <BlobType>BlockBlob</BlobType>
41
+ <LeaseStatus>unlocked</LeaseStatus>
42
+ </Properties>
43
+ </Blob>
44
+ <BlobPrefix>
45
+ <Name>myfolder/</Name>
46
+ </BlobPrefix>
47
+ <Blob>
48
+ <Name>newblob1.txt</Name>
49
+ <Url>https://myaccount.blob.core.windows.net/mycontainer/newblob1.txt</Url>
50
+ <Properties>
51
+ <Last-Modified>Sun, 27 Sep 2009 16:31:57 GMT</Last-Modified>
52
+ <Etag>0x8CAE7D55CF6C339</Etag>
53
+ <Content-Length>25</Content-Length>
54
+ <Content-Type>text/html</Content-Type>
55
+ <Content-Encoding />
56
+ <Content-Language>en-US</Content-Language>
57
+ <Content-MD5 />
58
+ <Cache-Control>no-cache</Cache-Control>
59
+ <BlobType>BlockBlob</BlobType>
60
+ <LeaseStatus>unlocked</LeaseStatus>
61
+ </Properties>
62
+ </Blob>
63
+ <BlobPrefix>
64
+ <Name>myfolder2/</Name>
65
+ </BlobPrefix>
66
+ </Blobs>
67
+ <NextMarker>newblob2.txt</NextMarker>
68
+ </EnumerationResults>
69
+ """
70
+
71
+
72
+ def remove_attributes(d: Dict[str, Any]) -> Dict[str, Any]:
73
+ result = {}
74
+ for k, v in d.items():
75
+ if k.startswith("@"):
76
+ continue
77
+ if isinstance(v, dict):
78
+ v = remove_attributes(v)
79
+ result[k] = v
80
+ return result
81
+
82
+
83
+ def xmltodict_parse(data: bytes) -> Dict[str, Any]:
84
+ parsed = xmltodict.parse(data.decode("utf8"))
85
+ # we don't support attributes in our parser since we don't use them anyway
86
+ return remove_attributes(parsed)
87
+
88
+
89
+ def xmltodict_unparse(d: Dict[str, Any]) -> bytes:
90
+ return xmltodict.unparse(d).encode("utf8")
91
+
92
+
93
+ def test_parse():
94
+ ref = xmltodict_parse(resp)
95
+ actual = xml.parse(resp, repeated_tags={"Blob", "BlobPrefix"})
96
+ json_ref = json.dumps(ref, sort_keys=True, indent=" ")
97
+ json_actual = json.dumps(actual, sort_keys=True, indent=" ")
98
+ print(json_ref)
99
+ print(json_actual)
100
+ assert json_ref == json_actual
101
+
102
+
103
+ def test_unparse():
104
+ body = {"BlockList": {"Latest": [str(i) for i in range(100)]}}
105
+ ref = xmltodict_unparse(body)
106
+ actual = xml.unparse(body)
107
+ print(ref)
108
+ print(actual)
109
+ assert ref == actual
110
+
111
+
112
+ def test_roundtrip():
113
+ ref_parsed = xmltodict_parse(resp)
114
+ ref_unparsed = xmltodict_unparse(ref_parsed)
115
+
116
+ actual_parsed = xml.parse(ref_unparsed, repeated_tags={"Blob", "BlobPrefix"})
117
+ assert ref_parsed == actual_parsed
118
+
119
+ actual_unparsed = xml.unparse(ref_parsed)
120
+ print()
121
+ print(ref_unparsed)
122
+ print(actual_unparsed)
123
+ assert ref_unparsed == actual_unparsed
124
+
125
+ assert ref_unparsed == xml.unparse(
126
+ xml.parse(xml.unparse(ref_parsed), repeated_tags={"Blob", "BlobPrefix"})
127
+ )
128
+
129
+
130
+ def main():
131
+ # benchmarking
132
+ doc = xmltodict_parse(resp)
133
+ doc2 = doc.copy()
134
+ doc2["EnumerationResults"]["Blobs"]["Blob"] = doc2["EnumerationResults"]["Blobs"]["Blob"] * 300
135
+ expanded_resp_utf8 = xmltodict_unparse(doc2)
136
+
137
+ start = time.perf_counter()
138
+ for _ in range(100):
139
+ xmltodict.parse(expanded_resp)
140
+ end = time.perf_counter()
141
+ print(f"xmltodict parse elapsed {end - start}")
142
+
143
+ start = time.perf_counter()
144
+ for _ in range(100):
145
+ lxml_parse(expanded_resp_utf8, repeated_tags={"Blob", "BlobPrefix"})
146
+ end = time.perf_counter()
147
+ print(f"lxml parse elapsed {end - start}")
148
+
149
+ start = time.perf_counter()
150
+ for _ in range(100):
151
+ xmltodict.unparse(doc2)
152
+ end = time.perf_counter()
153
+ print(f"xmltodict unparse elapsed {end - start}")
154
+
155
+ start = time.perf_counter()
156
+ for _ in range(100):
157
+ lxml_unparse(doc2)
158
+ end = time.perf_counter()
159
+ print(f"lxml unparse elapsed {end - start}")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
videollama2/lib/python3.10/site-packages/blobfile/py.typed ADDED
File without changes
videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This implementation of Markdown is licensed under the MIT License:
2
+
3
+ The MIT License
4
+
5
+ Copyright (c) 2012 Trent Mick
6
+ Copyright (c) 2010 ActiveState Software Inc.
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a
9
+ copy of this software and associated documentation files (the
10
+ "Software"), to deal in the Software without restriction, including
11
+ without limitation the rights to use, copy, modify, merge, publish,
12
+ distribute, sublicense, and/or sell copies of the Software, and to permit
13
+ persons to whom the Software is furnished to do so, subject to the
14
+ following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included
17
+ in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+
27
+
28
+ All files in a *source package* of markdown2 (i.e. those available on
29
+ pypi.python.org and the Google Code project "downloads" page) are under the
30
+ MIT license. However, in the *subversion repository* there are some files
31
+ (used for performance and testing purposes) that are under different licenses
32
+ as follows:
33
+
34
+ - perf/recipes.pprint
35
+
36
+ Python License. This file includes a number of real-world examples of
37
+ Markdown from the ActiveState Python Cookbook, used for doing some
38
+ performance testing of markdown2.py.
39
+
40
+ - test/php-markdown-cases/...
41
+ test/php-markdown-extra-cases/...
42
+
43
+ GPL. These are from the MDTest package announced here:
44
+ http://six.pairlist.net/pipermail/markdown-discuss/2007-July/000674.html
45
+
46
+ - test/markdown.py
47
+
48
+ GPL 2 or BSD. A copy (currently old) of Python-Markdown -- the other
49
+ Python Markdown implementation.
50
+
51
+ - test/markdown.php
52
+
53
+ BSD-style. This is PHP Markdown
54
+ (http://michelf.com/projects/php-markdown/).
55
+
56
+ - test/Markdown.pl: BSD-style
57
+
58
+ A copy of Perl Markdown (http://daringfireball.net/projects/markdown/).
59
+
videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/RECORD ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/markdown2,sha256=KkVDAWQ4bONPZiGBj3XK7q4noHU4G6Jgs0pp8GZyZ68,225
2
+ __pycache__/markdown2.cpython-310.pyc,,
3
+ markdown2-2.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
4
+ markdown2-2.5.0.dist-info/LICENSE.txt,sha256=-MfE1VRAnPYhuNZT2__7cZdF_Tb1xJuDBSWGSbQD75w,2313
5
+ markdown2-2.5.0.dist-info/METADATA,sha256=77fAG1WWkQYNiTeYHpP1qUGmL0vsCds5OJf7IfCFAz8,2168
6
+ markdown2-2.5.0.dist-info/RECORD,,
7
+ markdown2-2.5.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ markdown2-2.5.0.dist-info/WHEEL,sha256=WzZ8cwjh8l0jtULNjYq1Hpr-WCqCRgPr--TX4P5I1Wo,110
9
+ markdown2-2.5.0.dist-info/entry_points.txt,sha256=ZAfeiSjZzwRSLJYMNAPOV-cMgZhEAVdrjG_E3wF0kz4,46
10
+ markdown2-2.5.0.dist-info/top_level.txt,sha256=fDjZIsBNbTniMxzHsMuRyzfmvWbBOoUklf6ycVKreNc,10
11
+ markdown2.py,sha256=dPE0ONPHXlpGpAa66RUqH8Rmis0OcmRZ8a5LhOBH3m0,157356
videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/REQUESTED ADDED
File without changes
videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ markdown2 = markdown2:main
3
+
videollama2/lib/python3.10/site-packages/markdown2-2.5.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ markdown2
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Edinburgh Genome Foundry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: proglog
3
+ Version: 0.1.10
4
+ Summary: Log and progress bar manager for console, notebooks, web...
5
+ Author: Zulko
6
+ License: MIT
7
+ Keywords: logger log progress bar
8
+ Platform: UNKNOWN
9
+ License-File: LICENSE
10
+ Requires-Dist: tqdm
11
+
12
+ Proglog
13
+ =======
14
+
15
+ Proglog is a progress logging system for Python. It allows to build complex
16
+ libraries while giving the user control on the management of logs, callbacks and progress bars.
17
+
18
+
19
+ Infos
20
+ -----
21
+
22
+ **PIP installation:**
23
+
24
+ .. code:: bash
25
+
26
+ pip install proglog
27
+
28
+ **Github Page**
29
+
30
+ `<https://github.com/Edinburgh-Genome-Foundry/Proglog>`_
31
+
32
+ **License:** MIT, Copyright Edinburgh Genome Foundry
33
+
34
+
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ proglog-0.1.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ proglog-0.1.10.dist-info/LICENSE,sha256=akVjFR4jDJtNakzf3avomKdfddMyA9WHJ5aVV08efxY,1081
3
+ proglog-0.1.10.dist-info/METADATA,sha256=7HqXAeqQ_WotmBFY28nag6MAHWRdXYCY0x1Xmv49hKI,639
4
+ proglog-0.1.10.dist-info/RECORD,,
5
+ proglog-0.1.10.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ proglog-0.1.10.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
7
+ proglog-0.1.10.dist-info/top_level.txt,sha256=KeCzTcuXoZxru4GWsCpIwgVBfHdDrI0ujnDKu61sFXE,8
8
+ proglog/__init__.py,sha256=m68k-TnqoChy0FjkHWqSfPuEiQgl69Cfs-N4Kp7k-tU,302
9
+ proglog/__pycache__/__init__.cpython-310.pyc,,
10
+ proglog/__pycache__/proglog.cpython-310.pyc,,
11
+ proglog/__pycache__/version.cpython-310.pyc,,
12
+ proglog/proglog.py,sha256=qWQSpWM-pR_pyh5vrrlVBU094bkatfj9prbz5PJpK7U,13250
13
+ proglog/version.py,sha256=z0zCHFTcKSR0tJ6h5qrpNmRVP21QIPP8N0p7quCnnm0,23
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED ADDED
File without changes
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
videollama2/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ proglog
videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
videollama2/lib/python3.10/site-packages/pyarrow-17.0.0.dist-info/METADATA ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: pyarrow
3
+ Version: 17.0.0
4
+ Summary: Python library for Apache Arrow
5
+ Maintainer-email: Apache Arrow Developers <dev@arrow.apache.org>
6
+ License: Apache Software License
7
+ Project-URL: Homepage, https://arrow.apache.org/
8
+ Project-URL: Documentation, https://arrow.apache.org/docs/python
9
+ Project-URL: Repository, https://github.com/apache/arrow
10
+ Project-URL: Issues, https://github.com/apache/arrow/issues
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: ../LICENSE.txt
20
+ License-File: ../NOTICE.txt
21
+ Requires-Dist: numpy >=1.16.6
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest ; extra == 'test'
24
+ Requires-Dist: hypothesis ; extra == 'test'
25
+ Requires-Dist: cffi ; extra == 'test'
26
+ Requires-Dist: pytz ; extra == 'test'
27
+ Requires-Dist: pandas ; extra == 'test'
28
+
29
+ <!---
30
+ Licensed to the Apache Software Foundation (ASF) under one
31
+ or more contributor license agreements. See the NOTICE file
32
+ distributed with this work for additional information
33
+ regarding copyright ownership. The ASF licenses this file
34
+ to you under the Apache License, Version 2.0 (the
35
+ "License"); you may not use this file except in compliance
36
+ with the License. You may obtain a copy of the License at
37
+
38
+ http://www.apache.org/licenses/LICENSE-2.0
39
+
40
+ Unless required by applicable law or agreed to in writing,
41
+ software distributed under the License is distributed on an
42
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
43
+ KIND, either express or implied. See the License for the
44
+ specific language governing permissions and limitations
45
+ under the License.
46
+ -->
47
+
48
+ ## Python library for Apache Arrow
49
+
50
+ [![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)
51
+
52
+ This library provides a Python API for functionality provided by the Arrow C++
53
+ libraries, along with tools for Arrow integration and interoperability with
54
+ pandas, NumPy, and other software in the Python ecosystem.
55
+
56
+ ## Installing
57
+
58
+ Across platforms, you can install a recent version of pyarrow with the conda
59
+ package manager:
60
+
61
+ ```shell
62
+ conda install pyarrow -c conda-forge
63
+ ```
64
+
65
+ On Linux, macOS, and Windows, you can also install binary wheels from PyPI with
66
+ pip:
67
+
68
+ ```shell
69
+ pip install pyarrow
70
+ ```
71
+
72
+ If you encounter any issues importing the pip wheels on Windows, you may need
73
+ to install the [Visual C++ Redistributable for Visual Studio 2015][6].
74
+
75
+ ## Development
76
+
77
+ See [Python Development][2] in the documentation subproject.
78
+
79
+ ### Building the documentation
80
+
81
+ See [documentation build instructions][1] in the documentation subproject.
82
+
83
+ [1]: https://github.com/apache/arrow/blob/main/docs/source/developers/documentation.rst
84
+ [2]: https://github.com/apache/arrow/blob/main/docs/source/developers/python.rst
85
+ [3]: https://github.com/pandas-dev/pandas
86
+ [5]: https://arrow.apache.org/docs/latest/python/benchmarks.html
87
+ [6]: https://www.microsoft.com/en-us/download/details.aspx?id=48145
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/animate.cpython-310.pyc ADDED
Binary file (6.35 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/base.cpython-310.pyc ADDED
Binary file (8.34 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/container.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/drawing.cpython-310.pyc ADDED
Binary file (5.17 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/elementfactory.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/filters.cpython-310.pyc ADDED
Binary file (9.62 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/masking.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/mixins.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/params.cpython-310.pyc ADDED
Binary file (2.21 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/path.cpython-310.pyc ADDED
Binary file (3.16 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/pattern.cpython-310.pyc ADDED
Binary file (2.03 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/shapes.cpython-310.pyc ADDED
Binary file (5.45 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/utils.cpython-310.pyc ADDED
Binary file (7.17 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/validator2.cpython-310.pyc ADDED
Binary file (5.85 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/__pycache__/version.cpython-310.pyc ADDED
Binary file (226 Bytes). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/animate.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #coding:utf-8
3
+ # Author: mozman --<mozman@gmx.at>
4
+ # Purpose: animate elements
5
+ # Created: 31.10.2010
6
+ # Copyright (C) 2010, Manfred Moitzi
7
+ # License: MIT License
8
+
9
+ from svgwrite.base import BaseElement
10
+ from svgwrite.mixins import XLink
11
+ from svgwrite.utils import strlist, is_string
12
+
13
+
14
+ class Set(BaseElement, XLink):
15
+ """ The **set** element provides a simple means of just setting the value
16
+ of an attribute for a specified duration. It supports all attribute types,
17
+ including those that cannot reasonably be interpolated, such as string
18
+ and boolean values. The **set** element is non-additive. The additive and
19
+ accumulate attributes are not allowed, and will be ignored if specified.
20
+ """
21
+ elementname = 'set'
22
+
23
+ def __init__(self, href=None, **extra):
24
+ """ Set constructor.
25
+
26
+ :param href: target svg element, if **href** is not `None`; else
27
+ the target SVG Element is the parent SVG Element.
28
+ """
29
+ super(Set, self).__init__(**extra)
30
+ if href is not None:
31
+ self.set_href(href)
32
+
33
+ def get_xml(self):
34
+ self.update_id() # if href is an object - 'id' - attribute may be changed!
35
+ return super(Set, self).get_xml()
36
+
37
+ def set_target(self, attributeName, attributeType=None):
38
+ """
39
+ Set animation attributes :ref:`attributeName` and :ref:`attributeType`.
40
+ """
41
+ self['attributeName'] = attributeName
42
+ if attributeType is not None:
43
+ self['attributeType'] = attributeType
44
+
45
+
46
+ def set_event(self, onbegin=None, onend=None, onrepeat=None, onload=None):
47
+ """
48
+ Set animation attributes :ref:`onbegin`, :ref:`onend`, :ref:`onrepeat`
49
+ and :ref:`onload`.
50
+ """
51
+ if onbegin is not None:
52
+ self['onbegin'] = onbegin
53
+ if onend is not None:
54
+ self['onend'] = onend
55
+ if onrepeat is not None:
56
+ self['onrepeat'] = onrepeat
57
+ if onload is not None:
58
+ self['onload'] = onload
59
+
60
+ def set_timing(self, begin=None, end=None, dur=None, min=None, max=None,
61
+ restart=None, repeatCount=None, repeatDur=None):
62
+ """
63
+ Set animation attributes :ref:`begin`, :ref:`end`, :ref:`dur`,
64
+ :ref:`min`, :ref:`max`, :ref:`restart`, :ref:`repeatCount` and
65
+ :ref:`repeatDur`.
66
+ """
67
+ if begin is not None:
68
+ self['begin'] = begin
69
+ if end is not None:
70
+ self['end'] = end
71
+ if dur is not None:
72
+ self['dur'] = dur
73
+ if min is not None:
74
+ self['min'] = min
75
+ if max is not None:
76
+ self['max'] = max
77
+ if restart is not None:
78
+ self['restart'] = restart
79
+ if repeatCount is not None:
80
+ self['repeatCount'] = repeatCount
81
+ if repeatDur is not None:
82
+ self['repeatDur'] = repeatDur
83
+
84
+ def freeze(self):
85
+ """ Freeze the animation effect. (see also :ref:`fill <animateFill>`)
86
+ """
87
+ self['fill'] = 'freeze'
88
+
89
+ class AnimateMotion(Set):
90
+ """ The **animateMotion** element causes a referenced element to move
91
+ along a motion path.
92
+ """
93
+ elementname = 'animateMotion'
94
+
95
+ def __init__(self, path=None, href=None, **extra):
96
+ """
97
+ :param path: the motion path
98
+ :param href: target svg element, if **href** is not `None`; else
99
+ the target SVG Element is the parent SVG Element.
100
+ """
101
+ super(AnimateMotion, self).__init__(href=href, **extra)
102
+ if path is not None:
103
+ self['path'] = path
104
+
105
+ def set_value(self, path=None, calcMode=None, keyPoints=None, rotate=None):
106
+ """
107
+ Set animation attributes `path`, `calcMode`, `keyPoints` and `rotate`.
108
+ """
109
+ if path is not None:
110
+ self['path'] = path
111
+ if calcMode is not None:
112
+ self['calcMode'] = calcMode
113
+ if keyPoints is not None:
114
+ self['keyPoints'] = keyPoints
115
+ if rotate is not None:
116
+ self['rotate'] = rotate
117
+
118
+
119
+ class Animate(Set):
120
+ """ The **animate** element allows scalar attributes and properties to be
121
+ assigned different values over time .
122
+ """
123
+ elementname = 'animate'
124
+
125
+ def __init__(self, attributeName=None, values=None, href=None, **extra):
126
+ """
127
+ :param attributeName: name of the SVG Attribute to animate
128
+ :param values: interpolation values, `string` as `<semicolon-list>` or a python `list`
129
+ :param href: target svg element, if **href** is not `None`; else
130
+ the target SVG Element is the parent SVG Element.
131
+ """
132
+ super(Animate, self).__init__(href=href, **extra)
133
+ if values is not None:
134
+ self.set_value(values)
135
+ if attributeName is not None:
136
+ self.set_target(attributeName)
137
+
138
+ def set_value(self, values, calcMode=None, keyTimes=None, keySplines=None,
139
+ from_=None, to=None, by=None):
140
+ """
141
+ Set animation attributes :ref:`values`, :ref:`calcMode`, :ref:`keyTimes`,
142
+ :ref:`keySplines`, :ref:`from`, :ref:`to` and :ref:`by`.
143
+ """
144
+ if values is not None:
145
+ if not is_string(values):
146
+ values = strlist(values, ';')
147
+ self['values'] = values
148
+
149
+ if calcMode is not None:
150
+ self['calcMode'] = calcMode
151
+ if keyTimes is not None:
152
+ self['keyTimes'] = keyTimes
153
+ if keySplines is not None:
154
+ self['keySplines'] = keySplines
155
+ if from_ is not None:
156
+ self['from'] = from_
157
+ if to is not None:
158
+ self['to'] = to
159
+ if by is not None:
160
+ self['by'] = by
161
+
162
+
163
+ class AnimateColor(Animate):
164
+ """ The **animateColor** element specifies a color transformation over
165
+ time.
166
+ """
167
+ elementname = 'animateColor'
168
+
169
+
170
+ class AnimateTransform(Animate):
171
+ """ The **animateTransform** element animates a transformation attribute
172
+ on a target element, thereby allowing animations to control translation,
173
+ scaling, rotation and/or skewing.
174
+ """
175
+ elementname = 'animateTransform'
176
+ def __init__(self, transform, element=None, **extra):
177
+ """
178
+ :param element: target svg element, if element is not `None`; else
179
+ the target svg element is the parent svg element.
180
+ :param string transform: ``'translate | scale | rotate | skewX | skewY'``
181
+ """
182
+ super(AnimateTransform, self).__init__(element, **extra)
183
+ self['type'] = transform
videollama2/lib/python3.10/site-packages/svgwrite/base.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #coding:utf-8
3
+ # Author: mozman
4
+ # Purpose: svg base element
5
+ # Created: 08.09.2010
6
+ # Copyright (c) 2010-2020, Manfred Moitzi
7
+ # License: MIT License
8
+ """
9
+ The **BaseElement** is the root for all SVG elements.
10
+ """
11
+
12
+ from svgwrite.etree import etree
13
+
14
+ import copy
15
+
16
+ from svgwrite.params import Parameter
17
+ from svgwrite.utils import AutoID
18
+
19
+
20
+ class BaseElement(object):
21
+ """
22
+ The **BaseElement** is the root for all SVG elements. The SVG attributes
23
+ are stored in **attribs**, and the SVG subelements are stored in
24
+ **elements**.
25
+
26
+ """
27
+ elementname = 'baseElement'
28
+
29
+ def __init__(self, **extra):
30
+ """
31
+ :param extra: extra SVG attributes (keyword arguments)
32
+
33
+ * add trailing '_' to reserved keywords: ``'class_'``, ``'from_'``
34
+ * replace inner '-' by '_': ``'stroke_width'``
35
+
36
+
37
+ SVG attribute names will be checked, if **debug** is `True`.
38
+
39
+ workaround for removed **attribs** parameter in Version 0.2.2::
40
+
41
+ # replace
42
+ element = BaseElement(attribs=adict)
43
+
44
+ #by
45
+ element = BaseElement()
46
+ element.update(adict)
47
+
48
+ """
49
+ # the keyword 'factory' specifies the object creator
50
+ factory = extra.pop('factory', None)
51
+ if factory is not None:
52
+ # take parameter from 'factory'
53
+ self._parameter = factory._parameter
54
+ else:
55
+ # default parameter debug=True profile='full'
56
+ self._parameter = Parameter()
57
+
58
+ # override debug setting
59
+ debug = extra.pop('debug', None)
60
+ if debug is not None:
61
+ self._parameter.debug = debug
62
+
63
+ # override profile setting
64
+ profile = extra.pop('profile', None)
65
+ if profile is not None:
66
+ self._parameter.profile = profile
67
+
68
+ self.attribs = dict()
69
+ self.update(extra)
70
+ self.elements = list()
71
+
72
+ def update(self, attribs):
73
+ """ Update SVG Attributes from `dict` attribs.
74
+
75
+ Rules for keys:
76
+
77
+ 1. trailing '_' will be removed (``'class_'`` -> ``'class'``)
78
+ 2. inner '_' will be replaced by '-' (``'stroke_width'`` -> ``'stroke-width'``)
79
+
80
+ """
81
+ for key, value in attribs.items():
82
+ # remove trailing underscores
83
+ # and replace inner underscores
84
+ key = key.rstrip('_').replace('_', '-')
85
+ self.__setitem__(key, value)
86
+
87
+ def copy(self):
88
+ newobj = copy.copy(self) # shallow copy of object
89
+ newobj.attribs = copy.copy(self.attribs) # shallow copy of attributes
90
+ newobj.elements = copy.copy(self.elements) # shallow copy of subelements
91
+ if 'id' in newobj.attribs: # create a new 'id'
92
+ newobj['id'] = newobj.next_id()
93
+ return newobj
94
+
95
+ @property
96
+ def debug(self):
97
+ return self._parameter.debug
98
+
99
+ @property
100
+ def profile(self):
101
+ return self._parameter.profile
102
+
103
+ @property
104
+ def validator(self):
105
+ return self._parameter.validator
106
+
107
+ @validator.setter
108
+ def validator(self, value):
109
+ self._parameter.validator = value
110
+
111
+ @property
112
+ def version(self):
113
+ return self._parameter.get_version()
114
+
115
+ def set_parameter(self, parameter):
116
+ self._parameter = parameter
117
+
118
+ def next_id(self, value=None):
119
+ return AutoID.next_id(value)
120
+
121
+ def get_id(self):
122
+ """ Get the object `id` string, if the object does not have an `id`,
123
+ a new `id` will be created.
124
+
125
+ :returns: `string`
126
+ """
127
+ if 'id' not in self.attribs:
128
+ self.attribs['id'] = self.next_id()
129
+ return self.attribs['id']
130
+
131
+ def get_iri(self):
132
+ """
133
+ Get the `IRI` reference string of the object. (i.e., ``'#id'``).
134
+
135
+ :returns: `string`
136
+ """
137
+ return "#%s" % self.get_id()
138
+
139
+ def get_funciri(self):
140
+ """
141
+ Get the `FuncIRI` reference string of the object. (i.e. ``'url(#id)'``).
142
+
143
+ :returns: `string`
144
+ """
145
+ return "url(%s)" % self.get_iri()
146
+
147
+ def __getitem__(self, key):
148
+ """ Get SVG attribute by `key`.
149
+
150
+ :param string key: SVG attribute name
151
+ :return: SVG attribute value
152
+
153
+ """
154
+ return self.attribs[key]
155
+
156
+ def __setitem__(self, key, value):
157
+ """ Set SVG attribute by `key` to `value`.
158
+
159
+ :param string key: SVG attribute name
160
+ :param object value: SVG attribute value
161
+
162
+ """
163
+ # Attribute checking is only done by using the __setitem__() method or
164
+ # by self['attribute'] = value
165
+ if self.debug:
166
+ self.validator.check_svg_attribute_value(self.elementname, key, value)
167
+ self.attribs[key] = value
168
+
169
+ def add(self, element):
170
+ """ Add an SVG element as subelement.
171
+
172
+ :param element: append this SVG element
173
+ :returns: the added element
174
+
175
+ """
176
+ if self.debug:
177
+ self.validator.check_valid_children(self.elementname, element.elementname)
178
+ self.elements.append(element)
179
+ return element
180
+
181
+ def tostring(self):
182
+ """ Get the XML representation as unicode `string`.
183
+
184
+ :return: unicode XML string of this object and all its subelements
185
+
186
+ """
187
+ xml = self.get_xml()
188
+ # required for Python 2 support
189
+ xml_utf8_str = etree.tostring(xml, encoding='utf-8')
190
+ return xml_utf8_str.decode('utf-8')
191
+ # just Python 3: return etree.tostring(xml, encoding='unicode')
192
+
193
+ def _repr_svg_(self):
194
+ """ Show SVG in IPython, Jupyter Notebook, and Jupyter Lab
195
+
196
+ :return: unicode XML string of this object and all its subelements
197
+
198
+ """
199
+ return self.tostring()
200
+
201
+ def get_xml(self):
202
+ """ Get the XML representation as `ElementTree` object.
203
+
204
+ :return: XML `ElementTree` of this object and all its subelements
205
+
206
+ """
207
+ xml = etree.Element(self.elementname)
208
+ if self.debug:
209
+ self.validator.check_all_svg_attribute_values(self.elementname, self.attribs)
210
+ for attribute, value in sorted(self.attribs.items()):
211
+ # filter 'None' values
212
+ if value is not None:
213
+ value = self.value_to_string(value)
214
+ if value: # just add not empty attributes
215
+ xml.set(attribute, value)
216
+
217
+ for element in self.elements:
218
+ xml.append(element.get_xml())
219
+ return xml
220
+
221
+ def value_to_string(self, value):
222
+ """
223
+ Converts *value* into a <string> includes a value check, depending
224
+ on :attr:`self.debug` and :attr:`self.profile`.
225
+
226
+ """
227
+ if isinstance(value, (int, float)):
228
+ if self.debug:
229
+ self.validator.check_svg_type(value, 'number')
230
+ if isinstance(value, float) and self.profile == 'tiny':
231
+ value = round(value, 4)
232
+ return str(value)
233
+
234
+ def set_desc(self, title=None, desc=None):
235
+ """ Insert a **title** and/or a **desc** element as first subelement.
236
+ """
237
+ if desc is not None:
238
+ self.elements.insert(0, Desc(desc))
239
+ if title is not None:
240
+ self.elements.insert(0, Title(title))
241
+
242
+ def set_metadata(self, xmldata):
243
+ """
244
+ :param xmldata: an xml.etree.ElementTree - Element() object.
245
+ """
246
+ metadata = Metadata(xmldata)
247
+ if len(self.elements) == 0:
248
+ self.elements.append(metadata)
249
+ else:
250
+ pos = 0
251
+ while self.elements[pos].elementname in ('title', 'desc'):
252
+ pos += 1
253
+ if pos == len(self.elements):
254
+ self.elements.append(metadata)
255
+ return
256
+ if self.elements[pos].elementname == 'metadata':
257
+ self.elements[pos].xml.append(xmldata)
258
+ else:
259
+ self.elements.insert(pos, metadata)
260
+
261
+
262
+ class Title(object):
263
+ elementname = 'title'
264
+
265
+ def __init__(self, text):
266
+ self.xml = etree.Element(self.elementname)
267
+ self.xml.text = str(text)
268
+
269
+ def get_xml(self):
270
+ return self.xml
271
+
272
+
273
+ class Desc(Title):
274
+ elementname = 'desc'
275
+
276
+
277
+ class Metadata(Title):
278
+ elementname = 'metadata'
279
+
280
+ def __init__(self, xmldata):
281
+ """
282
+ :param xmldata: an xml.etree.ElementTree - Element() object.
283
+ """
284
+ self.xml = etree.Element('metadata')
285
+ self.xml.append(xmldata)
videollama2/lib/python3.10/site-packages/svgwrite/data/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/colors.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/full11.cpython-310.pyc ADDED
Binary file (34.5 kB). View file
 
videollama2/lib/python3.10/site-packages/svgwrite/data/__pycache__/pattern.cpython-310.pyc ADDED
Binary file (658 Bytes). View file