Spaces:
Paused
Paused
CBV01 commited on
Commit ·
ecc25e4
1
Parent(s): 932439c
Fix campaign card status colors, AI copy generation parsing, sample benchmark directive, and neat paragraph formatting
Browse files- backend/main.py +183 -76
- frontend/src/app/campaigns/page.tsx +41 -25
- frontend/src/components/TemplateAiAssistantModal.tsx +16 -8
backend/main.py
CHANGED
|
@@ -4506,6 +4506,74 @@ class AITemplateVariationsRequest(BaseModel):
|
|
| 4506 |
count: Optional[int] = 5
|
| 4507 |
length: Optional[str] = "moderate" # 'short' | 'moderate' | 'lengthy'
|
| 4508 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4509 |
@app.post("/api/ai/generate-template-variations")
|
| 4510 |
async def generate_template_variations(req: AITemplateVariationsRequest, user_id: str = Depends(get_current_user_id)):
|
| 4511 |
"""Generates 5 distinct high-converting Telegram template variations with custom length and structure."""
|
|
@@ -4528,30 +4596,31 @@ async def generate_template_variations(req: AITemplateVariationsRequest, user_id
|
|
| 4528 |
|
| 4529 |
if volume == "short":
|
| 4530 |
volume_guidelines = (
|
| 4531 |
-
"TARGET LENGTH: SHORT & PUNCHY (approx 45-
|
| 4532 |
-
"-
|
| 4533 |
"- 2-3 crisp bullet highlights (✅, 💎) on separate lines.\n"
|
| 4534 |
"- Quick, direct call to action with instruction (e.g. Reply 'INFO' or tap link)."
|
| 4535 |
)
|
|
|
|
| 4536 |
elif volume == "lengthy":
|
| 4537 |
volume_guidelines = (
|
| 4538 |
-
"TARGET LENGTH: LENGTHY, DETAILED & COMPREHENSIVE (approx
|
| 4539 |
"- Attention-grabbing headline hook with emojis (e.g. 📺🔥 ...).\n"
|
| 4540 |
"- Opening paragraph: Intriguing problem/solution question or compelling proposition.\n"
|
| 4541 |
-
"- Section 1 with header (e.g. ✅ WHAT WE OFFER) followed by
|
| 4542 |
-
"- Section 2 with header (e.g. 💎 WHY CHOOSE US) followed by
|
| 4543 |
-
"-
|
| 4544 |
-
"- Clear CTA with instructions (e.g. 💬 Reply 'SUBSCRIBE' or DM to get started).\n"
|
| 4545 |
-
"- Brief disclaimer/licensing note at the bottom."
|
| 4546 |
)
|
|
|
|
| 4547 |
else: # moderate
|
| 4548 |
volume_guidelines = (
|
| 4549 |
-
"TARGET LENGTH: MODERATE & BALANCED (approx
|
| 4550 |
"- Compelling hook headline with emojis.\n"
|
| 4551 |
"- 1 structured paragraph explaining why this offer matters.\n"
|
| 4552 |
-
"-
|
| 4553 |
-
"- Clear call to action link."
|
| 4554 |
)
|
|
|
|
| 4555 |
|
| 4556 |
spintax_rule = (
|
| 4557 |
"Incorporate natural Spintax variations {Option 1|Option 2|Option 3} in greetings, CTAs, adjectives, and key phrases so each message rotates dynamically."
|
|
@@ -4561,42 +4630,59 @@ async def generate_template_variations(req: AITemplateVariationsRequest, user_id
|
|
| 4561 |
sample_section = ""
|
| 4562 |
if sample_copy:
|
| 4563 |
sample_section = (
|
| 4564 |
-
f"\n\
|
| 4565 |
-
f"\
|
| 4566 |
-
f"
|
| 4567 |
-
f"
|
| 4568 |
-
f"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4569 |
)
|
| 4570 |
|
| 4571 |
sys_prompt = (
|
| 4572 |
-
f"You are
|
| 4573 |
-
f"
|
| 4574 |
-
f"
|
| 4575 |
f"{sample_section}\n\n"
|
| 4576 |
-
f"
|
| 4577 |
-
f"Generate exactly {target_count} unique, high-converting Telegram
|
| 4578 |
f"Cover diverse marketing angles:\n"
|
| 4579 |
-
f"- Variation 1: Direct Value & Clear Offer\n"
|
| 4580 |
-
f"- Variation 2: Curiosity &
|
| 4581 |
f"- Variation 3: Social Proof & Problem-Solver\n"
|
| 4582 |
-
f"- Variation 4:
|
| 4583 |
f"- Variation 5: High Urgency & Limited-Time Perk\n\n"
|
| 4584 |
-
f"
|
| 4585 |
-
f"1.
|
| 4586 |
-
f"2. MANDATORY DOUBLE LINE BREAKS: You MUST separate
|
| 4587 |
-
f"3.
|
| 4588 |
f"4. {volume_guidelines}\n"
|
| 4589 |
-
f"5. {spintax_rule}\n"
|
| 4590 |
-
f"
|
| 4591 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4592 |
)
|
| 4593 |
|
| 4594 |
-
async with httpx.AsyncClient(timeout=
|
| 4595 |
try:
|
| 4596 |
payload: Dict[str, Any] = {
|
| 4597 |
"model": selected_model,
|
| 4598 |
"messages": [{"role": "user", "content": sys_prompt}],
|
| 4599 |
-
"max_tokens":
|
| 4600 |
"include_reasoning": False
|
| 4601 |
}
|
| 4602 |
if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
|
|
@@ -4618,49 +4704,67 @@ async def generate_template_variations(req: AITemplateVariationsRequest, user_id
|
|
| 4618 |
if choices:
|
| 4619 |
msg = choices[0].get("message") or {}
|
| 4620 |
raw_text = msg.get("content") or ""
|
| 4621 |
-
cleaned = re.sub(r'<think>[\s\S]*?</think>', '', raw_text, flags=re.IGNORECASE)
|
| 4622 |
-
|
|
|
|
| 4623 |
|
| 4624 |
-
#
|
| 4625 |
-
|
| 4626 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4627 |
variations = []
|
| 4628 |
-
|
| 4629 |
-
|
| 4630 |
-
|
| 4631 |
-
|
| 4632 |
-
|
| 4633 |
-
|
| 4634 |
-
|
| 4635 |
-
|
| 4636 |
-
continue
|
| 4637 |
-
if len(t) > 20:
|
| 4638 |
-
variations.append(t)
|
| 4639 |
-
except Exception:
|
| 4640 |
-
try:
|
| 4641 |
-
fixed = re.sub(r',\s*\]', ']', cleaned[start:end+1])
|
| 4642 |
-
parsed = json.loads(fixed)
|
| 4643 |
-
if isinstance(parsed, list):
|
| 4644 |
-
for x in parsed:
|
| 4645 |
-
t = str(x).replace('\\n', '\n').strip()
|
| 4646 |
-
t = re.sub(r'\n{3,}', '\n\n', t)
|
| 4647 |
-
if sample_copy and t.strip().lower() == sample_copy.strip().lower():
|
| 4648 |
-
continue
|
| 4649 |
-
if len(t) > 20:
|
| 4650 |
-
variations.append(t)
|
| 4651 |
-
except Exception:
|
| 4652 |
-
pass
|
| 4653 |
-
|
| 4654 |
-
if not variations:
|
| 4655 |
-
blocks = re.split(r'\n(?=(?:Variation|\d+[\.\)]))\s*', cleaned)
|
| 4656 |
-
for b in blocks:
|
| 4657 |
-
t = re.sub(r'^(?:Variation\s*\d+:?|\d+[\.\)])\s*', '', b).strip().strip('"\'')
|
| 4658 |
-
t = t.replace('\\n', '\n')
|
| 4659 |
-
t = re.sub(r'\n{3,}', '\n\n', t)
|
| 4660 |
-
if sample_copy and t.strip().lower() == sample_copy.strip().lower():
|
| 4661 |
-
continue
|
| 4662 |
-
if len(t) > 20:
|
| 4663 |
-
variations.append(t)
|
| 4664 |
|
| 4665 |
if variations:
|
| 4666 |
return {
|
|
@@ -4672,10 +4776,13 @@ async def generate_template_variations(req: AITemplateVariationsRequest, user_id
|
|
| 4672 |
raise HTTPException(status_code=400, detail="Could not parse message variations from AI response.")
|
| 4673 |
else:
|
| 4674 |
try:
|
| 4675 |
-
|
|
|
|
| 4676 |
except Exception:
|
| 4677 |
-
err_msg = res.text[:
|
| 4678 |
raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error ({res.status_code}): {err_msg}")
|
|
|
|
|
|
|
| 4679 |
except HTTPException:
|
| 4680 |
raise
|
| 4681 |
except Exception as e:
|
|
|
|
| 4506 |
count: Optional[int] = 5
|
| 4507 |
length: Optional[str] = "moderate" # 'short' | 'moderate' | 'lengthy'
|
| 4508 |
|
| 4509 |
+
def clean_and_format_telegram_copy(text: str) -> str:
|
| 4510 |
+
"""Cleans and guarantees human-readable paragraph formatting, bullet alignment, and neat spacing for Telegram copy."""
|
| 4511 |
+
if not text:
|
| 4512 |
+
return ""
|
| 4513 |
+
|
| 4514 |
+
# 1. Normalize line endings and unescape literal \n
|
| 4515 |
+
text = text.replace('\\r\\n', '\n').replace('\\n', '\n').replace('\r\n', '\n').replace('\r', '\n')
|
| 4516 |
+
|
| 4517 |
+
# 2. Strip outer markdown code fences if present
|
| 4518 |
+
text = text.strip()
|
| 4519 |
+
if text.startswith('```') and text.endswith('```'):
|
| 4520 |
+
text = re.sub(r'^```[a-zA-Z]*\n', '', text)
|
| 4521 |
+
text = re.sub(r'\n```$', '', text)
|
| 4522 |
+
text = text.strip()
|
| 4523 |
+
|
| 4524 |
+
# Strip accidental outer quotes or markdown bold prefixes like **Variation 1:**
|
| 4525 |
+
text = re.sub(r'^(?:\*{1,2})?(?:Variation|Angle|Option)\s*\d+[\:\.\-\)]?(?:\*{1,2})?\s*', '', text, flags=re.IGNORECASE)
|
| 4526 |
+
if (text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'")):
|
| 4527 |
+
text = text[1:-1].strip()
|
| 4528 |
+
|
| 4529 |
+
lines = [line.strip() for line in text.split('\n')]
|
| 4530 |
+
bullet_symbols = r'[•\-\*▪️▫️🔹🔸▶️✅✔️⚡🔥💎📡🚀👉📺📱⚽🎬🌍🔧🤝🎉💥💰]'
|
| 4531 |
+
|
| 4532 |
+
# Separate multiple bullets squashed on a single line
|
| 4533 |
+
expanded_lines = []
|
| 4534 |
+
for line in lines:
|
| 4535 |
+
if not line:
|
| 4536 |
+
expanded_lines.append("")
|
| 4537 |
+
continue
|
| 4538 |
+
# Split squashed bullet items e.g. "• Item 1 • Item 2" or "✅ Feature A ✅ Feature B"
|
| 4539 |
+
split_items = re.split(rf'(?<=[^\s])\s+(?={bullet_symbols}\s+)', line)
|
| 4540 |
+
for item in split_items:
|
| 4541 |
+
sub = item.strip()
|
| 4542 |
+
if sub:
|
| 4543 |
+
expanded_lines.append(sub)
|
| 4544 |
+
|
| 4545 |
+
# Reassemble with smart paragraph spacing
|
| 4546 |
+
structured = []
|
| 4547 |
+
for line in expanded_lines:
|
| 4548 |
+
if not line:
|
| 4549 |
+
if structured and structured[-1] != "":
|
| 4550 |
+
structured.append("")
|
| 4551 |
+
continue
|
| 4552 |
+
|
| 4553 |
+
is_bullet = bool(re.match(rf'^{bullet_symbols}', line))
|
| 4554 |
+
is_header = bool(re.match(r'^(?:[A-Z0-9\s\&\-\/]{4,}:|🔥|⚡|💎|📺|🚀|✨|🌟|🎯|📢|👇|💡)', line) and len(line) < 65 and not line.endswith('.'))
|
| 4555 |
+
is_cta = bool(re.search(r'(?:t\.me\/|https?:\/\/|reply|dm\s+us|contact|get\s+started|claim\s+now|order\s+now|message\s+us)', line, re.IGNORECASE) and len(line) < 120)
|
| 4556 |
+
|
| 4557 |
+
prev_line = structured[-1] if structured else None
|
| 4558 |
+
prev_is_bullet = bool(prev_line and re.match(rf'^{bullet_symbols}', prev_line))
|
| 4559 |
+
prev_is_blank = prev_line == "" or prev_line is None
|
| 4560 |
+
|
| 4561 |
+
# Add blank line before section headers or standalone CTAs if not already separated
|
| 4562 |
+
if (is_header or is_cta) and not prev_is_blank and not prev_is_bullet:
|
| 4563 |
+
structured.append("")
|
| 4564 |
+
elif is_header and prev_is_bullet:
|
| 4565 |
+
structured.append("")
|
| 4566 |
+
elif not is_bullet and prev_is_bullet:
|
| 4567 |
+
# Bullet list just ended; separate following paragraph with a blank line
|
| 4568 |
+
structured.append("")
|
| 4569 |
+
|
| 4570 |
+
structured.append(line)
|
| 4571 |
+
|
| 4572 |
+
result_text = "\n".join(structured)
|
| 4573 |
+
# Ensure no more than 2 consecutive newlines
|
| 4574 |
+
result_text = re.sub(r'\n{3,}', '\n\n', result_text).strip()
|
| 4575 |
+
return result_text
|
| 4576 |
+
|
| 4577 |
@app.post("/api/ai/generate-template-variations")
|
| 4578 |
async def generate_template_variations(req: AITemplateVariationsRequest, user_id: str = Depends(get_current_user_id)):
|
| 4579 |
"""Generates 5 distinct high-converting Telegram template variations with custom length and structure."""
|
|
|
|
| 4596 |
|
| 4597 |
if volume == "short":
|
| 4598 |
volume_guidelines = (
|
| 4599 |
+
"TARGET LENGTH: SHORT & PUNCHY (approx 45-70 words).\n"
|
| 4600 |
+
"- 1 bold, energetic headline hook with emojis (🔥, ⚡).\n"
|
| 4601 |
"- 2-3 crisp bullet highlights (✅, 💎) on separate lines.\n"
|
| 4602 |
"- Quick, direct call to action with instruction (e.g. Reply 'INFO' or tap link)."
|
| 4603 |
)
|
| 4604 |
+
max_tokens_val = 1500
|
| 4605 |
elif volume == "lengthy":
|
| 4606 |
volume_guidelines = (
|
| 4607 |
+
"TARGET LENGTH: LENGTHY, DETAILED & COMPREHENSIVE (approx 180-260 words).\n"
|
| 4608 |
"- Attention-grabbing headline hook with emojis (e.g. 📺🔥 ...).\n"
|
| 4609 |
"- Opening paragraph: Intriguing problem/solution question or compelling proposition.\n"
|
| 4610 |
+
"- Section 1 with header (e.g. ✅ WHAT WE OFFER:) followed by 5 to 7 bullet items on separate lines.\n"
|
| 4611 |
+
"- Section 2 with header (e.g. 💎 WHY CHOOSE US:) followed by 3 to 4 bullet points on separate lines.\n"
|
| 4612 |
+
"- Clear CTA with instructions (e.g. 💬 Reply 'SUBSCRIBE' or DM to get started)."
|
|
|
|
|
|
|
| 4613 |
)
|
| 4614 |
+
max_tokens_val = 2600
|
| 4615 |
else: # moderate
|
| 4616 |
volume_guidelines = (
|
| 4617 |
+
"TARGET LENGTH: MODERATE & BALANCED (approx 90-150 words).\n"
|
| 4618 |
"- Compelling hook headline with emojis.\n"
|
| 4619 |
"- 1 structured paragraph explaining why this offer matters.\n"
|
| 4620 |
+
"- 3-5 organized bullet points highlighting key features on separate lines.\n"
|
| 4621 |
+
"- Clear call to action link/handle."
|
| 4622 |
)
|
| 4623 |
+
max_tokens_val = 2000
|
| 4624 |
|
| 4625 |
spintax_rule = (
|
| 4626 |
"Incorporate natural Spintax variations {Option 1|Option 2|Option 3} in greetings, CTAs, adjectives, and key phrases so each message rotates dynamically."
|
|
|
|
| 4630 |
sample_section = ""
|
| 4631 |
if sample_copy:
|
| 4632 |
sample_section = (
|
| 4633 |
+
f"\n\n=================================================================\n"
|
| 4634 |
+
f"REFERENCE SAMPLE COPY (BENCHMARK FOR STYLE, STRUCTURE & LENGTH ONLY):\n"
|
| 4635 |
+
f"\"\"\"\n{sample_copy}\n\"\"\"\n\n"
|
| 4636 |
+
f"CRITICAL DIRECTIVE ON USING THIS SAMPLE:\n"
|
| 4637 |
+
f"- DO NOT COPY, REPHRASE, OR REUSE THE SAMPLE'S WORDS, PRODUCT NAMES, OR SPECIFIC OFFER DETAILS!\n"
|
| 4638 |
+
f"- The sample is provided SOLELY to show the desired layout style, tone of voice, pacing, and length.\n"
|
| 4639 |
+
f"- You must write 100% BRAND NEW, ORIGINAL copy dedicated EXCLUSIVELY to the user's specific offer/prompt:\n"
|
| 4640 |
+
f" Offer/Topic: \"{user_prompt}\"\n"
|
| 4641 |
+
f"- Under no circumstances should you echo the sample text back.\n"
|
| 4642 |
+
f"=================================================================\n"
|
| 4643 |
)
|
| 4644 |
|
| 4645 |
sys_prompt = (
|
| 4646 |
+
f"You are an elite conversion copywriter specializing in high-converting Telegram broadcast copy.\n\n"
|
| 4647 |
+
f"USER OFFER / PROMPT:\n"
|
| 4648 |
+
f"\"\"\"\n{user_prompt}\n\"\"\""
|
| 4649 |
f"{sample_section}\n\n"
|
| 4650 |
+
f"YOUR TASK:\n"
|
| 4651 |
+
f"Generate exactly {target_count} unique, high-converting Telegram broadcast variations for this offer.\n"
|
| 4652 |
f"Cover diverse marketing angles:\n"
|
| 4653 |
+
f"- Variation 1: Direct Value & Clear Free Trial / Starter Offer\n"
|
| 4654 |
+
f"- Variation 2: Curiosity & Exclusive VIP Hook\n"
|
| 4655 |
f"- Variation 3: Social Proof & Problem-Solver\n"
|
| 4656 |
+
f"- Variation 4: Conversational Question / Engaging Dialogue\n"
|
| 4657 |
f"- Variation 5: High Urgency & Limited-Time Perk\n\n"
|
| 4658 |
+
f"MANDATORY FORMATTING & PARAGRAPH RULES:\n"
|
| 4659 |
+
f"1. TELEGRAM BROADCAST FORMAT: Hook the reader immediately. Never start with 'Hello {{First Name}}' email letters.\n"
|
| 4660 |
+
f"2. MANDATORY DOUBLE LINE BREAKS (\\n\\n): You MUST separate headlines, body paragraphs, section titles, bullet lists, and CTA with empty lines (\\n\\n). NEVER clump sentences together into one wall of text.\n"
|
| 4661 |
+
f"3. BULLET POINTS ON DEDICATED LINES: Every bullet point (•, ✅, ⚡, 🔥, 💎, etc.) MUST start on its own fresh line.\n"
|
| 4662 |
f"4. {volume_guidelines}\n"
|
| 4663 |
+
f"5. {spintax_rule}\n\n"
|
| 4664 |
+
f"CRITICAL OUTPUT FORMAT INSTRUCTION:\n"
|
| 4665 |
+
f"Separate each variation using the exact delimiter:\n"
|
| 4666 |
+
f"===VARIATION===\n\n"
|
| 4667 |
+
f"Do NOT return JSON. Do NOT wrap in markdown code blocks. Do NOT include conversational preamble or explanations.\n"
|
| 4668 |
+
f"Simply output:\n"
|
| 4669 |
+
f"[Variation 1 copy]\n"
|
| 4670 |
+
f"===VARIATION===\n"
|
| 4671 |
+
f"[Variation 2 copy]\n"
|
| 4672 |
+
f"===VARIATION===\n"
|
| 4673 |
+
f"[Variation 3 copy]\n"
|
| 4674 |
+
f"===VARIATION===\n"
|
| 4675 |
+
f"[Variation 4 copy]\n"
|
| 4676 |
+
f"===VARIATION===\n"
|
| 4677 |
+
f"[Variation 5 copy]"
|
| 4678 |
)
|
| 4679 |
|
| 4680 |
+
async with httpx.AsyncClient(timeout=85.0) as client:
|
| 4681 |
try:
|
| 4682 |
payload: Dict[str, Any] = {
|
| 4683 |
"model": selected_model,
|
| 4684 |
"messages": [{"role": "user", "content": sys_prompt}],
|
| 4685 |
+
"max_tokens": max_tokens_val,
|
| 4686 |
"include_reasoning": False
|
| 4687 |
}
|
| 4688 |
if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
|
|
|
|
| 4704 |
if choices:
|
| 4705 |
msg = choices[0].get("message") or {}
|
| 4706 |
raw_text = msg.get("content") or ""
|
| 4707 |
+
cleaned = re.sub(r'<think>[\s\S]*?</think>', '', raw_text, flags=re.IGNORECASE).strip()
|
| 4708 |
+
|
| 4709 |
+
raw_variations = []
|
| 4710 |
|
| 4711 |
+
# Strategy 1: Delimiter ===VARIATION=== or ---VARIATION---
|
| 4712 |
+
if re.search(r'={3,}\s*VARIATION(?:\s*\d+)?\s*={3,}|-{3,}\s*VARIATION(?:\s*\d+)?\s*-{3,}', cleaned, re.IGNORECASE):
|
| 4713 |
+
parts = re.split(r'={3,}\s*VARIATION(?:\s*\d+)?\s*={3,}|-{3,}\s*VARIATION(?:\s*\d+)?\s*-{3,}', cleaned, flags=re.IGNORECASE)
|
| 4714 |
+
for p in parts:
|
| 4715 |
+
p_clean = p.strip()
|
| 4716 |
+
if len(p_clean) > 20:
|
| 4717 |
+
raw_variations.append(p_clean)
|
| 4718 |
+
|
| 4719 |
+
# Strategy 2: JSON array (if model output JSON despite instructions)
|
| 4720 |
+
if not raw_variations:
|
| 4721 |
+
start_b = cleaned.find('[')
|
| 4722 |
+
end_b = cleaned.rfind(']')
|
| 4723 |
+
if start_b != -1 and end_b > start_b:
|
| 4724 |
+
json_slice = cleaned[start_b:end_b+1]
|
| 4725 |
+
for attempt in [json_slice, re.sub(r',\s*\]', ']', json_slice)]:
|
| 4726 |
+
try:
|
| 4727 |
+
parsed = json.loads(attempt)
|
| 4728 |
+
if isinstance(parsed, list):
|
| 4729 |
+
for item in parsed:
|
| 4730 |
+
s = str(item).strip()
|
| 4731 |
+
if len(s) > 20:
|
| 4732 |
+
raw_variations.append(s)
|
| 4733 |
+
if raw_variations:
|
| 4734 |
+
break
|
| 4735 |
+
except Exception:
|
| 4736 |
+
pass
|
| 4737 |
+
|
| 4738 |
+
# Strategy 3: Numbered or markdown headings (e.g. "Variation 1:", "### Variation 1", "1.")
|
| 4739 |
+
if not raw_variations:
|
| 4740 |
+
splits = re.split(r'\n+(?=(?:#{1,3}\s*|(?:\*{1,2})?)(?:Variation|Option|Angle)\s*\d+|(?:^|\n)\d+[\.\)]\s*(?:\*{1,2})?(?:Variation|Angle|Option|[A-Z]))', cleaned, flags=re.IGNORECASE)
|
| 4741 |
+
for sp in splits:
|
| 4742 |
+
sp_clean = re.sub(r'^(?:#{1,3}\s*|(?:\*{1,2})?)(?:Variation|Option|Angle)\s*\d+[\:\.\-\)]?(?:\*{1,2})?\s*', '', sp.strip(), flags=re.IGNORECASE).strip()
|
| 4743 |
+
if len(sp_clean) > 20:
|
| 4744 |
+
raw_variations.append(sp_clean)
|
| 4745 |
+
|
| 4746 |
+
# Strategy 4: Horizontal lines (---)
|
| 4747 |
+
if not raw_variations and '---' in cleaned:
|
| 4748 |
+
parts = cleaned.split('---')
|
| 4749 |
+
for p in parts:
|
| 4750 |
+
p_clean = p.strip()
|
| 4751 |
+
if len(p_clean) > 20:
|
| 4752 |
+
raw_variations.append(p_clean)
|
| 4753 |
+
|
| 4754 |
+
# Strategy 5: Single block fallback
|
| 4755 |
+
if not raw_variations and len(cleaned) > 20:
|
| 4756 |
+
raw_variations.append(cleaned)
|
| 4757 |
+
|
| 4758 |
+
# Clean, format paragraphs & filter variations
|
| 4759 |
variations = []
|
| 4760 |
+
sample_norm = sample_copy.strip().lower() if sample_copy else ""
|
| 4761 |
+
for v in raw_variations:
|
| 4762 |
+
formatted = clean_and_format_telegram_copy(v)
|
| 4763 |
+
# Exclude if it accidentally echoed the sample verbatim
|
| 4764 |
+
if sample_norm and formatted.strip().lower() == sample_norm:
|
| 4765 |
+
continue
|
| 4766 |
+
if len(formatted) > 20:
|
| 4767 |
+
variations.append(formatted)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4768 |
|
| 4769 |
if variations:
|
| 4770 |
return {
|
|
|
|
| 4776 |
raise HTTPException(status_code=400, detail="Could not parse message variations from AI response.")
|
| 4777 |
else:
|
| 4778 |
try:
|
| 4779 |
+
err_data = res.json()
|
| 4780 |
+
err_msg = err_data.get("error", {}).get("message") or res.text[:200]
|
| 4781 |
except Exception:
|
| 4782 |
+
err_msg = res.text[:200]
|
| 4783 |
raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error ({res.status_code}): {err_msg}")
|
| 4784 |
+
except httpx.TimeoutException:
|
| 4785 |
+
raise HTTPException(status_code=504, detail="AI generation timed out. OpenRouter is experiencing latency. Please try again.")
|
| 4786 |
except HTTPException:
|
| 4787 |
raise
|
| 4788 |
except Exception as e:
|
frontend/src/app/campaigns/page.tsx
CHANGED
|
@@ -548,15 +548,16 @@ export default function CampaignsPage() {
|
|
| 548 |
}
|
| 549 |
};
|
| 550 |
|
| 551 |
-
const getCampaignCardStyle = (
|
|
|
|
| 552 |
switch (status) {
|
| 553 |
case 'completed':
|
| 554 |
return {
|
| 555 |
topBeamColor: 'from-transparent via-teal-400 to-transparent',
|
| 556 |
-
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(45, 212, 191, 0.
|
| 557 |
-
iconBg: 'bg-
|
| 558 |
-
dotColor: 'bg-
|
| 559 |
-
accentText: 'text-
|
| 560 |
ringColor: '#2dd4bf',
|
| 561 |
statusText: 'COMPLETED',
|
| 562 |
actionBtn: 'bg-teal-500/15 text-teal-300 hover:bg-teal-500/25 border border-teal-500/30'
|
|
@@ -566,10 +567,10 @@ export default function CampaignsPage() {
|
|
| 566 |
case 'running':
|
| 567 |
return {
|
| 568 |
topBeamColor: 'from-transparent via-emerald-400 to-transparent',
|
| 569 |
-
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(52, 211, 153, 0.
|
| 570 |
-
iconBg: 'bg-
|
| 571 |
-
dotColor: 'bg-
|
| 572 |
-
accentText: 'text-
|
| 573 |
ringColor: '#34d399',
|
| 574 |
statusText: 'ACTIVE',
|
| 575 |
actionBtn: 'bg-white/[0.04] text-neutral-300 hover:bg-white/[0.08] border border-white/[0.08]'
|
|
@@ -577,10 +578,10 @@ export default function CampaignsPage() {
|
|
| 577 |
case 'paused':
|
| 578 |
return {
|
| 579 |
topBeamColor: 'from-transparent via-amber-400 to-transparent',
|
| 580 |
-
radialGlow: 'radial-gradient(circle at 50% -20%, rgba(251, 191, 36, 0.
|
| 581 |
-
iconBg: 'bg-
|
| 582 |
-
dotColor: 'bg-
|
| 583 |
-
accentText: 'text-
|
| 584 |
ringColor: '#fbbf24',
|
| 585 |
statusText: 'PAUSED',
|
| 586 |
actionBtn: 'bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 border border-amber-500/30'
|
|
@@ -589,23 +590,38 @@ export default function CampaignsPage() {
|
|
| 589 |
case 'error':
|
| 590 |
return {
|
| 591 |
topBeamColor: 'from-transparent via-rose-400 to-transparent',
|
| 592 |
-
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(244, 63, 94, 0.
|
| 593 |
-
iconBg: 'bg-
|
| 594 |
-
dotColor: 'bg-
|
| 595 |
-
accentText: 'text-
|
| 596 |
ringColor: '#fb7185',
|
| 597 |
statusText: 'FAILED',
|
| 598 |
actionBtn: 'bg-rose-500/15 text-rose-300 hover:bg-rose-500/25 border border-rose-500/30'
|
| 599 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
default:
|
| 601 |
return {
|
| 602 |
-
topBeamColor: 'from-transparent via-sky-400
|
| 603 |
-
radialGlow: 'radial-gradient(circle at 50% -20%, rgba(56, 189, 248, 0.
|
| 604 |
-
iconBg: 'bg-
|
| 605 |
-
dotColor: 'bg-
|
| 606 |
-
accentText: 'text-
|
| 607 |
ringColor: '#38bdf8',
|
| 608 |
-
statusText: status ?
|
| 609 |
actionBtn: 'bg-sky-500/15 text-sky-300 hover:bg-sky-500/25 border border-sky-500/30'
|
| 610 |
};
|
| 611 |
}
|
|
@@ -793,7 +809,7 @@ export default function CampaignsPage() {
|
|
| 793 |
return (
|
| 794 |
<div
|
| 795 |
key={camp.id}
|
| 796 |
-
className="relative rounded-2xl bg-[#
|
| 797 |
style={{ backgroundImage: cardStyle.radialGlow !== 'none' ? cardStyle.radialGlow : undefined }}
|
| 798 |
>
|
| 799 |
{/* Angled Glowing Top Beam */}
|
|
@@ -1023,7 +1039,7 @@ export default function CampaignsPage() {
|
|
| 1023 |
return (
|
| 1024 |
<div
|
| 1025 |
key={camp.id}
|
| 1026 |
-
className="relative rounded-2xl bg-[#
|
| 1027 |
style={{ backgroundImage: cardStyle.radialGlow !== 'none' ? cardStyle.radialGlow : undefined }}
|
| 1028 |
>
|
| 1029 |
{/* Angled Glowing Top Beam */}
|
|
|
|
| 548 |
}
|
| 549 |
};
|
| 550 |
|
| 551 |
+
const getCampaignCardStyle = (rawStatus: string) => {
|
| 552 |
+
const status = (rawStatus || '').toLowerCase().trim();
|
| 553 |
switch (status) {
|
| 554 |
case 'completed':
|
| 555 |
return {
|
| 556 |
topBeamColor: 'from-transparent via-teal-400 to-transparent',
|
| 557 |
+
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(45, 212, 191, 0.14) 0%, rgba(45, 212, 191, 0.02) 40%, transparent 70%)',
|
| 558 |
+
iconBg: 'bg-teal-500/15 text-teal-300 border border-teal-500/25',
|
| 559 |
+
dotColor: 'bg-teal-400',
|
| 560 |
+
accentText: 'text-teal-400',
|
| 561 |
ringColor: '#2dd4bf',
|
| 562 |
statusText: 'COMPLETED',
|
| 563 |
actionBtn: 'bg-teal-500/15 text-teal-300 hover:bg-teal-500/25 border border-teal-500/30'
|
|
|
|
| 567 |
case 'running':
|
| 568 |
return {
|
| 569 |
topBeamColor: 'from-transparent via-emerald-400 to-transparent',
|
| 570 |
+
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(52, 211, 153, 0.14) 0%, rgba(52, 211, 153, 0.02) 40%, transparent 70%)',
|
| 571 |
+
iconBg: 'bg-emerald-500/15 text-emerald-300 border border-emerald-500/25',
|
| 572 |
+
dotColor: 'bg-emerald-400',
|
| 573 |
+
accentText: 'text-emerald-400',
|
| 574 |
ringColor: '#34d399',
|
| 575 |
statusText: 'ACTIVE',
|
| 576 |
actionBtn: 'bg-white/[0.04] text-neutral-300 hover:bg-white/[0.08] border border-white/[0.08]'
|
|
|
|
| 578 |
case 'paused':
|
| 579 |
return {
|
| 580 |
topBeamColor: 'from-transparent via-amber-400 to-transparent',
|
| 581 |
+
radialGlow: 'radial-gradient(circle at 50% -20%, rgba(251, 191, 36, 0.14) 0%, rgba(251, 191, 36, 0.02) 40%, transparent 70%)',
|
| 582 |
+
iconBg: 'bg-amber-500/15 text-amber-300 border border-amber-500/25',
|
| 583 |
+
dotColor: 'bg-amber-400',
|
| 584 |
+
accentText: 'text-amber-400',
|
| 585 |
ringColor: '#fbbf24',
|
| 586 |
statusText: 'PAUSED',
|
| 587 |
actionBtn: 'bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 border border-amber-500/30'
|
|
|
|
| 590 |
case 'error':
|
| 591 |
return {
|
| 592 |
topBeamColor: 'from-transparent via-rose-400 to-transparent',
|
| 593 |
+
radialGlow: 'radial-gradient(circle at 45% -20%, rgba(244, 63, 94, 0.14) 0%, rgba(244, 63, 94, 0.02) 40%, transparent 70%)',
|
| 594 |
+
iconBg: 'bg-rose-500/15 text-rose-300 border border-rose-500/25',
|
| 595 |
+
dotColor: 'bg-rose-400',
|
| 596 |
+
accentText: 'text-rose-400',
|
| 597 |
ringColor: '#fb7185',
|
| 598 |
statusText: 'FAILED',
|
| 599 |
actionBtn: 'bg-rose-500/15 text-rose-300 hover:bg-rose-500/25 border border-rose-500/30'
|
| 600 |
};
|
| 601 |
+
case 'cancelled':
|
| 602 |
+
case 'canceled':
|
| 603 |
+
return {
|
| 604 |
+
topBeamColor: 'from-transparent via-slate-400 to-transparent',
|
| 605 |
+
radialGlow: 'radial-gradient(circle at 50% -20%, rgba(148, 163, 184, 0.12) 0%, transparent 65%)',
|
| 606 |
+
iconBg: 'bg-slate-500/15 text-slate-300 border border-slate-500/25',
|
| 607 |
+
dotColor: 'bg-slate-400',
|
| 608 |
+
accentText: 'text-slate-400',
|
| 609 |
+
ringColor: '#94a3b8',
|
| 610 |
+
statusText: 'CANCELLED',
|
| 611 |
+
actionBtn: 'bg-slate-500/15 text-slate-300 hover:bg-slate-500/25 border border-slate-500/30'
|
| 612 |
+
};
|
| 613 |
+
case 'pending':
|
| 614 |
+
case 'scheduled':
|
| 615 |
+
case 'draft':
|
| 616 |
default:
|
| 617 |
return {
|
| 618 |
+
topBeamColor: 'from-transparent via-sky-400 to-transparent',
|
| 619 |
+
radialGlow: 'radial-gradient(circle at 50% -20%, rgba(56, 189, 248, 0.14) 0%, rgba(56, 189, 248, 0.02) 40%, transparent 70%)',
|
| 620 |
+
iconBg: 'bg-sky-500/15 text-sky-300 border border-sky-500/25',
|
| 621 |
+
dotColor: 'bg-sky-400',
|
| 622 |
+
accentText: 'text-sky-400',
|
| 623 |
ringColor: '#38bdf8',
|
| 624 |
+
statusText: status === 'scheduled' ? 'SCHEDULED' : (status === 'draft' ? 'DRAFT' : 'PENDING'),
|
| 625 |
actionBtn: 'bg-sky-500/15 text-sky-300 hover:bg-sky-500/25 border border-sky-500/30'
|
| 626 |
};
|
| 627 |
}
|
|
|
|
| 809 |
return (
|
| 810 |
<div
|
| 811 |
key={camp.id}
|
| 812 |
+
className="relative rounded-2xl bg-[#101216] border border-white/[0.06] p-4 sm:p-5 transition-all duration-300 hover:translate-y-[-2px] flex flex-col justify-between group/card shadow-sm overflow-hidden"
|
| 813 |
style={{ backgroundImage: cardStyle.radialGlow !== 'none' ? cardStyle.radialGlow : undefined }}
|
| 814 |
>
|
| 815 |
{/* Angled Glowing Top Beam */}
|
|
|
|
| 1039 |
return (
|
| 1040 |
<div
|
| 1041 |
key={camp.id}
|
| 1042 |
+
className="relative rounded-2xl bg-[#101216] border border-white/[0.06] p-3.5 sm:p-4 transition-all flex flex-col md:flex-row md:items-center justify-between gap-3.5 group/card overflow-hidden"
|
| 1043 |
style={{ backgroundImage: cardStyle.radialGlow !== 'none' ? cardStyle.radialGlow : undefined }}
|
| 1044 |
>
|
| 1045 |
{/* Angled Glowing Top Beam */}
|
frontend/src/components/TemplateAiAssistantModal.tsx
CHANGED
|
@@ -118,7 +118,12 @@ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }:
|
|
| 118 |
setVariations(data.variations);
|
| 119 |
setSamplePreviews({});
|
| 120 |
} else {
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
}
|
| 123 |
} catch (e: any) {
|
| 124 |
setError(e.message || 'Error communicating with AI assistant.');
|
|
@@ -245,7 +250,7 @@ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }:
|
|
| 245 |
? 'bg-amber-500/15 text-amber-300 border-amber-500/35 shadow-xs'
|
| 246 |
: 'bg-foreground/5 hover:bg-foreground/10 text-foreground/60 border-border/60'
|
| 247 |
}`}
|
| 248 |
-
title="Drop or paste sample copy for the AI to emulate"
|
| 249 |
>
|
| 250 |
<span>{showSampleInput ? 'Hide Sample' : '+ Drop Sample'}</span>
|
| 251 |
{sampleText.trim() && <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />}
|
|
@@ -257,23 +262,26 @@ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }:
|
|
| 257 |
<div className="space-y-1.5 p-3 rounded-xl bg-amber-500/[0.04] border border-amber-500/25 animate-in fade-in slide-in-from-top-1 duration-200">
|
| 258 |
<div className="flex items-center justify-between">
|
| 259 |
<span className="text-[10px] font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1">
|
| 260 |
-
|
| 261 |
</span>
|
| 262 |
{sampleText && (
|
| 263 |
<button
|
| 264 |
type="button"
|
| 265 |
onClick={() => setSampleText('')}
|
| 266 |
-
className="text-[10px] text-foreground/40 hover:text-foreground/80 font-medium"
|
| 267 |
>
|
| 268 |
Clear Sample
|
| 269 |
</button>
|
| 270 |
)}
|
| 271 |
</div>
|
|
|
|
|
|
|
|
|
|
| 272 |
<textarea
|
| 273 |
-
rows={
|
| 274 |
value={sampleText}
|
| 275 |
onChange={(e) => setSampleText(e.target.value)}
|
| 276 |
-
placeholder="Paste reference message
|
| 277 |
className="w-full bg-input border border-border/70 text-foreground rounded-lg p-2.5 text-xs focus:ring-1 focus:ring-amber-500/30 outline-none transition-all placeholder:text-foreground/35 font-medium leading-relaxed resize-none"
|
| 278 |
/>
|
| 279 |
</div>
|
|
@@ -385,7 +393,7 @@ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }:
|
|
| 385 |
|
| 386 |
{/* Preview mode for Spintax */}
|
| 387 |
{previewText ? (
|
| 388 |
-
<div className="p-3 rounded-xl bg-purple-500/5 border border-purple-500/20 text-xs text-foreground/90 font-mono leading-relaxed whitespace-pre-wrap">
|
| 389 |
<div className="text-[9px] font-bold text-purple-400 uppercase tracking-wider mb-1 flex items-center gap-1">
|
| 390 |
<Shuffle size={9} /> Resolved Output Sample:
|
| 391 |
</div>
|
|
@@ -394,7 +402,7 @@ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }:
|
|
| 394 |
) : null}
|
| 395 |
|
| 396 |
{/* Raw Text View */}
|
| 397 |
-
<div className="p-3 rounded-xl bg-card border border-border/
|
| 398 |
{vText}
|
| 399 |
</div>
|
| 400 |
</div>
|
|
|
|
| 118 |
setVariations(data.variations);
|
| 119 |
setSamplePreviews({});
|
| 120 |
} else {
|
| 121 |
+
const detailMsg = typeof data.detail === 'string'
|
| 122 |
+
? data.detail
|
| 123 |
+
: Array.isArray(data.detail)
|
| 124 |
+
? data.detail.map((d: any) => d.msg || JSON.stringify(d)).join(', ')
|
| 125 |
+
: 'Failed to generate message variations. Please try another prompt.';
|
| 126 |
+
setError(detailMsg);
|
| 127 |
}
|
| 128 |
} catch (e: any) {
|
| 129 |
setError(e.message || 'Error communicating with AI assistant.');
|
|
|
|
| 250 |
? 'bg-amber-500/15 text-amber-300 border-amber-500/35 shadow-xs'
|
| 251 |
: 'bg-foreground/5 hover:bg-foreground/10 text-foreground/60 border-border/60'
|
| 252 |
}`}
|
| 253 |
+
title="Drop or paste sample copy for the AI to emulate style, layout, and length"
|
| 254 |
>
|
| 255 |
<span>{showSampleInput ? 'Hide Sample' : '+ Drop Sample'}</span>
|
| 256 |
{sampleText.trim() && <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />}
|
|
|
|
| 262 |
<div className="space-y-1.5 p-3 rounded-xl bg-amber-500/[0.04] border border-amber-500/25 animate-in fade-in slide-in-from-top-1 duration-200">
|
| 263 |
<div className="flex items-center justify-between">
|
| 264 |
<span className="text-[10px] font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1">
|
| 265 |
+
Style & Structure Benchmark (Optional)
|
| 266 |
</span>
|
| 267 |
{sampleText && (
|
| 268 |
<button
|
| 269 |
type="button"
|
| 270 |
onClick={() => setSampleText('')}
|
| 271 |
+
className="text-[10px] text-foreground/40 hover:text-foreground/80 font-medium cursor-pointer"
|
| 272 |
>
|
| 273 |
Clear Sample
|
| 274 |
</button>
|
| 275 |
)}
|
| 276 |
</div>
|
| 277 |
+
<p className="text-[10px] text-foreground/50 leading-tight">
|
| 278 |
+
The AI uses this purely as a layout, tone, bullet density, and length reference. It writes 100% original copy for your offer and will <strong>not copy</strong> the sample wording.
|
| 279 |
+
</p>
|
| 280 |
<textarea
|
| 281 |
+
rows={3}
|
| 282 |
value={sampleText}
|
| 283 |
onChange={(e) => setSampleText(e.target.value)}
|
| 284 |
+
placeholder="Paste reference message or competitor copy here to benchmark tone, formatting, and length..."
|
| 285 |
className="w-full bg-input border border-border/70 text-foreground rounded-lg p-2.5 text-xs focus:ring-1 focus:ring-amber-500/30 outline-none transition-all placeholder:text-foreground/35 font-medium leading-relaxed resize-none"
|
| 286 |
/>
|
| 287 |
</div>
|
|
|
|
| 393 |
|
| 394 |
{/* Preview mode for Spintax */}
|
| 395 |
{previewText ? (
|
| 396 |
+
<div className="p-3.5 rounded-xl bg-purple-500/5 border border-purple-500/20 text-xs text-foreground/90 font-mono leading-relaxed whitespace-pre-wrap break-words">
|
| 397 |
<div className="text-[9px] font-bold text-purple-400 uppercase tracking-wider mb-1 flex items-center gap-1">
|
| 398 |
<Shuffle size={9} /> Resolved Output Sample:
|
| 399 |
</div>
|
|
|
|
| 402 |
) : null}
|
| 403 |
|
| 404 |
{/* Raw Text View */}
|
| 405 |
+
<div className="p-3.5 rounded-xl bg-card border border-border/70 text-[12px] text-foreground/90 font-sans leading-relaxed whitespace-pre-wrap break-words max-h-60 overflow-y-auto custom-scrollbar select-text">
|
| 406 |
{vText}
|
| 407 |
</div>
|
| 408 |
</div>
|