File size: 6,710 Bytes
72b170b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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)