import gradio as gr import requests, base64, io from dotenv import load_dotenv import os, datetime, mimetypes from PIL import Image load_dotenv() API_URL = os.environ.get("API_URL", "http://0.0.0.0:8021") APP_ENV = os.environ.get("APP_ENV", None) def image_to_base64(input_file): file_bytes = None file_path = None if input_file is None: return None # Check if the input is a string (file path) if isinstance(input_file, str): file_path = input_file with open(input_file, "rb") as file: file_bytes = file.read() else: # Handle file-like object (_TemporaryFileWrapper) file_path = input_file.name file_bytes = input_file.read() # Guess the MIME type of the file based on the file extension mime_type, _ = mimetypes.guess_type(file_path) if mime_type is None: mime_type = 'application/octet-stream' # Use a binary data MIME type as a fallback data_url = f"data:{mime_type};base64,{base64.b64encode(file_bytes).decode()}" return data_url # Assuming the API returns an image URL in the response def generate_image(brand_name, primary_color, secondary_color, description, target_audience, font, logo_image, heading_text, sub_heading_text, image_layout, custom_graphic_prompt): if logo_image: logo_base64 = image_to_base64(logo_image) else: logo_base64 = "" # Define your payload/data to send to the image generation API data = { "brand_name": brand_name, "primary_color": primary_color, "secondary_color": secondary_color, "description": description, "target_audience": target_audience, "font": font, "heading_text": heading_text or "", "sub_heading_text": sub_heading_text or "", "logo_url": logo_base64, "user_prompt": custom_graphic_prompt, "image_dimension": image_layout } # Make the API call response = requests.post(API_URL, json=data) # Ensure the API call was successful if response.status_code != 200: print(f"Error {response.status_code}: {response.text}") return "Error: Unable to fetch image from the external API." # Create the directory if it doesn't exist image_directory = "images" if not os.path.exists(image_directory): os.makedirs(image_directory) image_path = f"images/temp_image_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.png" with open(image_path, "wb") as image_file: image_file.write(response.content) return image_path content_html = """