text_campaign / app.py
gaur3009's picture
Update app.py
7c4529a verified
"""
Enterprise Creative Campaign Suite - Separate-section generation (FLAN-T5-XL)
Author: Assistant (adapted for your needs)
Notes:
- This script calls the HF pipeline 5 times (one per section).
- If you have GPU, set device=0 inside the pipeline(...) call for speed.
"""
import tempfile
from fpdf import FPDF
import gradio as gr
from transformers import pipeline
# -----------------------------
# MODEL SETUP - FLAN-T5-XL
# -----------------------------
# If you have GPU, set device=0
generator = pipeline(
"text2text-generation",
model="google/flan-t5-xl",
# device=0, # uncomment if you want to use the first CUDA GPU
)
# -----------------------------
# Brand Memory (simple key-value)
# -----------------------------
brand_memory = {
"tone": "Professional, modern, emotionally resonant",
"style": "Story-driven, cinematic, customer-first",
}
# -----------------------------
# Low-level wrapper to call model
# -----------------------------
def gen_one(prompt: str, max_new_tokens: int = 220, temperature: float = 0.8, do_sample: bool = True):
"""Call the HF pipeline and return generated text (stripped)."""
out = generator(prompt, max_new_tokens=max_new_tokens, do_sample=do_sample, temperature=temperature)
# Pipeline returns a list of dicts; take first
return out[0]["generated_text"].strip()
# -----------------------------
# Per-section prompt builders
# -----------------------------
def build_creative_direction_prompt(brand, product, goal, tone, audience, region):
return f"""You are an expert creative strategist. Write a **3–5 line Creative Direction** for a premium brand campaign.
Brand: {brand}
Product: {product}
Goal: {goal}
Tone: {tone}. Brand historically sounds like: {brand_memory.get('tone')}
Audience: {audience}
Region: {region}
Constraints:
- Output ONLY the creative direction text (3-5 lines).
- No headings, no extra commentary.
- Make it cinematic, emotionally resonant, and brand-forward.
"""
def build_emotional_tone_prompt(brand, product, goal, tone, audience, region):
return f"""Write the Emotional Tone of the campaign in 4-6 lines.
Brand: {brand}
Product: {product}
Goal: {goal}
Tone: {tone}. Brand memory: {brand_memory.get('tone')}
Audience: {audience}
Region: {region}
Explain: emotional personality, core feelings to evoke, voice, and how it should make the audience feel.
Output ONLY the emotional tone paragraph(s). No headings.
"""
def build_ad_script_prompt(brand, product, goal, tone, audience, region, script_style="Hybrid"):
"""
Hybrid = cinematic storytelling + marketing clarity.
We'll ask for labeled sections inside the script: Intro, Body, CTA.
"""
return f"""Write a cinematic + marketing hybrid Ad Script for a 30-60 second film ad. Include labeled sections: "Intro:", "Body:", "CTA:".
Brand: {brand}
Product: {product}
Goal: {goal}
Tone: {tone}. Brand memory: {brand_memory.get('tone')}
Audience: {audience}
Region: {region}
Style: Hybrid (mix cinematic imagery and short marketing beats). Keep each labeled section concise (Intro: 2-4 lines, Body: 6-10 lines, CTA: 1-2 lines). Use vivid sensory details and short punch lines for the CTA.
Output only the script text with the labeled sections (Intro:, Body:, CTA:). No extra headings or commentary.
"""
def build_poster_prompt_prompt(brand, product, goal, tone, audience, region):
return f"""Generate a single-paragraph Stable Diffusion / SDXL poster prompt for the campaign.
Brand: {brand}
Product: {product}
Goal: {goal}
Tone: {tone}. Brand memory: {brand_memory.get('tone')}
Audience: {audience}
Region: {region}
Include: lighting, color palette, environment, camera angle, characters (appearance, clothing, pose), props, mood, depth of field suggestions, and where to place typography.
Output only one descriptive paragraph (no headings).
"""
def build_taglines_prompt(brand, product, goal, tone, audience, region):
return f"""Write **two** powerful taglines for the campaign. Keep them short, memorable, and emotionally resonant.
Brand: {brand}
Product: {product}
Goal: {goal}
Tone: {tone}. Brand memory: {brand_memory.get('tone')}
Audience: {audience}
Region: {region}
Format (exact):
- <Tagline 1>
- <Tagline 2>
Output only the two lines prefixed with a dash as shown.
"""
# -----------------------------
# Combined generator that calls the model for each section
# -----------------------------
def generate_campaign(brand_name, product_type, goal, tone, audience, region, temperature=0.8, do_sample=True):
"""
Calls the model separately for each section and returns assembled markdown plus raw sections.
"""
# Ensure brand memory hint appended to tone
tone_hint = f"{tone}. The brand historically sounds like: {brand_memory.get('tone')}"
# Build prompts
p_cd = build_creative_direction_prompt(brand_name, product_type, goal, tone_hint, audience, region)
p_et = build_emotional_tone_prompt(brand_name, product_type, goal, tone_hint, audience, region)
p_ad = build_ad_script_prompt(brand_name, product_type, goal, tone_hint, audience, region, script_style="Hybrid")
p_pp = build_poster_prompt_prompt(brand_name, product_type, goal, tone_hint, audience, region)
p_tg = build_taglines_prompt(brand_name, product_type, goal, tone_hint, audience, region)
# Generate each section (separate calls)
creative_direction = gen_one(p_cd, max_new_tokens=200, temperature=temperature, do_sample=do_sample)
emotional_tone = gen_one(p_et, max_new_tokens=180, temperature=temperature, do_sample=do_sample)
ad_script = gen_one(p_ad, max_new_tokens=420, temperature=temperature, do_sample=do_sample)
poster_prompt = gen_one(p_pp, max_new_tokens=200, temperature=temperature, do_sample=do_sample)
taglines = gen_one(p_tg, max_new_tokens=80, temperature=temperature, do_sample=do_sample)
# Assemble markdown
md = f"""
# 🎨 **Enterprise Creative Campaign Output**
---
## ✨ Brand: **{brand_name}**
### 🌍 Region: {region}
---
## 🎯 **Creative Direction**
{creative_direction}
---
## ❀️ **Emotional Tone**
{emotional_tone}
---
## 🎬 **Ad Script**
{ad_script}
---
## πŸ–Ό **Poster Prompt**
{poster_prompt}
---
## πŸ”₯ **Taglines**
{taglines}
---
"""
# Return markdown plus each piece so UI can store/use them
return md, creative_direction, emotional_tone, ad_script, poster_prompt, taglines
# -----------------------------
# Poster prompt single-call helper (tab 2)
# -----------------------------
def generate_poster_prompt(brand, mood, theme, audience, temperature=0.8, do_sample=True):
prompt = f"""Create a cinematic AI poster prompt for Stable Diffusion / SDXL.
Brand: {brand}
Mood: {mood}
Theme: {theme}
Audience: {audience}
Brand memory: {brand_memory.get('tone')}
OUTPUT: Single paragraph describing lighting, color palette, environment, camera angle, people (appearance, clothing, poses), props, depth of field, mood, and typography placement.
"""
return gen_one(prompt, max_new_tokens=240, temperature=temperature, do_sample=do_sample)
# -----------------------------
# Update Brand Memory
# -----------------------------
def update_brand_memory(new_tone, new_style):
if new_tone:
brand_memory["tone"] = new_tone
if new_style:
brand_memory["style"] = new_style
return "βœ… Brand memory updated successfully!", str(brand_memory)
# -----------------------------
# Export to PDF
# -----------------------------
def export_pdf(text):
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12)
for line in text.split("\n"):
pdf.multi_cell(0, 7, line)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
pdf.output(tmp.name)
return tmp.name
# -----------------------------
# Gradio UI
# -----------------------------
with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
gr.HTML("""
<div style='text-align:center; padding:20px'>
<h1 style='font-size:40px;'>πŸš€ Enterprise Creative Campaign Suite</h1>
<p style='font-size:18px; color:#ddd;'>FLAN-T5-XL β€’ Sectioned generation (Hybrid script)</p>
</div>
""")
with gr.Tabs():
# Campaign Generator Tab
with gr.Tab("🎨 Campaign Generator"):
with gr.Row():
brand_name = gr.Textbox(label="Brand Name", value="Chessy")
product_type = gr.Textbox(label="Product Type", value="Premium Chess Set")
goal = gr.Textbox(label="Campaign Goal", value="Increase D2C sales by 30% in 3 months")
tone = gr.Textbox(label="Tone / Voice", value="Warm, aspirational, cinematic")
audience = gr.Textbox(label="Target Audience", value="Young professionals, 25-40, India")
region = gr.Textbox(label="Region", value="India")
# Sampling controls
with gr.Row():
temperature = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.8, label="Temperature")
sampling_toggle = gr.Checkbox(value=True, label="Use sampling (do_sample)")
run_btn = gr.Button("πŸš€ Generate Full Campaign", variant="primary")
output_md = gr.Markdown("Your campaign will appear here…", elem_id="campaign_output_md")
# Hidden outputs for each section
cd = gr.Textbox(visible=False)
et = gr.Textbox(visible=False)
ad = gr.Textbox(visible=False)
pp = gr.Textbox(visible=False)
tg = gr.Textbox(visible=False)
run_btn.click(
fn=generate_campaign,
inputs=[brand_name, product_type, goal, tone, audience, region, temperature, sampling_toggle],
outputs=[output_md, cd, et, ad, pp, tg]
)
# Poster Prompt Tab
with gr.Tab("πŸ–Ό Poster Prompt Generator"):
brandp = gr.Textbox(label="Brand Name", value="Chessy")
mood = gr.Textbox(label="Mood & Emotion", value="Epic, reflective")
themep = gr.Textbox(label="Theme", value="Master vs Newcomer")
audp = gr.Textbox(label="Audience", value="Players & collectors")
# sampling controls local for poster
poster_temp = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.8, label="Temperature (poster)")
poster_sample = gr.Checkbox(value=True, label="Use sampling for poster")
gen_poster_btn = gr.Button("🎨 Generate Poster Prompt")
poster_out = gr.Textbox(label="Poster Prompt", lines=8)
gen_poster_btn.click(
generate_poster_prompt,
[brandp, mood, themep, audp, poster_temp, poster_sample],
poster_out
)
# Brand Memory Tab
with gr.Tab("🧠 Brand Tone Memory"):
gr.Markdown("### Update your persistent brand tone + style memory")
new_tone = gr.Textbox(label="New Tone")
new_style = gr.Textbox(label="New Style")
upd_btn = gr.Button("πŸ’Ύ Update Memory")
msg = gr.Textbox(label="Status")
mem = gr.Textbox(label="Current Memory", lines=5, value=str(brand_memory))
upd_btn.click(update_brand_memory, [new_tone, new_style], [msg, mem])
# Export Center Tab
with gr.Tab("πŸ“¦ Export Center"):
gr.Markdown("### Export your full campaign as PDF")
export_btn = gr.Button("πŸ“„ Export Campaign as PDF")
export_file = gr.File()
export_btn.click(export_pdf, inputs=output_md, outputs=export_file)
demo.launch()