decodingdatascience commited on
Commit
1693c7c
·
verified ·
1 Parent(s): b655b7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -264
app.py CHANGED
@@ -20,322 +20,124 @@ if not OPENAI_API_KEY:
20
  "Settings → Secrets and add OPENAI_API_KEY."
21
  )
22
 
23
-
24
- # --- Logo: convert GitHub page URL to raw if needed ---
25
- def to_raw_github(url: str) -> str:
26
- # Accepts both blob and raw URLs; converts blob → raw
27
- return url.replace("https://github.com/", "https://raw.githubusercontent.com/").replace("/blob/", "/")
28
 
29
- LOGO_URL = to_raw_github("https://github.com/Decoding-Data-Science/airesidency/blob/main/dds_logo.jpg")
30
 
31
- # ----------------------------
32
- # Your existing agents (unchanged)
33
- # ----------------------------
34
  lead_market_analyst = Agent(
35
  role="Lead Market Analyst",
36
- goal="Deliver sharp, data-driven market insights for the brand/product.",
37
- backstory=("Senior analyst skilled in competitor intelligence, audience segmentation, "
38
- "channel dynamics, and market sizing. Outputs actionable insights."),
 
 
39
  allow_delegation=False,
40
- verbose=True,
41
  )
42
 
43
  chief_marketing_strategist = Agent(
44
  role="Chief Marketing Strategist",
45
- goal="Turn research into a focused, measurable go-to-market strategy.",
46
- backstory=("Veteran strategist who crafts positioning, messaging pillars, channel mix, "
47
- "and KPI frameworks; coordinates the team."),
48
- allow_delegation=False,
49
- verbose=True,
 
 
 
50
  )
51
 
52
  creative_content_creator = Agent(
53
  role="Creative Content Creator",
54
- goal="Transform the strategy into compelling campaign concepts and a content calendar.",
55
- backstory=("Concept-to-copy creative converting strategy into campaign ideas, ad copy, "
56
- "social posts, and long-form content."),
57
- allow_delegation=False,
58
- verbose=True,
59
- )
60
-
61
- # Optional: focused social copywriter (only if toggled)
62
- social_copywriter = Agent(
63
- role="Social Copywriter",
64
- goal="Turn strategy into platform-appropriate copy with strong hooks and clear CTAs.",
65
- backstory=("Skilled at LinkedIn thought-leadership, X brevity, and long-form posts that convert."),
66
  allow_delegation=False,
67
- verbose=False,
68
  )
69
 
70
- # ----------------------------
71
- # Core crew (unchanged)
72
- # ----------------------------
73
- def run_marketing_crew(product_brand: str, target_audience: str, objective: str) -> str:
74
  topic = f"{product_brand} | Audience: {target_audience} | Objective: {objective}"
75
 
 
76
  market_analysis_task = Task(
77
  description=(
78
- f"Conduct a concise market analysis for: {topic}. "
79
  "Cover: (1) ICP & segments, (2) JTBD/pain points & objections, "
80
  "(3) competitive landscape & whitespace, (4) demand signals & seasonality, "
81
  "(5) channel dynamics (search/social/email/partners/events), "
82
  "(6) keyword themes & content gaps, (7) risks/assumptions."
83
  ),
84
  expected_output=(
85
- "A structured brief with bullet points for each section and a 5–8 point summary of "
86
- "the most actionable insights."
87
  ),
88
- agent=lead_market_analyst
 
89
  )
90
 
 
91
  strategy_task = Task(
92
  description=(
93
- f"Using the Market Analysis brief, craft a go-to-market strategy for: {topic}. "
94
  "Include: positioning statement, value prop, 3–5 messaging pillars, "
95
  "priority segments, channel mix with rationale, offer/CTA ideas, "
96
  "90-day roadmap (phases & owners), KPI tree (primary/leading indicators), "
97
  "and a lightweight budget allocation (% by channel)."
98
  ),
99
- expected_output="A strategy document with the sections above plus a one-page executive summary.",
 
 
100
  agent=chief_marketing_strategist,
 
101
  context=[market_analysis_task]
102
  )
