Spaces:
Running
Running
# s3_utils.py | |
import os | |
import datetime | |
import pathlib | |
import boto3 | |
from pathlib import Path | |
# βββ GLOBAL STATE βββββββββββββββββββββββββββββββββββββββ | |
uploaded_files = set() | |
last_reset = datetime.datetime.now() | |
# boto3 picks up AWS_* from env | |
s3 = boto3.client("s3", region_name=os.environ["AWS_DEFAULT_REGION"]) | |
BUCKET_NAME = os.environ["AWS_BUCKET_NAME"] | |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
def imagine(local_path: str, age: int) -> str: | |
global last_reset, uploaded_files | |
try: | |
now = datetime.datetime.now() | |
# 1) reset once per hour | |
if now - last_reset >= datetime.timedelta(hours=1): | |
print("Resetting uploaded files set") | |
uploaded_files.clear() | |
last_reset = now | |
# 2) skip the three built-in examples by name | |
if Path(local_path).name in ("girl.jpg", "man.jpg", "trump.jpg"): | |
print(f"Skipping upload for built-in example: {local_path}") | |
return None | |
basename = pathlib.Path(local_path).name | |
if basename in uploaded_files: | |
print(f"Skipping upload for already seen file: {basename}") | |
return None | |
today = now.strftime("%Y-%m-%d") | |
ts = now.strftime("%H%M%S") | |
stem = pathlib.Path(local_path).stem | |
ext = pathlib.Path(local_path).suffix | |
key = f"{today}/{age}_{ts}_{stem}{ext}" | |
s3.upload_file(Filename=local_path, Bucket=BUCKET_NAME, Key=key) | |
uploaded_files.add(basename) | |
print(f"Uploaded {local_path} to s3://{BUCKET_NAME}/{key}") | |
return key | |
except Exception as e: | |
print(f"Error uploading: {e}") | |
return None | |