File size: 6,176 Bytes
6956e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# Emotional Ad Campaign Generator - AI Pipeline with E-Commerce & Meta Ad Scraper

# === LAYER 1: USER INPUT & INTENT UNDERSTANDING ===
# Tools: Gradio UI + DistilBERT + spaCy NER + T5 for planning

import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification, T5ForConditionalGeneration, T5Tokenizer
import spacy

intent_classifier = pipeline("text-classification", model="distilbert-base-uncased")
ner_nlp = spacy.load("en_core_web_sm")
t5_model = T5ForConditionalGeneration.from_pretrained("t5-base")
t5_tokenizer = T5Tokenizer.from_pretrained("t5-base")

def parse_input(user_input):
    intent = intent_classifier(user_input)[0]['label']
    ner_doc = ner_nlp(user_input)
    entities = [(ent.text, ent.label_) for ent in ner_doc.ents]
    return intent, entities

def plan_campaign(user_input):
    input_text = "generate plan: " + user_input
    input_ids = t5_tokenizer(input_text, return_tensors="pt").input_ids
    output = t5_model.generate(input_ids, max_length=64, num_return_sequences=1)
    return t5_tokenizer.decode(output[0], skip_special_tokens=True)

# === LAYER 2: MARKET INSIGHT, AD SCRAPING & VECTOR STORAGE ===
# Tools: Selenium + BeautifulSoup + Sentence-BERT + FAISS (vector db)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
import os
import json

# Sentence Transformer for vector encoding
ad_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')

# Create FAISS vector database
vector_dim = 384
index = faiss.IndexFlatL2(vector_dim)
ad_texts = []
ad_metadata = []

# Web scraper for Meta Ads Library (mocked for demonstration)
def fetch_meta_ads(keyword):
    options = Options()
    options.add_argument('--headless')
    driver = webdriver.Chrome(options=options)
    driver.get(f"https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=IN&q={keyword}&search_type=keyword")
    time.sleep(5)
    soup = BeautifulSoup(driver.page_source, "html.parser")
    driver.quit()

    ad_blocks = soup.find_all("div", class_="_9cd1")  # This selector may vary
    scraped_ads = [block.get_text(strip=True) for block in ad_blocks]
    return scraped_ads

def store_ads_in_vector_db(ad_text_list):
    embeddings = ad_model.encode(ad_text_list)
    index.add(np.array(embeddings))
    ad_texts.extend(ad_text_list)
    for ad in ad_text_list:
        cta = extract_cta(ad)
        tagline = extract_tagline(ad)
        ad_metadata.append({"ad": ad, "cta": cta, "tagline": tagline})

# Extract CTA (simple regex or rules)
def extract_cta(ad_text):
    lines = ad_text.split('.')
    for line in reversed(lines):
        if any(word in line.lower() for word in ["buy", "shop now", "click", "try", "order"]):
            return line.strip()
    return ""

def extract_tagline(ad_text):
    return ad_text.split('.')[0].strip()

# === LAYER 3: AD SCRIPT GENERATION ===
# Tools: Prompt-tuned LLMs (GPT-2), emotional tone adapter

from transformers import pipeline as hf_pipeline
script_generator = hf_pipeline("text-generation", model="gpt2")

persona_styles = {
    "Gen Z": "funny, sassy, self-aware",
    "Minimal": "calm, poetic, clean",
    "Bold": "direct, assertive, high contrast"
}

emotion_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)

def generate_script(prompt, style):
    style_tone = persona_styles.get(style, "")
    full_prompt = f"Write a {style_tone} ad copy: {prompt}"
    result = script_generator(full_prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
    return result

# === LAYER 4: POSTER GENERATION ===
# Tools: Stable Diffusion + CLIP scoring

from diffusers import StableDiffusionPipeline
import torch

poster_pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
poster_pipe = poster_pipe.to("cuda" if torch.cuda.is_available() else "cpu")

def generate_poster(prompt):
    image = poster_pipe(prompt).images[0]
    return image

# === LAYER 5: TAGLINE & CTA CREATOR ===

def generate_tagline(prompt):
    input_prompt = f"Create a short emotional tagline for: {prompt}"
    tagline = script_generator(input_prompt, max_length=20, num_return_sequences=1)[0]['generated_text']
    return tagline.strip()

# === LAYER 6: FEEDBACK & EDITOR ===
from langchain.prompts import PromptTemplate

def rewrite_prompt(old_prompt, feedback):
    template = PromptTemplate.from_template(
        "Original prompt: {old}\nFeedback: {fb}\nRewritten prompt:"
    )
    return template.format(old=old_prompt, fb=feedback)

# === LAYER 7: A/B TESTING & PERFORMANCE ===
import random

def predict_ctr(ad_text):
    score = random.uniform(0.1, 0.9)
    return round(score, 2)

# === LAYER 8: CAMPAIGN DEPLOYMENT ===

def deploy_campaign(text, platform):
    return f"Deployed to {platform}: {text}"

# === INTEGRATION UI (Gradio) ===

def full_campaign_flow(user_input, tone):
    intent, entities = parse_input(user_input)
    plan = plan_campaign(user_input)
    ads_scraped = fetch_meta_ads(user_input)
    store_ads_in_vector_db(ads_scraped)
    script = generate_script(user_input, tone)
    tagline = generate_tagline(user_input)
    poster = generate_poster(user_input)
    ctr = predict_ctr(script)
    return plan, intent, entities, ads_scraped, script, tagline, poster, ctr

demo = gr.Interface(
    fn=full_campaign_flow,
    inputs=[
        gr.Textbox(label="Campaign Description"),
        gr.Radio(choices=list(persona_styles.keys()), label="Persona Tone")
    ],
    outputs=[
        gr.Text(label="Campaign Plan"),
        gr.Text(label="Intent Detected"),
        gr.Text(label="Named Entities"),
        gr.Text(label="Scraped Competitor Ads"),
        gr.Textbox(label="Generated Ad Script"),
        gr.Text(label="Generated Tagline"),
        gr.Image(label="Generated Poster"),
        gr.Number(label="Predicted CTR Score")
    ],
    title="🧠 Emotional Ad Campaign Generator"
)

if __name__ == "__main__":
    demo.launch()