import os import sys import time import uuid import requests import boto3 import mimetypes from dotenv import load_dotenv # Load .env file from the directory of this module env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env') load_dotenv(env_path) AWS_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY") AWS_REGION = os.getenv("AWS_REGION") AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME") IMAGE_API_BASE_URL = os.getenv("IMAGE_API_BASE_URL") API_KEY = os.getenv("API_KEY") def get_auth_headers(api_key=None, content_type="application/json"): """ Construct HTTP headers including Bearer Authorization token. """ key = api_key or API_KEY headers = {} if content_type: headers["Content-Type"] = content_type if key: headers["Authorization"] = f"Bearer {key}" return headers def upload_file_to_s3(local_path, bucket=None, key=None): """ Upload a local file to S3 with ACL='public-read' so the external API can access it. Returns (s3_url, key). """ bucket = bucket or AWS_BUCKET_NAME if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY: raise ValueError("AWS_S3_ACCESS_KEY_ID or AWS_S3_SECRET_ACCESS_KEY is not configured in .env.") if not key: file_ext = os.path.splitext(local_path)[1] or ".png" key = f"temp/{uuid.uuid4()}{file_ext}" print(f"[*] Uploading '{local_path}' to S3 bucket '{bucket}' with key '{key}'...") s3_client = boto3.client( 's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION ) content_type, _ = mimetypes.guess_type(local_path) if not content_type: content_type = 'image/png' s3_client.upload_file( local_path, bucket, key, ExtraArgs={'ACL': 'public-read', 'ContentType': content_type} ) s3_url = f"https://{bucket}.s3.{AWS_REGION}.amazonaws.com/{key}" print(f"[+] Uploaded successfully. S3 public URL: {s3_url}") return s3_url, key def delete_file_from_s3(bucket=None, key=None): """ Cleans up the uploaded file from S3. """ bucket = bucket or AWS_BUCKET_NAME if not key: return print(f"[*] Cleaning up temporary file from S3: {key}") try: s3_client = boto3.client( 's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION ) s3_client.delete_object(Bucket=bucket, Key=key) print("[+] Temporary file deleted from S3 successfully.") except Exception as e: print(f"[!] Failed to delete temporary S3 object: {e}") def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10): """ Polls the task status with a timeout. """ base_url = api_base_url or IMAGE_API_BASE_URL status_url = f"{base_url}/v1/media/status" start_time = time.time() print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...") headers = get_auth_headers(api_key=api_key, content_type=None) while True: elapsed = time.time() - start_time if elapsed > timeout_seconds: raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.") try: response = requests.get(status_url, params={"task_id": task_id}, headers=headers) response.raise_for_status() res_json = response.json() # Support both flat and nested responses for task status data = res_json if "data" in res_json and isinstance(res_json["data"], dict): if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]): data = res_json["data"] state = data.get("state") is_final = data.get("is_final", False) progress = data.get("progress", "0%") status_text = data.get("status", "") print(f"[*] [Elapsed: {int(elapsed)}s] State: {state} ({status_text}), Progress: {progress}") if is_final: if state == "success": result_url = data.get("result_url") if not result_url: raise ValueError("Task finished with success state, but result_url is empty.") return result_url else: error_msg = data.get("error", "Unknown error") raise RuntimeError(f"Task failed with state '{state}': {error_msg}") except Exception as e: print(f"[!] Error querying task status: {e}") time.sleep(poll_interval) def download_image(url, output_path): """ Downloads the final image from the given URL and saves it locally. """ print(f"[*] Downloading result image from: {url}") response = requests.get(url, stream=True) response.raise_for_status() with open(output_path, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f"[+] Image saved successfully to: {output_path}") def run_media_generation_pipeline(generate_task_fn, local_image_paths=None, output_path=None, default_prefix="result"): """ Generic execution pipeline for media generation tasks: 1. Upload local images to S3 (if any) 2. Invoke generation task function -> returns task_id 3. Poll task status -> returns result_url 4. Download final image to output_path 5. Clean up temporary S3 objects """ s3_uploaded_keys = [] s3_urls = [] if local_image_paths: if isinstance(local_image_paths, str): local_image_paths = [local_image_paths] for img_path in local_image_paths: if not os.path.exists(img_path): raise FileNotFoundError(f"Local file '{img_path}' does not exist.") s3_url, s3_key = upload_file_to_s3(img_path) s3_uploaded_keys.append(s3_key) s3_urls.append(s3_url) try: task_id = generate_task_fn(s3_urls if s3_urls else None) result_url = poll_task_status(task_id) if not output_path: output_path = f"{default_prefix}_{int(time.time())}.png" download_image(result_url, output_path) return output_path finally: for key in s3_uploaded_keys: delete_file_from_s3(key=key)