userIdc2024's picture
Update app.py
45d30c8 verified
from image_processor import process_zip_and_generate_images
from load_files import create_gradio_app
import gradio as gr
import os
import zipfile
import tempfile
import requests
import shutil
import logging
# Setup logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
examples = [
["examples/input/1.png", "This ad creative should be like a facebook post opened in someone's phone.", ["examples/output/image (5).png", "examples/output/image (5).png"]],
["examples/input/2.png", "Make this ad creative like a news information on TV", ["examples/output/image (8).png", "examples/output/image (7).png"]],
["examples/input/3.jpeg", "The ad creative should comprises of 3-4 images. The images should be like trust building images with no CTA or offer. Moreover, the images should not be much HD it should be of low quality grained image.", ["examples/output/image (3).png", "examples/output/image (4).png"]]
]
custom_css = """
.gradio-container {
max-width: 1200px;
margin: auto;
background-color: #111111;
}
.gradio-group {
border: 1px solid #2a2a2a;
border-radius: 0;
padding: 0;
margin-bottom: 20px;
background-color: #1a1a1a;
color: white;
}
/* Dark theme for headers */
.panel {
background-color: #2a2a2a;
color: white;
padding: 10px;
}
/* Space between image and prompt */
.prompt-section {
margin-top: 10px;
background-color: #2a2a2a;
padding: 5px;
}
/* Adjust image container height */
.image-container {
height: auto !important;
}
/* Make headings white on dark background */
h3, h4 {
color: white !important;
margin: 0 !important;
padding: 5px !important;
}
/* Overall dark theme */
body {
background-color: #111111;
color: white;
}
"""
def zip_gallery_images(gallery_items):
if not gallery_items:
logger.warning("No gallery items received for zipping.")
return None
image_urls = [item[0] if isinstance(item, tuple) else item for item in gallery_items]
try:
temp_dir = tempfile.mkdtemp()
zip_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip").name
for i, url in enumerate(image_urls):
try:
ext = url.split('.')[-1]
file_path = os.path.join(temp_dir, f"image_{i}.{ext}")
if url.startswith("http://") or url.startswith("https://"):
response = requests.get(url, timeout=5)
response.raise_for_status()
with open(file_path, 'wb') as f:
f.write(response.content)
logger.info(f"Downloaded and saved remote image: {url}")
elif os.path.exists(url):
shutil.copy(url, file_path)
logger.info(f"Copied local image: {url}")
else:
logger.warning(f"Skipping invalid path or URL: {url}")
except Exception as e:
logger.error(f"Error processing image {url}: {e}")
with zipfile.ZipFile(zip_path, 'w') as zipf:
for file_name in os.listdir(temp_dir):
zipf.write(os.path.join(temp_dir, file_name), arcname=file_name)
logger.info(f"Zip archive created at: {zip_path}")
return zip_path
except Exception as e:
logger.critical(f"Failed to create zip: {e}")
return None
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
logger.debug("Cleaned up temporary directory.")
def toggle_controls(selected_platform):
if selected_platform == "Google Display Network":
return gr.update(interactive=False), gr.update(interactive=False)
else:
return gr.update(interactive=True), gr.update(interactive=True)
def create_main_app():
with (gr.Blocks(theme=gr.themes.Soft()) as demo):
gr.Markdown("# Bulk Creative Generation")
with gr.Tab("Generate Images"):
gr.Markdown("Bulk Creative Generation is a tool where you can upload a single image or zip of upto 10 images which will create different images for every uploaded image. Make sure the user prompt which you will write will be applicable to each image. Make sure you use this tool wisely. Also refer to the examples below for better understanding.")
with gr.Column():
zip_file = gr.File(label="Upload Zip or Single File", file_types=[".zip", ".png", ".jpg", ".jpeg"])
category = gr.Textbox(label="Category")
with gr.Row():
platform = gr.Dropdown(choices = ["Facebook", "Native", "Newsbreak", "Google Display Network"], label="Platform")
num_images = gr.Slider(1, 10, value=2, label="No. of Images to be generated:", step=1)
size = gr.Dropdown(choices=["auto","1024x1024", "1536x1024", "1024x1536"], label="Image Size")
quality = gr.Dropdown(choices=["auto", "low", "medium"], label="Quality")
sentiment = gr.Dropdown(choices=["as original image", "positive", "negative"], label="Sentiment")
blur = gr.Checkbox(label="Blur Image", info="Do you want blur background")
platform.change(fn=toggle_controls, inputs=platform, outputs=[num_images, size])
user_prompt = gr.Textbox(label="User Prompt", lines=4)
demo_btn = gr.Button("Generate Demo Image")
generate_all_btn = gr.Button("Generate All Images")
gallery = gr.Gallery(label="Generated Images", columns=4)
zip_output = gr.File(label="Download All Images (ZIP)")
download_btn = gr.Button("Download All")
gr.Markdown("## Example Transformations")
with gr.Row(variant="panel"):
gr.Markdown("## Example Transformations")
with gr.Blocks():
for example in examples:
input_img, prompt_text, output_imgs = example
with gr.Group():
with gr.Row():
with gr.Column(scale=1, variant="panel"):
gr.Markdown("### Input")
if os.path.exists(input_img):
gr.Image(value=input_img, type="filepath", label="Input Image")
else:
logger.warning(f"Example input image missing: {input_img}")
gr.Markdown(f"Image not found: {input_img}")
with gr.Row(variant="panel"):
gr.Markdown("#### Prompt:")
gr.Markdown(prompt_text)
# Output column with dark header
with gr.Column(scale=2, variant="panel"):
gr.Markdown("### Generated Outputs")
with gr.Row():
for output_path in output_imgs:
if os.path.exists(output_path):
gr.Image(value=output_path, type="filepath", label="Image")
else:
logger.warning(f"Example output image missing: {output_path}")
gr.Markdown(f"Image not found: {output_path}")
demo_btn.click(
process_zip_and_generate_images,
inputs=[zip_file, category, size, quality, user_prompt, sentiment, platform, num_images, gr.State(True),
gallery, blur],
outputs=[gallery]
)
generate_all_btn.click(
process_zip_and_generate_images,
inputs=[zip_file, category, size, quality, user_prompt, sentiment, platform, num_images, gr.State(False),
gallery, blur],
outputs=[gallery]
)
download_btn.click(
zip_gallery_images,
inputs=[gallery],
outputs=[zip_output]
)
with gr.Tab("Creative AI Library"):
MONGO_URI = os.getenv("MONGO_URI")
if not MONGO_URI:
logger.warning("MONGO_URI not set; Creative AI Library may fail to load.")
DB_NAME = "adgenesis"
COLLECTION_NAME = "records"
demo = create_gradio_app(MONGO_URI, DB_NAME, COLLECTION_NAME)
return demo
def check_token(user_token):
if not ACCESS_TOKEN:
logger.critical("ACCESS_TOKEN not set in environment.")
return gr.update(visible=False), gr.update(visible=True), "Server error: Access token not configured."
if user_token == ACCESS_TOKEN:
logger.info("Access token validated successfully.")
return gr.update(visible=True), gr.update(visible=False), ""
logger.warning("Invalid access token attempt.")
return gr.update(visible=False), gr.update(visible=True), "Invalid token."
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
with gr.Blocks() as auth_wrapper:
gr.Markdown("## Access Required")
token_input = gr.Textbox(label="Enter Access Token", type="password")
unlock_btn = gr.Button("Unlock App")
error_msg = gr.Markdown(visible=False)
main_app = gr.Column(visible=False)
with main_app:
app = create_main_app()
app.css = custom_css
unlock_btn.click(
fn=check_token,
inputs=[token_input],
outputs=[main_app, error_msg, error_msg]
)
if __name__ == "__main__":
try:
logger.info("Launching Gradio app...")
auth_wrapper.launch()
except Exception as e:
logger.exception("Unhandled error during app launch.")