| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import base64 |
| 8 | import mimetypes |
| 9 | import os |
| 10 | |
| 11 | from llama_models.llama3.api.datatypes import URL |
| 12 | |
| 13 | |
| 14 | def data_url_from_file(file_path: str) -> URL: |
| 15 | if not os.path.exists(file_path): |
| 16 | raise FileNotFoundError(f"File not found: {file_path}") |
| 17 | |
| 18 | with open(file_path, "rb") as file: |
| 19 | file_content = file.read() |
| 20 | |
| 21 | base64_content = base64.b64encode(file_content).decode("utf-8") |
| 22 | mime_type, _ = mimetypes.guess_type(file_path) |
| 23 | |
| 24 | data_url = f"data:{mime_type};base64,{base64_content}" |
| 25 | |
| 26 | return URL(uri=data_url) |