103
 
 
104
  creative_task = Task(
105
  description=(
106
  "Based on the Strategy, produce: (a) 3 campaign concepts (hook, angle, proof), "
107
- "(b) ad copy variants (paid search & paid social), "
108
- "(c) a 4-week content calendar (blog/LinkedIn/X/YouTube/Newsletter) with titles, "
109
- "briefs, CTAs, intended KPIs, and (d) a landing-page wireframe outline "
110
  "(hero, value blocks, social proof, FAQ)."
111
  ),
112
- expected_output="Campaign concepts + copy, a tabular content calendar, and a structured LP outline.",
 
 
113
  agent=creative_content_creator,
 
114
  context=[strategy_task]
115
  )
116
 
117
  crew = Crew(
118
  agents=[lead_market_analyst, chief_marketing_strategist, creative_content_creator],
119
- tasks=[market_analysis_task, strategy_task, creative_task],
120
- verbose=True
121
- )
122
- return crew.kickoff()
123
-
124
- # ----------------------------
125
- # Helpers
126
- # ----------------------------
127
- def _first_n_points(text: str, n: int = 5):
128
- lines = [l.strip() for l in text.splitlines() if l.strip()]
129
- bullets = []
130
- for l in lines:
131
- if l.startswith(("-", "*", "•")) or re.match(r"^\d+[\.\)]", l) or len(l) > 50:
132
- bullets.append(l.lstrip("-*• ").strip())
133
- if len(bullets) >= n: break
134
- if not bullets:
135
- parts = [p.strip() for p in text.split("\n\n") if p.strip()]
136
- bullets = parts[:n]
137
- return bullets[:n]
138
-
139
- def _hashtags(csv_tags: str) -> str:
140
- tags = [t.strip().replace("#", "") for t in (csv_tags or "").split(",") if t.strip()]
141
- return "" if not tags else " " + " ".join(f"#{t}" for t in tags)
142
-
143
- def _truncate_chars(s: str, max_chars: int) -> str:
144
- return s if len(s) <= max_chars else s[:max_chars - 1] + "…"
145
-
146
- # ----------------------------
147
- # Lightweight templates (no extra LLM call)
148
- # ----------------------------
149
- def tpl_linkedin(strategy, brand, audience, objective, hashtags, max_words=180):
150
- hook = f"{brand}: a sharper path to {objective} for {audience}."
151
- pts = "\n".join([f"- {p}" for p in _first_n_points(strategy, 5)])
152
- body = f"""**{hook}**
153
-
154
- **Key insights**
155
- {pts}
156
-
157
- **Next 90 days**
158
- - Prove the positioning with fast tests
159
- - Double down on channels with strongest signals
160
- - Track leading KPIs weekly
161
-
162
- CTA: Comment “PLAYBOOK” if you want the GTM outline.{_hashtags(hashtags)}
163
- """
164
- words = body.split()
165
- return (" ".join(words[:max_words]) + "…") if len(words) > max_words else body
166
-
167
- def tpl_tweet(strategy, brand, audience, objective, hashtags, max_chars=270):
168
- points = _first_n_points(strategy, 3)
169
- msg = f"{brand} → {objective} for {audience}: " + " | ".join(_truncate_chars(p, 80) for p in points)
170
- return _truncate_chars(msg + _hashtags(hashtags), max_chars)
171
-
172
- def tpl_article(strategy, brand, audience, objective, hashtags, max_words=800):
173
- intro = (f"{brand} is targeting {audience} to achieve {objective}. "
174
- "Here’s the distilled market analysis, GTM strategy, and a 90-day plan.")
175
- text = f"""# {brand}: GTM Playbook for {audience}
176
-
177
- ## Why this matters
178
- {intro}
179
-
180
- ## Strategy in brief
181
- - Positioning & messaging pillars
182
- - Priority segments & channel mix
183
- - Offers/CTAs, KPI tree
184
- - 90-day roadmap & budget split
185
-
186
- ## Research & Strategy Notes
187
- {strategy}
188
-
189
- ## What to do next
190
- 1) Validate 1–2 offers with tight ICP cohorts
191
- 2) Launch a 2-channel test with weekly KPI reviews
192
- 3) Scale what converts, archive what doesn’t
193
 
194
- *Updated: {datetime.utcnow().strftime("%Y-%m-%d")}*{_hashtags(hashtags)}
195
- """
196
- words = text.split()
197
- return (" ".join(words[:max_words]) + "…") if len(words) > max_words else text
198
-
199
- # ----------------------------
200
- # Optional LLM copywriter (reuses Social Copywriter agent)
201
- # ----------------------------
202
- def llm_copywriter(strategy_text, brand, audience, objective, tone, platform,
203
- hashtags, li_words, tweet_chars, article_words):
204
- limits = {
205
- "LinkedIn": f"≈ {li_words} words",
206
- "X (Twitter)": f"≤ {tweet_chars} chars",
207
- "Article": f"≈ {article_words} words",
208
- }
209
- req = f"""Create a {platform} post from the GTM strategy.
210
-
211
- Brand: {brand}
212
- Audience: {audience}
213
- Objective: {objective}
214
- Tone: {tone}
215
- Hashtags: {hashtags or '(none)'}
216
- Length limit: {limits.get(platform, 'keep concise')}
217
-
218
- Requirements:
219
- - Strong first-line hook
220
- - 1–3 concrete insights from the strategy (no clichés)
221
- - Clear CTA
222
- - Respect platform style and length
223
-
224
- --- STRATEGY ---
225
- {strategy_text}
226
- """
227
- task = Task(description=req, expected_output=f"{platform} copy ready to publish.", agent=social_copywriter)
228
- crew = Crew(agents=[social_copywriter], tasks=[task], verbose=False)
229
- return crew.kickoff()
230
-
231
- # ----------------------------
232
- # Generation wrapper
233
- # ----------------------------
234
- PLATFORMS = ["LinkedIn", "X (Twitter)", "Article"] # Reduced for better UX
235
-
236
- def generate(product_brand, target_audience, objective,
237
- platform, tone, hashtags, use_llm,
238
- li_max_words, tweet_max_chars, article_max_words):
239
-
240
- if not product_brand or not target_audience or not objective:
241
- return "Please fill Brand, Audience, and Objective.", "", None
242
-
243
- # 1) Run the main Crew once
244
- strategy = run_marketing_crew(product_brand, target_audience, objective)
245
-
246
- # 2) Copy route
247
- if use_llm:
248
- social = llm_copywriter(strategy, product_brand, target_audience, objective,
249
- tone, platform, hashtags,
250
- li_max_words, tweet_max_chars, article_max_words)
251
- else:
252
- if platform == "LinkedIn":
253
- social = tpl_linkedin(strategy, product_brand, target_audience, objective, hashtags, li_max_words)
254
- fname = f"linkedin_{re.sub(r'\\W+','_',product_brand.lower())}.md"
255
- elif platform == "X (Twitter)":
256
- social = tpl_tweet(strategy, product_brand, target_audience, objective, hashtags, tweet_max_chars)
257
- fname = f"tweet_{re.sub(r'\\W+','_',product_brand.lower())}.txt"
258
- else: # Article
259
- social = tpl_article(strategy, product_brand, target_audience, objective, hashtags, article_max_words)
260
- fname = f"article_{re.sub(r'\\W+','_',product_brand.lower())}.md"
261
-
262
- out_path = Path(fname).resolve()
263
- out_path.write_text(social, encoding="utf-8")
264
- return strategy, social, str(out_path)
265
-
266
- # Save LLM result with reasonable extension
267
- name_map = {"LinkedIn": "linkedin", "X (Twitter)": "tweet", "Article": "article"}
268
- fname = f"{name_map.get(platform,'post')}_{re.sub(r'\\W+','_',product_brand.lower())}.md"
269
- out_path = Path(fname).resolve()
270
- out_path.write_text(social, encoding="utf-8")
271
- return strategy, social, str(out_path)
272
-
273
- # ----------------------------
274
- # Theming & Layout (2 columns with header)
275
- # ----------------------------
276
- theme = gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")
277
-
278
- CUSTOM_CSS = """
279
- #header {display:flex; align-items:center; gap:16px; padding:10px 14px; border-radius:12px;
280
- background: linear-gradient(90deg, #eef2ff, #f8fafc); border:1px solid #e5e7eb;}
281
- #header img {width:44px; height:44px; object-fit:contain; border-radius:8px;}
282
- #header .title {font-weight:700; font-size:18px; color:#111827;}
283
- #header .subtitle {font-size:13px; color:#6b7280;}
284
- .card {border:1px solid #e5e7eb; border-radius:12px; padding:12px; background:#ffffff;}
285
- """
286
-
287
- with gr.Blocks(title="DDS Marketing Crew → Social Content", theme=theme, css=CUSTOM_CSS) as demo:
288
- with gr.Row():
289
- with gr.Column(scale=12):
290
- with gr.Row(elem_id="header"):
291
- gr.Image(value=LOGO_URL, show_label=False, interactive=False, height=48, width=48)
292
- gr.HTML("""
293
- <div>
294
- <div class="title">Decoding Data Science — Marketing Strategy → Social Generator</div>
295
- <div class="subtitle">Run the Analyst → Strategist → Creator pipeline, then produce a platform-ready post.</div>
296
- </div>
297
- """)
298
-
299
- with gr.Row():
300
- # Left: Inputs
301
- with gr.Column(scale=5):
302
- with gr.Group(elem_classes="card"):
303
- brand = gr.Textbox(label="Product/Brand", placeholder="e.g., DDS AI Residency", autofocus=True)
304
- audience = gr.Textbox(label="Target Audience", placeholder="e.g., Data science beginners in MENA")
305
- objective = gr.Textbox(label="Objective", placeholder="e.g., Drive applications for Cohort 8")
306
-
307
- with gr.Group(elem_classes="card"):
308
- platform = gr.Dropdown(choices=PLATFORMS, value="LinkedIn", label="Platform")
309
- tone = gr.Dropdown(choices=["Professional", "Friendly", "Bold", "Educational", "Conversational"],
310
- value="Professional", label="Tone")
311
- hashtags = gr.Textbox(label="Hashtags (comma separated)", placeholder="ai, generativeai, datascience")
312
- use_llm = gr.Checkbox(value=False, label="Use LLM Copywriter (higher fidelity)")
313
-
314
- with gr.Group(elem_classes="card"):
315
- li_max_words = gr.Slider(100, 350, value=180, step=10, label="LinkedIn max words")
316
- tweet_max_chars = gr.Slider(120, 280, value=270, step=5, label="X/Tweet max chars")
317
- article_max_words = gr.Slider(400, 1200, value=800, step=50, label="Article max words")
318
-
319
- run_btn = gr.Button("Generate Strategy → Post", variant="primary")
320
-
321
- # Right: Outputs
322
- with gr.Column(scale=7):
323
- with gr.Accordion("Strategy Output (from Crew)", open=True):
324
- strategy_md = gr.Markdown(value="*(Will appear here after generation)*")
325
-
326
- with gr.Group(elem_classes="card"):
327
- gr.Markdown("**Platform Copy** (editable; use the copy icon)")
328
- social_tb = gr.Textbox(lines=18, show_copy_button=True, label=None)
329
-
330
- download_file = gr.File(label="Download", interactive=False)
331
-
332
- run_btn.click(
333
- fn=generate,
334
- inputs=[brand, audience, objective, platform, tone, hashtags, use_llm,
335
- li_max_words, tweet_max_chars, article_max_words],
336
- outputs=[strategy_md, social_tb, download_file]
337
  )
