Spaces:
Build error
Build error
Create workflows/storage.py
Browse files- workflows/storage.py +55 -0
workflows/storage.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from prefect import task
|
| 2 |
+
from google.oauth2 import service_account
|
| 3 |
+
from googleapiclient.discovery import build
|
| 4 |
+
from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload
|
| 5 |
+
from config.settings import settings
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
import base64
|
| 8 |
+
|
| 9 |
+
@task(retries=2)
|
| 10 |
+
def upload_to_google_drive(image_data: str, filename: str, folder_id: str = None) -> str:
|
| 11 |
+
"""Upload image to Google Drive"""
|
| 12 |
+
|
| 13 |
+
# Parse credentials
|
| 14 |
+
credentials = service_account.Credentials.from_service_account_info(
|
| 15 |
+
settings.google_credentials_dict,
|
| 16 |
+
scopes=['https://www.googleapis.com/auth/drive.file']
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Build Drive service
|
| 20 |
+
service = build('drive', 'v3', credentials=credentials)
|
| 21 |
+
|
| 22 |
+
# Prepare file
|
| 23 |
+
if image_data.startswith('data:image'):
|
| 24 |
+
# Base64 data URL
|
| 25 |
+
header, encoded = image_data.split(',', 1)
|
| 26 |
+
image_bytes = base64.b64decode(encoded)
|
| 27 |
+
media = MediaIoBaseUpload(
|
| 28 |
+
BytesIO(image_bytes),
|
| 29 |
+
mimetype='image/png',
|
| 30 |
+
resumable=True
|
| 31 |
+
)
|
| 32 |
+
else:
|
| 33 |
+
# URL or file path - download first
|
| 34 |
+
import requests
|
| 35 |
+
response = requests.get(image_data)
|
| 36 |
+
media = MediaIoBaseUpload(
|
| 37 |
+
BytesIO(response.content),
|
| 38 |
+
mimetype='image/png',
|
| 39 |
+
resumable=True
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# File metadata
|
| 43 |
+
file_metadata = {
|
| 44 |
+
'name': filename,
|
| 45 |
+
'parents': [folder_id] if folder_id else []
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
# Upload
|
| 49 |
+
file = service.files().create(
|
| 50 |
+
body=file_metadata,
|
| 51 |
+
media_body=media,
|
| 52 |
+
fields='id, webViewLink'
|
| 53 |
+
).execute()
|
| 54 |
+
|
| 55 |
+
return file.get('webViewLink')
|