|
| 1 | +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import os |
| 16 | +from veadk.config import getenv |
| 17 | +from veadk.utils.logger import get_logger |
| 18 | +import tos |
| 19 | +import asyncio |
| 20 | +from typing import Union |
| 21 | +from pydantic import BaseModel, Field |
| 22 | +from typing import Any |
| 23 | +from urllib.parse import urlparse |
| 24 | +from datetime import datetime |
| 25 | + |
| 26 | +logger = get_logger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class TOSConfig(BaseModel): |
| 30 | + region: str = Field( |
| 31 | + default_factory=lambda: getenv("DATABASE_TOS_REGION"), |
| 32 | + description="TOS region", |
| 33 | + ) |
| 34 | + ak: str = Field( |
| 35 | + default_factory=lambda: getenv("VOLCENGINE_ACCESS_KEY"), |
| 36 | + description="Volcengine access key", |
| 37 | + ) |
| 38 | + sk: str = Field( |
| 39 | + default_factory=lambda: getenv("VOLCENGINE_SECRET_KEY"), |
| 40 | + description="Volcengine secret key", |
| 41 | + ) |
| 42 | + bucket_name: str = Field( |
| 43 | + default_factory=lambda: getenv("DATABASE_TOS_BUCKET"), |
| 44 | + description="TOS bucket name", |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +class VeTOS(BaseModel): |
| 49 | + config: TOSConfig = Field(default_factory=TOSConfig) |
| 50 | + |
| 51 | + def model_post_init(self, __context: Any) -> None: |
| 52 | + try: |
| 53 | + self._client = tos.TosClientV2( |
| 54 | + self.config.ak, |
| 55 | + self.config.sk, |
| 56 | + endpoint=f"tos-{self.config.region}.volces.com", |
| 57 | + region=self.config.region, |
| 58 | + ) |
| 59 | + logger.info("Connected to TOS successfully.") |
| 60 | + except Exception as e: |
| 61 | + logger.error(f"Client initialization failed:{e}") |
| 62 | + return None |
| 63 | + |
| 64 | + def create_bucket(self) -> bool: |
| 65 | + """If the bucket does not exist, create it""" |
| 66 | + try: |
| 67 | + self._client.head_bucket(self.config.bucket_name) |
| 68 | + logger.info(f"Bucket {self.config.bucket_name} already exists") |
| 69 | + return True |
| 70 | + except tos.exceptions.TosServerError as e: |
| 71 | + if e.status_code == 404: |
| 72 | + self._client.create_bucket( |
| 73 | + bucket=self.config.bucket_name, |
| 74 | + storage_class=tos.StorageClassType.Storage_Class_Standard, |
| 75 | + acl=tos.ACLType.ACL_Private, |
| 76 | + ) |
| 77 | + logger.info(f"Bucket {self.config.bucket_name} created successfully") |
| 78 | + return True |
| 79 | + except Exception as e: |
| 80 | + logger.error(f"Bucket creation failed: {str(e)}") |
| 81 | + return False |
| 82 | + |
| 83 | + def build_tos_url( |
| 84 | + self, user_id: str, app_name: str, session_id: str, data_path: str |
| 85 | + ) -> tuple[str, str]: |
| 86 | + """generate TOS object key""" |
| 87 | + parsed_url = urlparse(data_path) |
| 88 | + |
| 89 | + if parsed_url.scheme and parsed_url.scheme in ("http", "https", "ftp", "ftps"): |
| 90 | + file_name = os.path.basename(parsed_url.path) |
| 91 | + else: |
| 92 | + file_name = os.path.basename(data_path) |
| 93 | + |
| 94 | + timestamp: str = datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3] |
| 95 | + object_key: str = f"{app_name}-{user_id}-{session_id}/{timestamp}-{file_name}" |
| 96 | + tos_url: str = f"https://{self.config.bucket_name}.tos-{self.config.region}.volces.com/{object_key}" |
| 97 | + |
| 98 | + return object_key, tos_url |
| 99 | + |
| 100 | + def upload( |
| 101 | + self, |
| 102 | + object_key: str, |
| 103 | + data: Union[str, bytes], |
| 104 | + ): |
| 105 | + if isinstance(data, str): |
| 106 | + data_type = "file" |
| 107 | + elif isinstance(data, bytes): |
| 108 | + data_type = "bytes" |
| 109 | + else: |
| 110 | + error_msg = f"Upload failed: data type error. Only str (file path) and bytes are supported, got {type(data)}" |
| 111 | + logger.error(error_msg) |
| 112 | + raise ValueError(error_msg) |
| 113 | + if data_type == "file": |
| 114 | + return asyncio.to_thread(self._do_upload_file, object_key, data) |
| 115 | + elif data_type == "bytes": |
| 116 | + return asyncio.to_thread(self._do_upload_bytes, object_key, data) |
| 117 | + |
| 118 | + def _do_upload_bytes(self, object_key: str, bytes: bytes) -> bool: |
| 119 | + try: |
| 120 | + if not self._client: |
| 121 | + return False |
| 122 | + if not self.create_bucket(): |
| 123 | + return False |
| 124 | + self._client.put_object( |
| 125 | + bucket=self.config.bucket_name, key=object_key, content=bytes |
| 126 | + ) |
| 127 | + logger.debug(f"Upload success, object_key: {object_key}") |
| 128 | + self._close() |
| 129 | + return True |
| 130 | + except Exception as e: |
| 131 | + logger.error(f"Upload failed: {e}") |
| 132 | + self._close() |
| 133 | + return False |
| 134 | + |
| 135 | + def _do_upload_file(self, object_key: str, file_path: str) -> bool: |
| 136 | + try: |
| 137 | + if not self._client: |
| 138 | + return False |
| 139 | + if not self.create_bucket(): |
| 140 | + return False |
| 141 | + |
| 142 | + self._client.put_object_from_file( |
| 143 | + bucket=self.config.bucket_name, key=object_key, file_path=file_path |
| 144 | + ) |
| 145 | + self._close() |
| 146 | + logger.debug(f"Upload success, object_key: {object_key}") |
| 147 | + return True |
| 148 | + except Exception as e: |
| 149 | + logger.error(f"Upload failed: {e}") |
| 150 | + self._close() |
| 151 | + return False |
| 152 | + |
| 153 | + def download(self, object_key: str, save_path: str) -> bool: |
| 154 | + """download image from TOS""" |
| 155 | + try: |
| 156 | + object_stream = self._client.get_object(self.config.bucket_name, object_key) |
| 157 | + |
| 158 | + save_dir = os.path.dirname(save_path) |
| 159 | + if save_dir and not os.path.exists(save_dir): |
| 160 | + os.makedirs(save_dir, exist_ok=True) |
| 161 | + |
| 162 | + with open(save_path, "wb") as f: |
| 163 | + for chunk in object_stream: |
| 164 | + f.write(chunk) |
| 165 | + |
| 166 | + logger.debug(f"Image download success, saved to: {save_path}") |
| 167 | + return True |
| 168 | + |
| 169 | + except Exception as e: |
| 170 | + logger.error(f"Image download failed: {str(e)}") |
| 171 | + |
| 172 | + return False |
| 173 | + |
| 174 | + def _close(self): |
| 175 | + if self._client: |
| 176 | + self._client.close() |
0 commit comments