@@ -152,12 +152,33 @@ def embeddable_uri(self) -> str:
152
152
153
153
@classmethod
154
154
def from_uri (cls , uri : str , ** kwargs ) -> 'Mime' :
155
+ if uri .startswith ('data:' ):
156
+ mime_type , content = cls ._parse_data_uri (uri )
157
+ return cls .class_from_mime_type (mime_type ).from_bytes (content , ** kwargs )
158
+
155
159
if cls is Mime :
156
160
content = cls .download (uri )
157
161
mime = from_buffer (content , mime = True ).lower ()
158
162
return cls .class_from_mime_type (mime )(uri = uri , content = content , ** kwargs )
159
163
return cls (uri = uri , content = None , ** kwargs )
160
164
165
+ @classmethod
166
+ def _parse_data_uri (cls , uri : str ) -> tuple [str , bytes ]:
167
+ """Returns the MIME type and content from the given data URI."""
168
+ assert uri .startswith ('data:' ), uri
169
+ mime_end_pos = uri .find (';' , 0 )
170
+ if mime_end_pos == - 1 :
171
+ raise ValueError (f'Invalid data URI: { uri !r} .' )
172
+ mime_type = uri [5 : mime_end_pos ].strip ().lower ()
173
+ encoding_end_pos = uri .find (',' , mime_end_pos + 1 )
174
+ if encoding_end_pos == - 1 :
175
+ raise ValueError (f'Invalid data URI: { uri !r} .' )
176
+ encoding = uri [mime_end_pos + 1 : encoding_end_pos ].strip ().lower ()
177
+ if encoding != 'base64' :
178
+ raise ValueError (f'Unsupported encoding: { encoding !r} .' )
179
+ base64_content = uri [encoding_end_pos + 1 :].strip ().encode ()
180
+ return mime_type , base64 .b64decode (base64_content )
181
+
161
182
@classmethod
162
183
def from_bytes (cls , content : bytes | str , ** kwargs ) -> 'Mime' :
163
184
if cls is Mime :
0 commit comments