MCPcopy Create free account
hub / github.com/AstrBotDevs/AstrBot / to_base64_data

Method to_base64_data

astrbot/core/utils/media_utils.py:766–849  ·  view source on GitHub ↗

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",
    )

Source from the content-addressed store, hash-verified

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(

Callers 8

to_data_urlMethod · 0.95
_parse_to_discordMethod · 0.45
assemble_contextMethod · 0.45
prepare_audio_inputFunction · 0.45

Calls 9

as_pathMethod · 0.95
is_file_uriFunction · 0.85
_decode_base64_payloadFunction · 0.85
describe_media_refFunction · 0.85
ResolvedMediaDataClass · 0.85
startswithMethod · 0.80
decodeMethod · 0.80
read_bytesMethod · 0.80

Tested by

no test coverage detected