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
| 2 |
+
import openai
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import requests
|
| 6 |
+
import nest_asyncio
|
| 7 |
+
import asyncio
|
| 8 |
+
|
| 9 |
+
from playwright.sync_api import sync_playwright
|
| 10 |
+
|
| 11 |
+
nest_asyncio.apply()
|
| 12 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
|
| 14 |
+
# Synchronous version for HF Spaces compatibility
|
| 15 |
+
def extract_text_from_url(url):
|
| 16 |
+
with sync_playwright() as pw:
|
| 17 |
+
browser = pw.chromium.launch(headless=True)
|
| 18 |
+
page = browser.new_page()
|
| 19 |
+
page.goto(url, timeout=60000)
|
| 20 |
+
page.wait_for_load_state('networkidle')
|
| 21 |
+
content = page.content()
|
| 22 |
+
browser.close()
|
| 23 |
+
|
| 24 |
+
soup = BeautifulSoup(content, "html.parser")
|
| 25 |
+
text = ' '.join(p.get_text(strip=True) for p in soup.find_all(['p', 'span', 'h1', 'h2', 'li']))
|
| 26 |
+
return text[:4000] # limit to 4000 characters
|
| 27 |
+
|
| 28 |
+
def extract_keywords(text):
|
| 29 |
+
prompt = f"""
|
| 30 |
+
Extract up to 10 concise, relevant SEO keywords suitable for an automotive advertisement from the following content:
|
| 31 |
+
|
| 32 |
+
{text}
|
| 33 |
+
|
| 34 |
+
Keywords:
|
| 35 |
+
"""
|
| 36 |
+
response = openai.ChatCompletion.create(
|
| 37 |
+
model="gpt-4",
|
| 38 |
+
messages=[{"role": "user", "content": prompt}],
|
| 39 |
+
temperature=0.6,
|
| 40 |
+
max_tokens=100
|
| 41 |
+
)
|
| 42 |
+
keywords = response.choices[0].message.content.strip().split(',')
|
| 43 |
+
return [kw.strip() for kw in keywords]
|
| 44 |
+
|
| 45 |
+
def generate_ad_copy(platform, keywords):
|
| 46 |
+
prompt = f"""
|
| 47 |
+
Create a compelling, SEO-optimized {platform} ad using these keywords: {', '.join(keywords)}.
|
| 48 |
+
Include a clear and enticing call-to-action.
|
| 49 |
+
"""
|
| 50 |
+
response = openai.ChatCompletion.create(
|
| 51 |
+
model="gpt-4",
|
| 52 |
+
messages=[{"role": "user", "content": prompt}],
|
| 53 |
+
temperature=0.7,
|
| 54 |
+
max_tokens=300
|
| 55 |
+
)
|
| 56 |
+
return response.choices[0].message.content.strip()
|
| 57 |
+
|
| 58 |
+
def generate_ad_image(keywords):
|
| 59 |
+
kw_str = ", ".join(keywords)
|
| 60 |
+
image_prompt = f"Professional automotive social media ad featuring: {kw_str}. Bright visuals, luxury theme, with text overlay space."
|
| 61 |
+
response = openai.Image.create(
|
| 62 |
+
prompt=image_prompt,
|
| 63 |
+
n=1,
|
| 64 |
+
size="512x512"
|
| 65 |
+
)
|
| 66 |
+
image_url = response["data"][0]["url"]
|
| 67 |
+
img_data = requests.get(image_url).content
|
| 68 |
+
img_file = "generated_ad_image.png"
|
| 69 |
+
with open(img_file, "wb") as f:
|
| 70 |
+
f.write(img_data)
|
| 71 |
+
return img_file
|
| 72 |
+
|
| 73 |
+
def main_workflow(input_mode, url_or_keywords):
|
| 74 |
+
error = None
|
| 75 |
+
# Step 1: Get keywords
|
| 76 |
+
if input_mode == "URL":
|
| 77 |
+
try:
|
| 78 |
+
text = extract_text_from_url(url_or_keywords)
|
| 79 |
+
keywords = extract_keywords(text)
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return None, None, None, f"URL extraction error: {e}"
|
| 82 |
+
else:
|
| 83 |
+
keywords = [kw.strip() for kw in url_or_keywords.split(",") if kw.strip()]
|
| 84 |
+
if not keywords:
|
| 85 |
+
return None, None, None, "Please provide at least one keyword."
|
| 86 |
+
|
| 87 |
+
# Step 2: Generate ad copies
|
| 88 |
+
platforms = ["Facebook", "Instagram", "X (Twitter)", "Google Search"]
|
| 89 |
+
ad_copies = {}
|
| 90 |
+
for platform in platforms:
|
| 91 |
+
ad_copies[platform] = generate_ad_copy(platform, keywords)
|
| 92 |
+
|
| 93 |
+
# Step 3: Generate ad image
|
| 94 |
+
try:
|
| 95 |
+
image_path = generate_ad_image(keywords)
|
| 96 |
+
except Exception as e:
|
| 97 |
+
image_path = None
|
| 98 |
+
error = f"Image generation error: {e}"
|
| 99 |
+
|
| 100 |
+
# Step 4: Save ad copies to txt
|
| 101 |
+
output_txt = "generated_ads.txt"
|
| 102 |
+
with open(output_txt, "w", encoding="utf-8") as f:
|
| 103 |
+
for platform, content in ad_copies.items():
|
| 104 |
+
f.write(f"--- {platform} Ad Copy ---\n{content}\n\n")
|
| 105 |
+
|
| 106 |
+
return keywords, ad_copies, image_path, error
|
| 107 |
+
|
| 108 |
+
def run_space(input_mode, url, keywords):
|
| 109 |
+
url_or_keywords = url if input_mode == "URL" else keywords
|
| 110 |
+
keywords, ad_copies, image_path, error = main_workflow(input_mode, url_or_keywords)
|
| 111 |
+
ad_previews = ""
|
| 112 |
+
if ad_copies:
|
| 113 |
+
for platform, ad in ad_copies.items():
|
| 114 |
+
ad_previews += f"### {platform}\n{ad}\n\n"
|
| 115 |
+
return (
|
| 116 |
+
keywords,
|
| 117 |
+
ad_previews,
|
| 118 |
+
image_path,
|
| 119 |
+
"generated_ads.txt" if ad_copies else None,
|
| 120 |
+
error
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
with gr.Blocks() as demo:
|
| 124 |
+
gr.Markdown("# 🚗 Auto Ad Generator\nPaste a car listing URL **or** enter your own keywords, then preview AI-generated ads for each social media platform, plus an auto-generated image!")
|
| 125 |
+
input_mode = gr.Radio(["URL", "Keywords"], value="URL", label="Input Type")
|
| 126 |
+
url_input = gr.Textbox(label="Listing URL", placeholder="https://www.cars.com/listing/...", visible=True)
|
| 127 |
+
kw_input = gr.Textbox(label="Manual Keywords (comma separated)", placeholder="e.g. BMW, used car, sunroof", visible=False)
|
| 128 |
+
submit_btn = gr.Button("Generate Ads")
|
| 129 |
+
|
| 130 |
+
gr.Markdown("## Keywords")
|
| 131 |
+
kw_out = gr.JSON(label="Extracted/Provided Keywords")
|
| 132 |
+
|
| 133 |
+
gr.Markdown("## Ad Copy Previews")
|
| 134 |
+
ad_out = gr.Markdown(label="Ad Copy Preview")
|
| 135 |
+
|
| 136 |
+
gr.Markdown("## Generated Ad Image")
|
| 137 |
+
img_out = gr.Image(label="Generated Ad Image", type="filepath")
|
| 138 |
+
|
| 139 |
+
gr.Markdown("## Download Ad Copies")
|
| 140 |
+
file_out = gr.File(label="Download TXT")
|
| 141 |
+
|
| 142 |
+
err_out = gr.Textbox(label="Errors", interactive=False)
|
| 143 |
+
|
| 144 |
+
def show_hide_fields(choice):
|
| 145 |
+
return (
|
| 146 |
+
gr.update(visible=choice == "URL"),
|
| 147 |
+
gr.update(visible=choice == "Keywords"),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
input_mode.change(show_hide_fields, input_mode, [url_input, kw_input])
|
| 151 |
+
|
| 152 |
+
submit_btn.click(
|
| 153 |
+
run_space,
|
| 154 |
+
inputs=[input_mode, url_input, kw_input],
|
| 155 |
+
outputs=[kw_out, ad_out, img_out, file_out, err_out]
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
demo.launch()
|