-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path__init__.py
More file actions
211 lines (177 loc) · 6.36 KB
/
__init__.py
File metadata and controls
211 lines (177 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import mimetypes
import re
import sys
import textwrap
from base64 import b64decode as decode64
from base64 import b64encode as encode64
from typing import Any, Dict, MutableMapping, Optional, Tuple, TypeVar, Union
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
from urllib.parse import quote, unquote
from cached_property import cached_property
from .exceptions import InvalidCharset, InvalidDataURI, InvalidMimeType
T = TypeVar("T")
MIMETYPE_REGEX = r"[\w]+\/[\w\-\+\.]+"
_MIMETYPE_RE = re.compile("^{}$".format(MIMETYPE_REGEX))
CHARSET_REGEX = r"[\w\-\+\.]+"
_CHARSET_RE = re.compile("^{}$".format(CHARSET_REGEX))
DATA_URI_REGEX = (
r"data:"
+ r"(?P<mimetype>{})?".format(MIMETYPE_REGEX)
+ r"(?:\;name\=(?P<name>[\w\.\-%!*'~\(\)]+))?"
+ r"(?:\;charset\=(?P<charset>{}))?".format(CHARSET_REGEX)
+ r"(?P<base64>\;base64)?"
+ r",(?P<data>.*)"
)
_DATA_URI_RE = re.compile(r"^{}$".format(DATA_URI_REGEX), re.DOTALL)
class DataURI(str):
@classmethod
def make(
cls,
mimetype: Optional[str],
charset: Optional[str],
base64: Optional[bool],
data: Union[str, bytes],
) -> Self:
parts = ["data:"]
if mimetype is not None:
if not _MIMETYPE_RE.match(mimetype):
raise InvalidMimeType("Invalid mimetype: %r" % mimetype)
parts.append(mimetype)
if charset is not None:
if not _CHARSET_RE.match(charset):
raise InvalidCharset("Invalid charset: %r" % charset)
parts.extend([";charset=", charset])
if base64:
parts.append(";base64")
_charset = charset or "utf-8"
if isinstance(data, bytes):
_data = data
else:
_data = bytes(data, _charset)
encoded_data = encode64(_data).decode(_charset).strip()
else:
encoded_data = quote(data)
parts.extend([",", encoded_data])
return cls("".join(parts))
@classmethod
def from_file(
cls,
filename: str,
charset: Optional[str] = None,
base64: Optional[bool] = True,
mimetype: Optional[str] = None,
) -> Self:
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename, strict=False)
with open(filename, "rb") as fp:
data = fp.read()
return cls.make(mimetype, charset, base64, data)
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
uri = super(DataURI, cls).__new__(cls, *args, **kwargs)
uri._parse # Trigger any ValueErrors on instantiation.
return uri
def __repr__(self) -> str:
truncated = str(self)
if len(truncated) > 80:
truncated = truncated[:79] + "…"
return "DataURI(%s)" % (truncated,)
def wrap(self, width: int = 76) -> str:
return "\n".join(textwrap.wrap(self, width, break_on_hyphens=False))
@property
def mimetype(self) -> Optional[str]:
return self._parse[0]
@property
def name(self) -> Optional[str]:
name = self._parse[1]
if name is not None:
return unquote(name)
return name
@property
def charset(self) -> Optional[str]:
return self._parse[2]
@property
def is_base64(self) -> bool:
return self._parse[3]
@property
def data(self) -> bytes:
return self._parse[4]
@property
def text(self) -> str:
if self.charset is None:
raise InvalidCharset("DataURI has no encoding set.")
return self.data.decode(self.charset)
@property
def is_valid(self) -> bool:
match = _DATA_URI_RE.match(self)
if not match:
return False
return True
@cached_property
def _parse(
self,
) -> Tuple[Optional[str], Optional[str], Optional[str], bool, bytes]:
match = _DATA_URI_RE.match(self)
if match is None:
raise InvalidDataURI("Not a valid data URI: %r" % self)
mimetype = match.group("mimetype") or None
name = match.group("name") or None
charset = match.group("charset") or None
_charset = charset or "utf-8"
if match.group("base64"):
_data = bytes(match.group("data"), _charset)
data = decode64(_data)
else:
data = bytes(unquote(match.group("data")), _charset)
return mimetype, name, charset, bool(match.group("base64")), data
# Pydantic methods
@classmethod
def __get_validators__(cls):
# one or more validators may be yielded which will be called in the
# order to validate the input, each validator will receive as an input
# the value returned from the previous validator
yield cls.validate
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: Any) -> Any:
from pydantic_core import core_schema
return core_schema.no_info_after_validator_function(cls, handler(str))
@classmethod
def validate(
cls,
value: str,
values: Optional[MutableMapping[str, Any]] = None,
config: Any = None,
field: Any = None,
**kwargs: Any,
) -> Self:
if not isinstance(value, str):
raise TypeError("string required")
m = cls(value)
if not m.is_valid:
raise ValueError("invalid data-uri format")
return m
@classmethod
def __get_pydantic_json_schema__(
cls, core_schema: MutableMapping[str, Any], handler: Any
) -> Any:
json_schema = handler(core_schema)
json_schema = handler.resolve_ref_schema(json_schema)
json_schema["examples"] = [
"data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"
]
json_schema["pattern"] = DATA_URI_REGEX
json_schema["type"] = "string"
json_schema["title"] = "DataURI"
return json_schema
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
# __modify_schema__ should mutate the dict it receives in place,
# the returned value will be ignored
field_schema.update(
pattern=DATA_URI_REGEX,
examples=[
"data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"
],
)