|
12 | 12 | from botocore.awsrequest import AWSRequest |
13 | 13 | from botocore.credentials import Credentials |
14 | 14 |
|
| 15 | +try: |
| 16 | + from google.cloud import storage as _gcs_storage |
| 17 | +except ImportError: # pragma: no cover - optional dependency, install the "gcs" extra |
| 18 | + _gcs_storage = None |
| 19 | + |
15 | 20 | load_dotenv() |
16 | 21 |
|
17 | 22 | MIME_TO_FORMAT: Dict[str, List[str]] = { |
@@ -69,6 +74,19 @@ def get_s3_bucket_uri() -> str: |
69 | 74 | return s3_uri |
70 | 75 |
|
71 | 76 |
|
| 77 | +def resolve_upload_backend() -> str: |
| 78 | + """Decide which storage backend upload_image() should use. |
| 79 | +
|
| 80 | + ``IMAGE_UPLOAD_BACKEND`` ("s3" or "gcs") wins when set to a known value. |
| 81 | + Otherwise the presence of ``GCS_BUCKET`` selects GCS, and S3 is the default |
| 82 | + so existing deployments keep working unchanged. |
| 83 | + """ |
| 84 | + backend = (os.getenv('IMAGE_UPLOAD_BACKEND') or '').strip().lower() |
| 85 | + if backend in ('s3', 'gcs'): |
| 86 | + return backend |
| 87 | + return 'gcs' if os.getenv('GCS_BUCKET') else 's3' |
| 88 | + |
| 89 | + |
72 | 90 | def get_aws_signed_request(full_url, buffer, mime_type): |
73 | 91 | credentials = Credentials( |
74 | 92 | access_key=os.environ['AWS_ACCESS_KEY_ID'], |
@@ -113,57 +131,97 @@ def get_aws_signed_request(full_url, buffer, mime_type): |
113 | 131 | return aws_request |
114 | 132 |
|
115 | 133 |
|
| 134 | +def _upload_s3(folder_name: str, filename: str, data: bytes, mime_type: str) -> str: |
| 135 | + """Upload bytes to S3 with a SigV4-signed PUT and return the object URL.""" |
| 136 | + base_url: str = get_s3_bucket_uri() |
| 137 | + full_url = os.path.join(base_url, folder_name, filename) |
| 138 | + |
| 139 | + aws_request = get_aws_signed_request(full_url, data, mime_type).prepare() |
| 140 | + |
| 141 | + response: requests.Response = requests.request( |
| 142 | + method=aws_request.method, |
| 143 | + url=aws_request.url, |
| 144 | + data=aws_request.body, |
| 145 | + headers=aws_request.headers, |
| 146 | + timeout=30 |
| 147 | + ) |
| 148 | + |
| 149 | + if response.status_code != 200: |
| 150 | + raise ImageUploadError( |
| 151 | + f"Upload failed with status code {response.status_code}: {response.text}" |
| 152 | + ) |
| 153 | + |
| 154 | + return full_url |
| 155 | + |
| 156 | + |
| 157 | +def _upload_gcs(folder_name: str, filename: str, data: bytes, mime_type: str) -> str: |
| 158 | + """Upload bytes to Google Cloud Storage and return the object URL. |
| 159 | +
|
| 160 | + Authenticates with Application Default Credentials (the runtime service |
| 161 | + account on Cloud Run / GKE / GCE) -- no static keys. Set ``GCS_BUCKET`` to |
| 162 | + the target bucket and, optionally, ``GCS_PUBLIC_BASE_URL`` to override the |
| 163 | + returned URL's host (e.g. a CDN or custom domain). |
| 164 | + """ |
| 165 | + if _gcs_storage is None: |
| 166 | + raise ImageUploadError( |
| 167 | + "google-cloud-storage is not installed; install lf_toolkit with the " |
| 168 | + "'gcs' extra to use IMAGE_UPLOAD_BACKEND=gcs" |
| 169 | + ) |
| 170 | + |
| 171 | + bucket_name: Optional[str] = os.getenv('GCS_BUCKET') |
| 172 | + if not bucket_name: |
| 173 | + raise MissingEnvironmentVariableError( |
| 174 | + "GCS_BUCKET environment variable is not set" |
| 175 | + ) |
| 176 | + |
| 177 | + blob_name = f"{folder_name}/{filename}" |
| 178 | + client = _gcs_storage.Client() |
| 179 | + blob = client.bucket(bucket_name).blob(blob_name) |
| 180 | + blob.upload_from_string(data, content_type=mime_type) |
| 181 | + |
| 182 | + base_url = os.getenv('GCS_PUBLIC_BASE_URL', 'https://storage.googleapis.com').rstrip('/') |
| 183 | + return f"{base_url}/{bucket_name}/{blob_name}" |
| 184 | + |
| 185 | + |
116 | 186 | def upload_image(img: Image.Image, folder_name: str) -> str: |
117 | | - """Upload PIL image with comprehensive MIME type validation |
| 187 | + """Upload a PIL image to the configured storage backend. |
| 188 | +
|
| 189 | + The backend is chosen by :func:`resolve_upload_backend` (env var |
| 190 | + ``IMAGE_UPLOAD_BACKEND=s3|gcs``, else auto-detected from ``GCS_BUCKET`` / |
| 191 | + ``S3_BUCKET_URI``, defaulting to S3). |
118 | 192 |
|
119 | 193 | Args: |
120 | | - folder_name: name of folder to save image |
121 | 194 | img: PIL Image object to upload |
| 195 | + folder_name: name of the folder/prefix to store the image under |
122 | 196 |
|
123 | 197 | Returns: |
124 | | - JSON response from the server as a dictionary |
| 198 | + The public URL of the uploaded object |
125 | 199 |
|
126 | 200 | Raises: |
127 | 201 | InvalidMimeTypeError: If MIME type validation fails |
128 | | - MissingEnvironmentVariableError: If S3_BUCKET_URI is not set |
| 202 | + MissingEnvironmentVariableError: If required env vars are not set |
129 | 203 | ImageUploadError: If upload fails for any reason |
130 | 204 | """ |
131 | 205 | try: |
132 | | - # Get URL from environment variable |
133 | | - base_url: str = get_s3_bucket_uri() |
134 | | - |
135 | 206 | filename: str = generate_file_name(img) |
136 | 207 |
|
137 | | - full_url = os.path.join(base_url, folder_name, filename) |
138 | | - |
139 | 208 | if img.format is None: |
140 | 209 | img.format = 'PNG' |
141 | 210 |
|
142 | 211 | mime_type = FORMAT_TO_MIME[img.format.upper()] |
143 | 212 |
|
144 | 213 | buffer: BytesIO = BytesIO() |
145 | | - img_format: str = img.format if img.format else 'PNG' |
146 | | - img.save(buffer, format=img_format) |
147 | | - buffer.seek(0) |
148 | | - |
149 | | - aws_request = get_aws_signed_request(full_url, buffer, mime_type).prepare() |
150 | | - |
151 | | - response: requests.Response = requests.request( |
152 | | - method=aws_request.method, |
153 | | - url=aws_request.url, |
154 | | - data=aws_request.body, |
155 | | - headers=aws_request.headers, |
156 | | - timeout=30 |
157 | | - ) |
158 | | - |
159 | | - if response.status_code != 200: |
160 | | - raise ImageUploadError( |
161 | | - f"Upload failed with status code {response.status_code}: {response.text}" |
162 | | - ) |
| 214 | + img.save(buffer, format=img.format) |
| 215 | + data: bytes = buffer.getvalue() |
163 | 216 |
|
164 | | - return full_url |
| 217 | + backend = resolve_upload_backend() |
| 218 | + if backend == 'gcs': |
| 219 | + return _upload_gcs(folder_name, filename, data, mime_type) |
| 220 | + return _upload_s3(folder_name, filename, data, mime_type) |
165 | 221 |
|
166 | | - except (InvalidMimeTypeError, MissingEnvironmentVariableError): |
| 222 | + except ImageUploadError: |
| 223 | + # InvalidMimeTypeError / MissingEnvironmentVariableError / backend errors |
| 224 | + # already carry a useful message -- propagate as-is. |
167 | 225 | raise |
168 | 226 | except requests.exceptions.RequestException as e: |
169 | 227 | raise ImageUploadError(f"Network error: {str(e)}") |
|
0 commit comments