338
 
339
- # In Colab, share=True is handy
340
- demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
 
 
 
 
20
  "Settings → Secrets and add OPENAI_API_KEY."
21
  )
22
 
 
 
 
 
 
23
 
 
24
 
25
+
26
+ # ---------- Agents ----------
 
27
  lead_market_analyst = Agent(
28
  role="Lead Market Analyst",
29
+ goal="Deliver sharp, data-driven market insights for {product_brand}",
30
+ backstory=(
31
+ "A senior analyst skilled in competitor intelligence, audience segmentation, "
32
+ "channel dynamics, and market sizing, with a bias for actionable insights."
33
+ ),
34
  allow_delegation=False,
35
+ verbose=True
36
  )
37
 
38
  chief_marketing_strategist = Agent(
39
  role="Chief Marketing Strategist",
40
+ goal="Turn research into a focused, measurable go-to-market strategy for {product_brand}",
41
+ backstory=(
42
+ "A veteran strategist who crafts positioning, messaging pillars, channel mix, "
43
+ "and KPI frameworks—aligning cross-functional stakeholders and timelines."
44
+ ),
45
+ # Manager/orchestrator: can hand off sub-tasks or ask questions to teammates
46
+ allow_delegation=True,
47
+ verbose=True
48
  )
49
 
