BrandBrainAI / app.py
kapildew18's picture
Create app.py
a851adf verified
Raw
History Blame Contribute Delete
11.7 kB
"""
BrandBrain AI Marketing Campaign Generator - Gemini API Version
Updated to use Google's Gemini AI API instead of Ollama
Requirements:
google-generativeai==0.3.2
gradio==4.44.0
requests==2.31.0
"""
import gradio as gr
import google.generativeai as genai
import os
from datetime import datetime
class BrandBrainGeminiGenerator:
def __init__(self, api_key=None):
self.api_key = api_key
if api_key:
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel("gemini-2.5-flash")
def configure_api(self, api_key):
"""Configure Gemini API with provided key"""
try:
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel("gemini-2.5-flash")
self.api_key = api_key
return True
except Exception as e:
return False
def generate_campaign_prompt(
self, brand_name, tone, audience, product_description, primary_goal
):
"""Create a comprehensive prompt for campaign generation"""
prompt = f"""
You are BrandBrain AI, an expert marketing strategist. Generate a complete marketing campaign for the following brand:
BRAND: {brand_name}
TONE: {tone}
TARGET AUDIENCE: {audience}
PRODUCT/OFFER: {product_description}
PRIMARY GOAL: {primary_goal}
Create a comprehensive marketing campaign with the following sections (use EXACT formatting with ALL CAPS headers):
VALUE PROPOSITION
[One compelling line that captures the core value]
ELEVATOR PITCH
[A persuasive paragraph explaining what the brand does, who it serves, and why it matters]
LANDING PAGE HEADLINES
[3 different headline options for landing pages]
1. [Headline 1]
2. [Headline 2]
3. [Headline 3]
LANDING PAGE STRUCTURE
Hero Section: [Description of hero section content]
Features Section: [Key features to highlight]
Social Proof Section: [Types of testimonials/proof needed]
Call-to-Action: [Primary CTA strategy]
SOCIAL POSTS
[6 short social media posts, 3 for Instagram and 3 for LinkedIn, each with relevant hashtags]
Instagram Posts:
1. [Post 1 with hashtags]
2. [Post 2 with hashtags]
3. [Post 3 with hashtags]
LinkedIn Posts:
1. [Post 1 with hashtags]
2. [Post 2 with hashtags]
3. [Post 3 with hashtags]
AD COPY
[3 Facebook/Meta ad variations with different approaches]
1. [Ad variation 1]
2. [Ad variation 2]
3. [Ad variation 3]
EMAIL SEQUENCE
Subject Lines:
1. [Subject line 1]
2. [Subject line 2]
3. [Subject line 3]
Email Bodies:
1. [Short email body 1]
2. [Short email body 2]
3. [Short email body 3]
IMAGE PROMPTS
[3 creative briefs for visual content]
1. [Image prompt 1]
2. [Image prompt 2]
3. [Image prompt 3]
Make everything specific to the brand, tone, and audience provided. Be creative and strategic.
"""
return prompt
def generate_campaign(
self,
brand_name,
tone,
audience,
product_description,
primary_goal,
api_key,
progress=gr.Progress(),
):
"""Generate complete marketing campaign using Gemini API"""
# Validate inputs
if not all(
[
brand_name.strip(),
tone.strip(),
audience.strip(),
product_description.strip(),
primary_goal.strip(),
]
):
return "Error: Please fill in all fields before generating a campaign."
if not api_key.strip():
return "Error: Please provide your Gemini API key."
# Configure API
progress(0.1, desc="Configuring Gemini API...")
if not self.configure_api(api_key):
return "Error: Invalid API key. Please check your Gemini API key and try again."
# Generate prompt
progress(0.3, desc="Creating campaign prompt...")
prompt = self.generate_campaign_prompt(
brand_name, tone, audience, product_description, primary_goal
)
# Call Gemini API
progress(0.5, desc="Generating campaign with Gemini AI...")
try:
response = self.model.generate_content(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=0.7,
top_p=0.9,
max_output_tokens=2048,
),
)
campaign_output = response.text
except Exception as e:
return f"Error calling Gemini API: {str(e)}"
progress(1.0, desc="Campaign generated!")
# Add metadata
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
final_output = f"""# BrandBrain AI Marketing Campaign (Gemini Powered)
Generated on: {timestamp}
Brand: {brand_name}
Tone: {tone}
Audience: {audience}
Goal: {primary_goal}
---
{campaign_output}
---
Generated by BrandBrain AI Marketing Campaign Generator - Powered by Google Gemini
"""
return final_output
def save_campaign_to_file(campaign_text, brand_name):
"""Save campaign to a downloadable text file"""
if not campaign_text or campaign_text.startswith("Error:"):
return None
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"campaign_{brand_name.replace(' ', '_')}_{timestamp}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(campaign_text)
return filename
def create_interface():
"""Create the Gradio interface"""
# Initialize the generator
generator = BrandBrainGeminiGenerator()
with gr.Blocks(
title="BrandBrain AI Marketing Campaign Generator - Gemini Powered",
theme=gr.themes.Soft(),
) as interface:
# Header
gr.Markdown(
"""
# 🧠 BrandBrain AI Marketing Campaign Generator
### Powered by Google Gemini AI
Create comprehensive marketing campaigns in minutes using Google's advanced Gemini AI model.
"""
)
with gr.Row():
# Input Section
with gr.Column(scale=1):
gr.Markdown("## πŸ”‘ API Configuration")
api_key = gr.Textbox(
label="Gemini API Key",
placeholder="Enter your Google Gemini API key",
type="password",
info="Get your API key from: https://aistudio.google.com/app/apikey",
)
gr.Markdown("## πŸ“ Campaign Details")
brand_name = gr.Textbox(
label="Brand Name", placeholder="Enter your brand or company name"
)
tone = gr.Dropdown(
label="Brand Tone",
choices=[
"Professional & Authoritative",
"Friendly & Conversational",
"Bold & Energetic",
"Luxury & Sophisticated",
"Fun & Playful",
"Trustworthy & Reliable",
"Innovative & Tech-Forward",
"Warm & Caring",
],
value="Professional & Authoritative",
)
audience = gr.Textbox(
label="Target Audience",
placeholder="e.g., Small business owners, Tech professionals, Parents",
lines=2,
)
product_description = gr.Textbox(
label="Product/Offer Description",
placeholder="Describe what you're selling or promoting",
lines=3,
)
primary_goal = gr.Dropdown(
label="Primary Campaign Goal",
choices=[
"Increase Sales",
"Build Brand Awareness",
"Generate Leads",
"Drive Website Traffic",
"Boost App Downloads",
"Promote Event Registration",
"Increase Newsletter Signups",
"Launch New Product",
],
value="Increase Sales",
)
# Generate button
generate_btn = gr.Button(
"πŸš€ Generate Campaign with Gemini", variant="primary", size="lg"
)
# Output Section
with gr.Column(scale=1):
gr.Markdown("## πŸ“Š Generated Campaign")
campaign_output = gr.Textbox(
label="Marketing Campaign",
lines=25,
max_lines=50,
show_copy_button=True,
placeholder="Your Gemini-powered marketing campaign will appear here...",
)
with gr.Row():
download_btn = gr.DownloadButton(
"πŸ’Ύ Download as TXT",
size="sm",
variant="secondary",
visible=False,
)
# Footer
gr.Markdown(
"""
---
**Getting Started:**
1. Get your free Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey)
2. Enter your API key above (it's stored securely in your session)
3. Fill in your campaign details
4. Generate your comprehensive marketing campaign!
**Features:**
- βœ… Advanced AI-powered campaign generation
- βœ… 8 different marketing asset types
- βœ… Customized to your brand and audience
- βœ… Professional copywriting quality
*Powered by Google Gemini AI*
"""
)
# Event handlers
def generate_and_prepare_download(
brand_name,
tone,
audience,
product_description,
primary_goal,
api_key,
progress=gr.Progress(),
):
# Generate campaign
campaign = generator.generate_campaign(
brand_name,
tone,
audience,
product_description,
primary_goal,
api_key,
progress,
)
# Prepare download file
if not campaign.startswith("Error:") and brand_name.strip():
filename = save_campaign_to_file(campaign, brand_name)
return campaign, gr.DownloadButton(
"πŸ’Ύ Download as TXT", value=filename, visible=True
)
else:
return campaign, gr.DownloadButton("πŸ’Ύ Download as TXT", visible=False)
# Wire up the generate button
generate_btn.click(
fn=generate_and_prepare_download,
inputs=[
brand_name,
tone,
audience,
product_description,
primary_goal,
api_key,
],
outputs=[campaign_output, download_btn],
show_progress=True,
)
return interface
def main():
"""Main function to run the application"""
print("🧠 Starting BrandBrain AI Marketing Campaign Generator...")
print("✨ Powered by Google Gemini AI")
print("πŸ”‘ Get your API key: https://aistudio.google.com/app/apikey")
print()
# Create and launch interface
interface = create_interface()
# Launch with corrected settings
interface.launch(server_port=7860, share=False, show_error=True)
if __name__ == "__main__":
main()