Resolve media to base64 data plus MIME metadata. Args: strict: Raise on invalid or unreadable media instead of returning ``None`` where the resolver can safely ignore the reference. target_format: Optional output format for audio conversion.
(
self,
*,
strict: bool = False,
target_format: str | None = None,
preserve_mp3: bool = False,
default_mime_type: str | None = "image/jpeg",
)
| 764 | ).decode("utf-8") |
| 765 | |
| 766 | async def to_base64_data( |
| 767 | self, |
| 768 | *, |
| 769 | strict: bool = False, |
| 770 | target_format: str | None = None, |
| 771 | preserve_mp3: bool = False, |
| 772 | default_mime_type: str | None = "image/jpeg", |
| 773 | ) -> ResolvedMediaData | None: |
| 774 | """Resolve media to base64 data plus MIME metadata. |
| 775 | |
| 776 | Args: |
| 777 | strict: Raise on invalid or unreadable media instead of returning |
| 778 | ``None`` where the resolver can safely ignore the reference. |
| 779 | target_format: Optional output format for audio conversion. |
| 780 | preserve_mp3: Keep existing MP3 audio as MP3 when no target format is |
| 781 | provided; otherwise audio defaults to WAV. |
| 782 | default_mime_type: Fallback MIME type for legacy image base64 payloads |
| 783 | whose bytes cannot be identified. |
| 784 | """ |
| 785 | if self.media_type == "image": |
| 786 | async with self.as_path(target_format=target_format) as resolved: |
| 787 | try: |
| 788 | media_bytes = await asyncio.to_thread(resolved.read_bytes) |
| 789 | except OSError: |
| 790 | if strict: |
| 791 | raise |
| 792 | return None |
| 793 | |
| 794 | mime_type = await detect_image_mime_type_async( |
| 795 | media_bytes, |
| 796 | default_mime_type=None, |
| 797 | ) |
| 798 | if ( |
| 799 | not mime_type |
| 800 | and resolved.mime_type |
| 801 | and resolved.mime_type.startswith("image/") |
| 802 | ): |
| 803 | mime_type = resolved.mime_type |
| 804 | is_legacy_base64_ref = self.media_ref.startswith("base64://") |
| 805 | is_remote_or_data_ref = self.media_ref.startswith( |
| 806 | ("http://", "https://", "data:") |
| 807 | ) or is_file_uri(self.media_ref) |
| 808 | if not is_legacy_base64_ref and not is_remote_or_data_ref: |
| 809 | try: |
| 810 | _decode_base64_payload( |
| 811 | "".join(self.media_ref.split()), |
| 812 | error_message="invalid bare base64 media payload", |
| 813 | validate=True, |
| 814 | ) |
| 815 | except ValueError: |
| 816 | is_legacy_base64_ref = False |
| 817 | else: |
| 818 | is_legacy_base64_ref = True |
| 819 | if not mime_type and is_legacy_base64_ref: |
| 820 | mime_type = default_mime_type |
| 821 | if not mime_type: |
| 822 | if strict: |
| 823 | raise ValueError( |
no test coverage detected