Encode image or video file to base64 string. Args: media_file_path (str): Path to the image or video file Returns: str: Base64 encoded string with data URL prefix Raises: FileNotFoundError: If image/video file doesn't exist ValueError: If file is n
(media_file_path: str)
| 529 | |
| 530 | |
| 531 | def encode_media_to_base64(media_file_path: str) -> str: |
| 532 | """ |
| 533 | Encode image or video file to base64 string. |
| 534 | |
| 535 | Args: |
| 536 | media_file_path (str): Path to the image or video file |
| 537 | |
| 538 | Returns: |
| 539 | str: Base64 encoded string with data URL prefix |
| 540 | |
| 541 | Raises: |
| 542 | FileNotFoundError: If image/video file doesn't exist |
| 543 | ValueError: If file is not a valid format |
| 544 | """ |
| 545 | import base64 |
| 546 | import mimetypes |
| 547 | |
| 548 | # Expand user path |
| 549 | media_file_path = os.path.expanduser(media_file_path) |
| 550 | |
| 551 | if not os.path.exists(media_file_path): |
| 552 | raise FileNotFoundError(f'Image file not found: {media_file_path}') |
| 553 | |
| 554 | if not os.path.isfile(media_file_path): |
| 555 | raise ValueError(f'Path is not a file: {media_file_path}') |
| 556 | |
| 557 | # Get MIME type, with fallback for formats that may not be registered |
| 558 | # in the system's MIME database on some platforms (e.g. Linux servers, |
| 559 | # Docker containers). |
| 560 | mime_type, _ = mimetypes.guess_type(media_file_path) |
| 561 | if not mime_type: |
| 562 | mime_type = _FALLBACK_MIME_TYPES.get( |
| 563 | os.path.splitext(media_file_path)[1].lower()) |
| 564 | if not mime_type: |
| 565 | raise ValueError(f'File is not a valid format: {media_file_path}') |
| 566 | |
| 567 | # Read and encode file |
| 568 | with open(media_file_path, 'rb') as media_file: |
| 569 | image_data = media_file.read() |
| 570 | base64_data = base64.b64encode(image_data).decode('utf-8') |
| 571 | |
| 572 | # Return data URL format |
| 573 | return f'data:{mime_type};base64,{base64_data}' |