50
  creative_content_creator = Agent(
51
  role="Creative Content Creator",
52
+ goal="Transform the strategy into compelling creative concepts and a content calendar",
53
+ backstory=(
54
+ "A concept-to-copy creative who converts strategy into campaign ideas, ad copy, "
55
+ "social posts, and SEO-ready long-form content."
56
+ ),
 
 
 
 
 
 
 
57
  allow_delegation=False,
58
+ verbose=True
59
  )
60
 
61
+ # ---------- Crew runner ----------
62
+ def run_crewai_marketing_strategy(product_brand: str, target_audience: str, objective: str):
63
+ # Compose a shared topic string for clarity across tasks
 
64
  topic = f"{product_brand} | Audience: {target_audience} | Objective: {objective}"
65
 
66
+ # 1) Market Analysis
67
  market_analysis_task = Task(
68
  description=(
69
+ "Conduct a concise but thorough market analysis for the topic: {topic}. "
70
  "Cover: (1) ICP & segments, (2) JTBD/pain points & objections, "
71
  "(3) competitive landscape & whitespace, (4) demand signals & seasonality, "
72
  "(5) channel dynamics (search/social/email/partners/events), "
73
  "(6) keyword themes & content gaps, (7) risks/assumptions."
74
  ),
75
  expected_output=(
76
+ "A structured brief with bullet points for each section above, "
77
+ "ending with a 5–8 point summary of the most actionable insights."
78
  ),
79
+ agent=lead_market_analyst,
80
+ input_variables={"topic": topic}
81
  )
