import os import zipfile import logging from typing import List, Optional import base64 from openai import OpenAI from dotenv import load_dotenv load_dotenv() def unzip_images(zip_path: str, extract_to: Optional[str] = None) -> List[str]: logger = logging.getLogger(__name__) logger.debug(f"Starting to unzip images from {zip_path!r}") # Determine extraction directory if extract_to is None: extract_to = os.path.splitext(os.path.basename(zip_path))[0] logger.debug(f"Extraction directory set to {extract_to!r}") # Define supported image extensions image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'} extracted_files: List[str] = [] try: # Ensure the zip file exists if not os.path.isfile(zip_path): logger.error(f"Zip file does not exist: {zip_path}") return [] # Create extraction directory if needed os.makedirs(extract_to, exist_ok=True) logger.debug(f"Ensured extraction directory exists: {extract_to!r}") # Open and iterate through the zip with zipfile.ZipFile(zip_path, 'r') as zf: for member in zf.infolist(): filename = member.filename _, ext = os.path.splitext(filename.lower()) # Only extract images if ext in image_extensions: try: zf.extract(member, extract_to) file_path = os.path.join(extract_to, filename) extracted_files.append(_encode_image_to_base64(file_path)) logger.info(f"Extracted image: {file_path}") except Exception as e: logger.error(f"Failed to extract {filename}: {e}") if not extracted_files: logger.warning(f"No images found in archive: {zip_path}") logger.debug(f"Finished unzipping. Total images extracted: {len(extracted_files)}") return extracted_files except zipfile.BadZipFile: logger.exception(f"Bad zip file or corrupt archive: {zip_path}") return [] except Exception: logger.exception(f"Unexpected error while unzipping {zip_path}") return [] def _encode_image_to_base64(image_path): with open(image_path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8") def is_valid_image(file_name: str) -> bool: return file_name.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp")) def generate_image(template_path, file_path, size, quality, category, sentiment, user_prompt): client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) result = client.images.edit( model="gpt-image-1", prompt=f"""You are a top-tier performance digital marketer and creative strategist with 15+ years of expertise in affiliate marketing. Your objective is to analyze the provided winning template image and given ad image, deconstruct ad image concept, visual composition, and color scheme, and generate a fresh, conversion-focused ad visual in the given template image tailored for the {category} niche. The new design should convey a {sentiment} sentiment and incorporate the user instruction: {user_prompt}. Create a visually compelling ad optimized for Facebook Ads in the same template that is scroll-stopping, pattern-interrupting, and designed to drive high CTR and CR. Utilize striking color combinations, dynamic contrast levels, and strategic layout compositions to command attention while aligning with the target audience avatar and reinforcing the brand’s messaging.""", image=[open(template_path, "rb"), open(file_path, "rb")], size=size, quality=quality, ) image_base64 = result.data[0].b64_json image_bytes = base64.b64decode(image_base64) return image_bytes