82
 
83
+ # 2) Strategy Formulation (manager)
84
  strategy_task = Task(
85
  description=(
86
+ "Using the Market Analysis brief, craft a go-to-market strategy for {topic}. "
87
  "Include: positioning statement, value prop, 3–5 messaging pillars, "
88
  "priority segments, channel mix with rationale, offer/CTA ideas, "
89
  "90-day roadmap (phases & owners), KPI tree (primary/leading indicators), "
90
  "and a lightweight budget allocation (% by channel)."
91
  ),
92
+ expected_output=(
93
+ "A strategy document with clear sections as listed, plus a one-page executive summary."
94
+ ),
95
  agent=chief_marketing_strategist,
96
+ input_variables={"topic": topic},
97
  context=[market_analysis_task]
98
  )
99
 
100
+ # 3) Creative & Content Plan
101
  creative_task = Task(
102
  description=(
103
  "Based on the Strategy, produce: (a) 3 campaign concepts (hook, angle, proof), "
104
+ "(b) ad copy variants (paid search, paid social), "
105
+ "(c) a 4-week content calendar (blog/LI/X/YouTube/Newsletter) with titles, "
106
+ "briefs, CTAs, and intended KPIs, and (d) landing-page wireframe outline "
107
  "(hero, value blocks, social proof, FAQ)."
108
  ),
109
+ expected_output=(
110
+ "Campaign concepts + copy, a tabular content calendar, and a structured LP outline."
111
+ ),
112
  agent=creative_content_creator,
113
+ input_variables={"topic": topic},
114
  context=[strategy_task]
115
  )
116
 
117
  crew = Crew(
118
  agents=[lead_market_analyst, chief_marketing_strategist, creative_content_creator],
119
+ tasks=[market_analysis_task, strategy_task, creative_task]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  )
122
 
123
+ result = crew.kickoff()
124
+ return result
125
+
126
+ # ---------- Gradio app ----------
127
+ def generate_strategy(product_brand, target_audience, objective):
128
+ return run_crewai_marketing_strategy(product_brand, target_audience, objective)
129
+
130
+ iface = gr.Interface(
131
+ fn=generate_strategy,
132
+ inputs=[
133
+ gr.Textbox(lines=1, label="Product / Brand", placeholder="e.g., SaaS analytics platform"),
134
+ gr.Textbox(lines=1, label="Target Audience", placeholder="e.g., mid-market product managers in EMEA"),
135
+ gr.Textbox(lines=1, label="Primary Objective", placeholder="e.g., drive free trials / demo requests")
136
+ ],
137
+ outputs=gr.Textbox(lines=28, label="Marketing Strategy & Content Plan"),
138
+ title="DDS • AI Crew for Marketing Strategy",
139
+ description="Provide brand, audience, and objective. The crew analyzes the market, builds a GTM strategy, and outputs creative + a content calendar."
140
+ )
141
 
142
+ if __name__ == "__main__":
143
+ iface.launch()