Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
-
B2B Content Strategy Planner
|
| 3 |
Deployed for Hugging Face Spaces.
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
@@ -9,13 +9,11 @@ import requests
|
|
| 9 |
import re
|
| 10 |
import time
|
| 11 |
import pandas as pd
|
| 12 |
-
import json
|
| 13 |
from urllib.parse import urlparse, urljoin
|
| 14 |
from collections import defaultdict
|
| 15 |
from bs4 import BeautifulSoup
|
| 16 |
import plotly.graph_objects as go
|
| 17 |
import plotly.express as px
|
| 18 |
-
import os
|
| 19 |
|
| 20 |
# ============================================================================
|
| 21 |
# 1. CONFIGURATION & TOPIC PACKS (FULL)
|
|
@@ -39,458 +37,450 @@ TOPIC_PACKS = {
|
|
| 39 |
}
|
| 40 |
|
| 41 |
CATEGORY_HINTS = {
|
| 42 |
-
"Blog": ["blog", "article", "news", "insights"],
|
| 43 |
-
"Whitepaper": ["whitepaper", "white-paper", "ebook", "guide", "report", "research"],
|
| 44 |
-
"Case Study": ["case-study", "customer", "success-story", "client"],
|
| 45 |
-
"
|
| 46 |
-
"
|
|
|
|
| 47 |
}
|
| 48 |
|
| 49 |
# ============================================================================
|
| 50 |
-
# 2.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
# ============================================================================
|
| 52 |
|
| 53 |
def normalize_str(s: str) -> str:
|
| 54 |
-
"""Normalize string: lowercase, replace non-alphanumeric with hyphens"""
|
| 55 |
if not s: return ""
|
| 56 |
return re.sub(r'^-|-$', '', re.sub(r'-+', '-', re.sub(r'[^a-z0-9]+', '-', s.lower())))
|
| 57 |
|
| 58 |
def path_norm(url: str) -> str:
|
| 59 |
-
"""Normalize URL path"""
|
| 60 |
try:
|
| 61 |
u = urlparse(url)
|
| 62 |
return normalize_str(u.path)
|
| 63 |
except:
|
| 64 |
return normalize_str(url)
|
| 65 |
|
| 66 |
-
def
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
def expand_topic_variants(topic_slug: str) -> set:
|
| 70 |
-
"""
|
| 71 |
-
variants =
|
| 72 |
-
variants.add(topic_slug)
|
| 73 |
-
|
| 74 |
-
# Hyphenated vs no hyphens vs spaces
|
| 75 |
-
variants.add(topic_slug.replace('-', ''))
|
| 76 |
-
variants.add(topic_slug.replace('-', ' '))
|
| 77 |
-
|
| 78 |
-
# Individual tokens
|
| 79 |
-
for token in topic_slug.split('-'):
|
| 80 |
-
if len(token) > 2: variants.add(token)
|
| 81 |
|
| 82 |
-
#
|
| 83 |
for pack_name, keywords in TOPIC_PACKS.items():
|
| 84 |
-
|
| 85 |
-
if any(normalize_str(kw) == topic_slug for kw in keywords):
|
| 86 |
for kw in keywords:
|
| 87 |
-
|
| 88 |
-
variants.
|
| 89 |
-
variants.add(norm_kw.replace('-', ''))
|
| 90 |
-
variants.add(norm_kw.replace('-', ' '))
|
| 91 |
break
|
| 92 |
-
|
| 93 |
return variants
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
def match_topic_urls(links
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
|
| 110 |
# 2. Negative Keywords
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
filtered = [u for u in filtered if not any(
|
| 114 |
-
|
| 115 |
-
|
|
|
|
| 116 |
search_terms = {topic_slug}
|
| 117 |
|
| 118 |
-
# Add Synonyms
|
| 119 |
if synonyms:
|
| 120 |
-
for
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
results.append(url)
|
| 131 |
-
return list(set(results))
|
| 132 |
-
|
| 133 |
-
# Fuzzy/Semantic (Expansion)
|
| 134 |
-
expanded_terms = set()
|
| 135 |
-
for term in search_terms:
|
| 136 |
-
expanded_terms.update(expand_topic_variants(term))
|
| 137 |
-
|
| 138 |
-
scored_results = []
|
| 139 |
for url in filtered:
|
| 140 |
norm = path_norm(url)
|
| 141 |
score = 0
|
| 142 |
-
for term in
|
| 143 |
if term in norm:
|
| 144 |
score += 10
|
| 145 |
-
if term in norm.split('-'): score += 5 #
|
| 146 |
|
| 147 |
-
if score > 0:
|
| 148 |
-
scored_results.append((url, score))
|
| 149 |
-
|
| 150 |
-
scored_results.sort(key=lambda x: x[1], reverse=True)
|
| 151 |
-
return [x[0] for x in scored_results]
|
| 152 |
-
|
| 153 |
-
def categorize_links_strict(urls: list) -> dict:
|
| 154 |
-
"""Categorize URLs based on specific HINTS + Folder structure"""
|
| 155 |
-
categories = defaultdict(list)
|
| 156 |
-
|
| 157 |
-
for url in urls:
|
| 158 |
-
norm_path = path_norm(url)
|
| 159 |
-
assigned = False
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
if any(h in norm_path for h in hints):
|
| 164 |
-
topic = norm_path.split('-')[-1] # Simple topic extraction
|
| 165 |
-
if len(norm_path.split('-')) > 1:
|
| 166 |
-
topic = " ".join(norm_path.split('-')[1:])
|
| 167 |
-
categories[cat_name].append(topic)
|
| 168 |
-
assigned = True
|
| 169 |
-
break
|
| 170 |
-
|
| 171 |
-
# Fallback to folder structure
|
| 172 |
-
if not assigned:
|
| 173 |
-
parts = list(filter(None, urlparse(url).path.split('/')))
|
| 174 |
-
if len(parts) > 1:
|
| 175 |
-
cat = parts[0].title()
|
| 176 |
-
topic = parts[-1]
|
| 177 |
-
categories[cat].append(topic)
|
| 178 |
-
|
| 179 |
-
return dict(categories)
|
| 180 |
-
|
| 181 |
-
# ============================================================================
|
| 182 |
-
# 4. FUNNEL ANALYSIS & AI SCORING
|
| 183 |
-
# ============================================================================
|
| 184 |
-
|
| 185 |
-
def classify_stage(url: str) -> str:
|
| 186 |
-
norm = path_norm(url).lower()
|
| 187 |
-
if any(x in norm for x in ['case-study', 'customer', 'success', 'pricing', 'demo']): return 'BOFU'
|
| 188 |
-
if any(x in norm for x in ['whitepaper', 'guide', 'ebook', 'webinar', 'report']): return 'MOFU'
|
| 189 |
-
return 'TOFU'
|
| 190 |
-
|
| 191 |
-
def analyze_funnel_gaps(urls: list, topic_text: str):
|
| 192 |
-
stages = [classify_stage(u) for u in urls]
|
| 193 |
-
total = len(stages) or 1
|
| 194 |
-
tofu = stages.count('TOFU')
|
| 195 |
-
mofu = stages.count('MOFU')
|
| 196 |
-
bofu = stages.count('BOFU')
|
| 197 |
-
|
| 198 |
-
tofu_pct = round((tofu/total)*100)
|
| 199 |
-
mofu_pct = round((mofu/total)*100)
|
| 200 |
-
bofu_pct = round((bofu/total)*100)
|
| 201 |
-
|
| 202 |
-
recs = []
|
| 203 |
-
if tofu_pct < 25: recs.append(f"β οΈ Increase TOFU (Awareness) content (currently {tofu_pct}%). Create more blog posts/guides.")
|
| 204 |
-
if mofu_pct < 25: recs.append(f"β οΈ Strengthen MOFU (Consideration) content (currently {mofu_pct}%). Create whitepapers/webinars.")
|
| 205 |
-
if bofu_pct < 25: recs.append(f"β οΈ Build BOFU (Decision) content (currently {bofu_pct}%). Add case studies/ROI tools.")
|
| 206 |
-
if not recs: recs.append("β
Balanced funnel distribution. Maintain this ratio.")
|
| 207 |
-
|
| 208 |
-
return {
|
| 209 |
-
'topic': topic_text, 'total': len(urls),
|
| 210 |
-
'tofu_pct': tofu_pct, 'mofu_pct': mofu_pct, 'bofu_pct': bofu_pct,
|
| 211 |
-
'recommendations': recs
|
| 212 |
-
}
|
| 213 |
|
| 214 |
def score_ai_output(output_text: str, topic: str, stage: str) -> dict:
|
| 215 |
-
"""
|
| 216 |
scores = {'total': 0}
|
| 217 |
lower_out = output_text.lower()
|
| 218 |
|
| 219 |
-
# 1.
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
scores['Topic Relevance'] = min(20, matches * 2)
|
| 223 |
|
| 224 |
-
# 2. Stage Alignment
|
| 225 |
-
stage_kws = {
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
'BOFU': ['case study', 'roi', 'demo', 'pricing', 'proof']
|
| 229 |
-
}
|
| 230 |
-
stage_matches = sum(1 for k in stage_kws.get(stage, []) if k in lower_out)
|
| 231 |
-
scores['Stage Alignment'] = min(20, stage_matches * 5)
|
| 232 |
|
| 233 |
-
# 3. Structure
|
| 234 |
struct_score = 0
|
| 235 |
-
if '##' in output_text
|
| 236 |
-
if '
|
| 237 |
-
if '
|
| 238 |
scores['Structure'] = struct_score
|
| 239 |
|
| 240 |
-
# 4. Specificity (
|
| 241 |
-
spec_matches = len(re.findall(r'\d+%|\$\d+
|
| 242 |
-
scores['Specificity'] = min(10, spec_matches *
|
| 243 |
|
| 244 |
-
# 5. Creativity
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
scores['Creativity'] = min(10, creat_matches * 2)
|
| 248 |
|
| 249 |
-
# 6. Actionability
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
scores['Actionability'] = min(10, act_matches * 2)
|
| 253 |
|
| 254 |
scores['total'] = sum(v for k,v in scores.items() if k != 'total')
|
| 255 |
return scores
|
| 256 |
|
| 257 |
# ============================================================================
|
| 258 |
-
#
|
| 259 |
# ============================================================================
|
| 260 |
|
| 261 |
-
def
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
queue, visited, found_urls = [start_url], {start_url}, []
|
| 265 |
-
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
|
| 266 |
-
|
| 267 |
-
log = f"π·οΈ **Crawler Activated** on {domain}...\n"
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
queue.append(full_url)
|
| 285 |
-
except: continue
|
| 286 |
-
return list(set(found_urls)), log + f"β
Scanned {len(found_urls)} pages."
|
| 287 |
-
|
| 288 |
-
def fetch_sitemap_links(user_input: str):
|
| 289 |
-
user_input = user_input.strip()
|
| 290 |
-
base_url = user_input if user_input.startswith('http') else f'https://{user_input}'
|
| 291 |
-
candidates = [base_url, f"{base_url.rstrip('/')}/sitemap.xml", f"{base_url.rstrip('/')}/sitemap_index.xml", f"{base_url.rstrip('/')}/wp-sitemap.xml"]
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
# ============================================================================
|
| 304 |
-
#
|
| 305 |
# ============================================================================
|
| 306 |
|
| 307 |
-
def
|
| 308 |
-
urls, msg = fetch_sitemap_links(url)
|
| 309 |
-
cats =
|
| 310 |
return urls, cats, msg, list(cats.keys())
|
| 311 |
|
| 312 |
-
def
|
| 313 |
-
if not urls: return "
|
|
|
|
|
|
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
-
summary = f"### Analysis: {topic}\n"
|
| 319 |
-
summary += f"**
|
| 320 |
-
summary += "\n".join(funnel_data['recommendations'])
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
# Mock generation if no key (to prevent crash), normally would use OpenAI/LangChain
|
| 326 |
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
-
## 1. The
|
| 330 |
**Format:** Blog Post
|
| 331 |
-
**Why:**
|
| 332 |
-
**
|
| 333 |
|
| 334 |
-
## 2. {topic}
|
| 335 |
**Format:** Whitepaper
|
| 336 |
-
**Why:**
|
| 337 |
-
**Details:** Includes step-by-step framework.
|
| 338 |
|
| 339 |
-
## 3. Case Study:
|
| 340 |
-
**Format:**
|
| 341 |
-
**Why:**
|
| 342 |
"""
|
| 343 |
-
|
| 344 |
-
#
|
| 345 |
-
|
| 346 |
-
score_display = f"### π AI Quality Score: {scores['total']}/100\n"
|
| 347 |
-
for k, v in scores.items():
|
| 348 |
-
if k != 'total': score_display += f"- **{k}:** {v}\n"
|
| 349 |
-
|
| 350 |
-
return mock_response, score_display
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
urls, msg = fetch_sitemap_links(comp_url)
|
| 356 |
-
domain = urlparse(comp_url if comp_url.startswith('http') else f'https://{comp_url}').netloc
|
| 357 |
-
|
| 358 |
-
new_data = {
|
| 359 |
-
'domain': domain,
|
| 360 |
-
'urls': urls,
|
| 361 |
-
'count': len(urls),
|
| 362 |
-
'stats': {'TOFU': 0, 'MOFU': 0, 'BOFU': 0} # Placeholder
|
| 363 |
-
}
|
| 364 |
|
| 365 |
-
# Calc actual stats
|
| 366 |
stages = [classify_stage(u) for u in urls]
|
| 367 |
total = len(stages) or 1
|
| 368 |
-
|
| 369 |
'TOFU': (stages.count('TOFU')/total)*100,
|
| 370 |
'MOFU': (stages.count('MOFU')/total)*100,
|
| 371 |
-
'BOFU': (stages.count('BOFU')/total)*100
|
|
|
|
| 372 |
}
|
| 373 |
|
|
|
|
| 374 |
current_list.append(new_data)
|
| 375 |
-
display = "\n".join([f"β
{c['domain']} ({c['count']} pages)" for c in current_list])
|
| 376 |
-
return current_list, display, ""
|
| 377 |
-
|
| 378 |
-
def ui_analyze_gaps(user_urls, competitors, filter_topic):
|
| 379 |
-
# Logic from analyze_gaps in previous turn
|
| 380 |
-
if not user_urls or not competitors: return "Need data.", None, None
|
| 381 |
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
for u in urls:
|
| 385 |
-
slug = path_norm(u)
|
| 386 |
-
t.update([w for w in slug.split('-') if len(w)>3])
|
| 387 |
-
return t
|
| 388 |
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
diff = c_tokens - my_tokens
|
| 395 |
-
for t in diff:
|
| 396 |
-
if not filter_topic or filter_topic.lower() in t:
|
| 397 |
-
gaps.append(f"Missing '{t}' (seen on {c['domain']})")
|
| 398 |
-
|
| 399 |
-
unique_gaps = sorted(list(set(gaps)))[:30]
|
| 400 |
-
gap_text = f"### π Top {len(unique_gaps)} Gaps\n" + "\n".join(f"- {g}" for g in unique_gaps)
|
| 401 |
-
|
| 402 |
-
# Radar Chart
|
| 403 |
-
cats = ['TOFU', 'MOFU', 'BOFU']
|
| 404 |
-
fig = go.Figure()
|
| 405 |
-
|
| 406 |
-
# User
|
| 407 |
-
user_stages = [classify_stage(u) for u in user_urls]
|
| 408 |
-
utotal = len(user_stages) or 1
|
| 409 |
-
ustats = [(user_stages.count(s)/utotal)*100 for s in cats]
|
| 410 |
-
|
| 411 |
-
fig.add_trace(go.Scatterpolar(r=ustats, theta=cats, fill='toself', name='You', line_color='#3b82f6'))
|
| 412 |
-
|
| 413 |
-
for i, c in enumerate(competitors):
|
| 414 |
-
s = c['stats']
|
| 415 |
-
fig.add_trace(go.Scatterpolar(r=[s['TOFU'], s['MOFU'], s['BOFU']], theta=cats, fill='toself', name=c['domain'], opacity=0.5))
|
| 416 |
-
|
| 417 |
-
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 100])), title="Funnel Strategy Radar")
|
| 418 |
-
|
| 419 |
-
return gap_text, fig
|
| 420 |
|
| 421 |
# ============================================================================
|
| 422 |
-
#
|
| 423 |
# ============================================================================
|
| 424 |
|
| 425 |
with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
| 426 |
state_urls = gr.State([])
|
| 427 |
state_cats = gr.State({})
|
| 428 |
-
|
| 429 |
|
| 430 |
-
gr.Markdown("# π B2B Content Strategy
|
| 431 |
|
| 432 |
with gr.Tabs():
|
| 433 |
# TAB 1: PLANNER
|
| 434 |
with gr.Tab("π Planner"):
|
| 435 |
with gr.Row():
|
| 436 |
-
url_input = gr.Textbox(label="
|
|
|
|
| 437 |
fetch_btn = gr.Button("Fetch Data", variant="primary")
|
| 438 |
|
| 439 |
-
fetch_log = gr.Textbox(label="Status",
|
| 440 |
|
| 441 |
with gr.Row():
|
| 442 |
cat_dd = gr.Dropdown(label="Category", choices=[])
|
| 443 |
-
|
| 444 |
|
| 445 |
with gr.Accordion("Advanced Matching", open=False):
|
| 446 |
match_mode = gr.Radio(["fuzzy", "exact"], label="Mode", value="fuzzy")
|
| 447 |
synonyms = gr.Textbox(label="Synonyms (comma-separated)")
|
| 448 |
neg_kw = gr.Textbox(label="Negative Keywords")
|
| 449 |
|
| 450 |
-
analyze_btn = gr.Button("Analyze Content", variant="
|
| 451 |
|
| 452 |
with gr.Row():
|
| 453 |
-
|
| 454 |
-
|
| 455 |
|
| 456 |
-
gr.Markdown("### β¨ AI
|
| 457 |
with gr.Row():
|
| 458 |
-
|
| 459 |
-
api_key = gr.Textbox(label="OpenAI API Key (Optional for mock)", type="password")
|
| 460 |
gen_btn = gr.Button("Generate Ideas")
|
| 461 |
|
| 462 |
with gr.Row():
|
| 463 |
-
|
| 464 |
-
|
| 465 |
|
| 466 |
# TAB 2: COMPETITORS
|
| 467 |
with gr.Tab("π Competitors"):
|
| 468 |
with gr.Row():
|
| 469 |
-
|
| 470 |
-
|
| 471 |
|
| 472 |
comp_display = gr.Markdown("No competitors added.")
|
| 473 |
|
| 474 |
with gr.Row():
|
| 475 |
-
gap_filter = gr.Textbox(label="
|
| 476 |
-
|
| 477 |
|
| 478 |
with gr.Row():
|
|
|
|
| 479 |
gap_res = gr.Markdown()
|
| 480 |
-
radar_plot = gr.Plot()
|
| 481 |
|
| 482 |
-
#
|
| 483 |
-
fetch_btn.click(
|
| 484 |
|
| 485 |
-
analyze_btn.click(
|
| 486 |
-
[state_urls, cat_dd,
|
| 487 |
-
[
|
| 488 |
|
| 489 |
-
gen_btn.click(ui_generate_ideas, [
|
| 490 |
|
| 491 |
-
|
| 492 |
|
| 493 |
-
|
| 494 |
|
| 495 |
if __name__ == "__main__":
|
| 496 |
demo.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
+
π B2B Content Strategy Planner (Final Master Edition)
|
| 3 |
Deployed for Hugging Face Spaces.
|
| 4 |
+
Features: Unlimited Deep Crawling, Full Topic Packs, AI Scoring, Radar Charts, & Competitor Intelligence.
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
|
|
| 9 |
import re
|
| 10 |
import time
|
| 11 |
import pandas as pd
|
|
|
|
| 12 |
from urllib.parse import urlparse, urljoin
|
| 13 |
from collections import defaultdict
|
| 14 |
from bs4 import BeautifulSoup
|
| 15 |
import plotly.graph_objects as go
|
| 16 |
import plotly.express as px
|
|
|
|
| 17 |
|
| 18 |
# ============================================================================
|
| 19 |
# 1. CONFIGURATION & TOPIC PACKS (FULL)
|
|
|
|
| 37 |
}
|
| 38 |
|
| 39 |
CATEGORY_HINTS = {
|
| 40 |
+
"Blog": ["blog", "article", "news", "insights", "journal"],
|
| 41 |
+
"Whitepaper": ["whitepaper", "white-paper", "ebook", "guide", "report", "research", "resource"],
|
| 42 |
+
"Case Study": ["case-study", "customer", "success-story", "client", "portfolio", "project"],
|
| 43 |
+
"Service": ["service", "solution", "capability", "offering", "consulting"],
|
| 44 |
+
"Product": ["product", "platform", "tool", "software", "feature"],
|
| 45 |
+
"Webinar": ["webinar", "event", "masterclass", "video"]
|
| 46 |
}
|
| 47 |
|
| 48 |
# ============================================================================
|
| 49 |
+
# 2. DEEP CRAWLER (UNLIMITED MODE)
|
| 50 |
+
# ============================================================================
|
| 51 |
+
|
| 52 |
+
def normalize_domain(url):
|
| 53 |
+
"""Strip www. to ensure domain matching works across subdomains"""
|
| 54 |
+
netloc = urlparse(url).netloc
|
| 55 |
+
return netloc.replace('www.', '')
|
| 56 |
+
|
| 57 |
+
def crawl_website_unlimited(start_url: str):
|
| 58 |
+
"""
|
| 59 |
+
Robust Crawler: Handles redirects, subdomains, and deep linking.
|
| 60 |
+
Limit set to 5000 to prevent infinite loops, effectively 'unlimited' for most sites.
|
| 61 |
+
"""
|
| 62 |
+
MAX_PAGES = 5000
|
| 63 |
+
|
| 64 |
+
if not start_url.startswith(('http://', 'https://')):
|
| 65 |
+
start_url = f'https://{start_url}'
|
| 66 |
+
|
| 67 |
+
base_domain = normalize_domain(start_url)
|
| 68 |
+
queue = [start_url]
|
| 69 |
+
visited = set()
|
| 70 |
+
found_urls = []
|
| 71 |
+
|
| 72 |
+
# Headers to bypass basic bot protection
|
| 73 |
+
headers = {
|
| 74 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 75 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
log = [f"π·οΈ **Deep Crawler Started** on {start_url}"]
|
| 79 |
+
|
| 80 |
+
while queue and len(found_urls) < MAX_PAGES:
|
| 81 |
+
current_url = queue.pop(0)
|
| 82 |
+
|
| 83 |
+
if current_url in visited:
|
| 84 |
+
continue
|
| 85 |
+
visited.add(current_url)
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
# Short delay to prevent server blocking
|
| 89 |
+
time.sleep(0.05)
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
resp = requests.get(current_url, headers=headers, timeout=5)
|
| 93 |
+
except:
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
# Update domain if redirected (e.g., http -> https)
|
| 97 |
+
final_url = resp.url
|
| 98 |
+
visited.add(final_url)
|
| 99 |
+
|
| 100 |
+
# Skip non-HTML
|
| 101 |
+
if 'text/html' not in resp.headers.get('Content-Type', '').lower():
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
if resp.status_code == 200:
|
| 105 |
+
found_urls.append(final_url)
|
| 106 |
+
|
| 107 |
+
# Parse HTML (lxml is faster)
|
| 108 |
+
soup = BeautifulSoup(resp.text, 'lxml')
|
| 109 |
+
|
| 110 |
+
for link in soup.find_all('a', href=True):
|
| 111 |
+
href = link['href'].strip()
|
| 112 |
+
full_url = urljoin(final_url, href)
|
| 113 |
+
clean_url = full_url.split('#')[0].split('?')[0].rstrip('/')
|
| 114 |
+
|
| 115 |
+
# Logic: Internal Domain ONLY, No Files, No System Pages
|
| 116 |
+
link_domain = normalize_domain(clean_url)
|
| 117 |
+
is_internal = (link_domain == base_domain)
|
| 118 |
+
is_file = any(clean_url.endswith(ext) for ext in ['.pdf', '.jpg', '.png', '.css', '.js', '.zip'])
|
| 119 |
+
is_system = any(x in clean_url.lower() for x in ['/login', '/cart', 'javascript:', 'mailto:', 'tel:'])
|
| 120 |
+
|
| 121 |
+
if is_internal and not is_file and not is_system:
|
| 122 |
+
if clean_url not in visited and clean_url not in queue:
|
| 123 |
+
queue.append(clean_url)
|
| 124 |
+
|
| 125 |
+
except Exception:
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
return list(set(found_urls)), f"β
Crawl Complete. Scanned {len(visited)} links. Found {len(found_urls)} valid pages."
|
| 129 |
+
|
| 130 |
+
def fetch_sitemap_links(user_input: str, force_crawl: bool = False):
|
| 131 |
+
"""Smart Fetcher: Checks XML first, then Deep Crawls"""
|
| 132 |
+
user_input = user_input.strip()
|
| 133 |
+
base_url = user_input if user_input.startswith('http') else f'https://{user_input}'
|
| 134 |
+
|
| 135 |
+
if force_crawl:
|
| 136 |
+
return crawl_website_unlimited(base_url)
|
| 137 |
+
|
| 138 |
+
# 1. Try XML Sitemaps
|
| 139 |
+
candidates = [
|
| 140 |
+
f"{base_url.rstrip('/')}/sitemap.xml",
|
| 141 |
+
f"{base_url.rstrip('/')}/sitemap_index.xml",
|
| 142 |
+
f"{base_url.rstrip('/')}/wp-sitemap.xml"
|
| 143 |
+
]
|
| 144 |
+
if user_input.endswith('.xml'): candidates = [user_input]
|
| 145 |
+
|
| 146 |
+
for xml_url in candidates:
|
| 147 |
+
try:
|
| 148 |
+
r = requests.get(xml_url, timeout=10, headers={'User-Agent': 'Googlebot/2.1'})
|
| 149 |
+
if r.status_code == 200:
|
| 150 |
+
# Regex is faster/more robust for malformed XML than XML parsers
|
| 151 |
+
urls = re.findall(r'<loc>(.*?)</loc>', r.text)
|
| 152 |
+
if len(urls) > 10:
|
| 153 |
+
return list(set(urls)), f"β
Found {len(urls)} URLs via XML Sitemap."
|
| 154 |
+
except: continue
|
| 155 |
+
|
| 156 |
+
# 2. Fallback to Deep Crawler
|
| 157 |
+
return crawl_website_unlimited(base_url)
|
| 158 |
+
|
| 159 |
+
# ============================================================================
|
| 160 |
+
# 3. ANALYSIS LOGIC (Normalization, Classification, Scoring)
|
| 161 |
# ============================================================================
|
| 162 |
|
| 163 |
def normalize_str(s: str) -> str:
|
|
|
|
| 164 |
if not s: return ""
|
| 165 |
return re.sub(r'^-|-$', '', re.sub(r'-+', '-', re.sub(r'[^a-z0-9]+', '-', s.lower())))
|
| 166 |
|
| 167 |
def path_norm(url: str) -> str:
|
|
|
|
| 168 |
try:
|
| 169 |
u = urlparse(url)
|
| 170 |
return normalize_str(u.path)
|
| 171 |
except:
|
| 172 |
return normalize_str(url)
|
| 173 |
|
| 174 |
+
def classify_stage(url: str) -> str:
|
| 175 |
+
norm = path_norm(url).lower()
|
| 176 |
+
if any(x in norm for x in ['case-study', 'customer', 'success', 'pricing', 'demo']): return 'BOFU'
|
| 177 |
+
if any(x in norm for x in ['whitepaper', 'guide', 'ebook', 'webinar', 'report']): return 'MOFU'
|
| 178 |
+
return 'TOFU' # Default
|
| 179 |
|
| 180 |
def expand_topic_variants(topic_slug: str) -> set:
|
| 181 |
+
"""Expands a topic into synonyms and variations based on Packs"""
|
| 182 |
+
variants = {topic_slug, topic_slug.replace('-', ''), topic_slug.replace('-', ' ')}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
+
# Add pack keywords if topic matches a pack
|
| 185 |
for pack_name, keywords in TOPIC_PACKS.items():
|
| 186 |
+
if topic_slug in [normalize_str(k) for k in keywords] or topic_slug == pack_name:
|
|
|
|
| 187 |
for kw in keywords:
|
| 188 |
+
n_kw = normalize_str(kw)
|
| 189 |
+
variants.update({n_kw, n_kw.replace('-', ''), n_kw.replace('-', ' ')})
|
|
|
|
|
|
|
| 190 |
break
|
|
|
|
| 191 |
return variants
|
| 192 |
|
| 193 |
+
def categorize_links(urls):
|
| 194 |
+
cats = defaultdict(list)
|
| 195 |
+
for url in urls:
|
| 196 |
+
norm = path_norm(url)
|
| 197 |
+
assigned = False
|
| 198 |
+
# 1. Check Hints
|
| 199 |
+
for cat_name, hints in CATEGORY_HINTS.items():
|
| 200 |
+
if any(h in norm for h in hints):
|
| 201 |
+
topic = norm.split('-')[-1]
|
| 202 |
+
if len(norm.split('-')) > 1: topic = " ".join(norm.split('-')[1:])
|
| 203 |
+
cats[cat_name].append(topic)
|
| 204 |
+
assigned = True
|
| 205 |
+
break
|
| 206 |
+
# 2. Check Folder Structure
|
| 207 |
+
if not assigned:
|
| 208 |
+
parts = list(filter(None, urlparse(url).path.split('/')))
|
| 209 |
+
if len(parts) > 0:
|
| 210 |
+
cats[parts[0].title()].append(parts[-1])
|
| 211 |
+
return dict(cats)
|
| 212 |
|
| 213 |
+
def match_topic_urls(links, topic, category, match_mode, synonyms="", neg_keywords=""):
|
| 214 |
+
# 1. Filter by Category
|
| 215 |
+
filtered = links
|
| 216 |
+
if category and category != "All":
|
| 217 |
+
filtered = [u for u in links if category.lower() in str(categorize_links([u]).keys()).lower()]
|
| 218 |
|
| 219 |
# 2. Negative Keywords
|
| 220 |
+
if neg_keywords:
|
| 221 |
+
negs = [n.strip().lower() for n in neg_keywords.split(',') if n.strip()]
|
| 222 |
+
filtered = [u for u in filtered if not any(n in path_norm(u) for n in negs)]
|
| 223 |
+
|
| 224 |
+
# 3. Topic Matching
|
| 225 |
+
topic_slug = normalize_str(topic)
|
| 226 |
search_terms = {topic_slug}
|
| 227 |
|
| 228 |
+
# Add User Synonyms
|
| 229 |
if synonyms:
|
| 230 |
+
search_terms.update([normalize_str(s) for s in synonyms.split(',')])
|
| 231 |
+
|
| 232 |
+
# Expansion for Fuzzy/Semantic
|
| 233 |
+
if match_mode != "exact":
|
| 234 |
+
expanded = set()
|
| 235 |
+
for t in search_terms:
|
| 236 |
+
expanded.update(expand_topic_variants(t))
|
| 237 |
+
search_terms = expanded
|
| 238 |
+
|
| 239 |
+
results = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
for url in filtered:
|
| 241 |
norm = path_norm(url)
|
| 242 |
score = 0
|
| 243 |
+
for term in search_terms:
|
| 244 |
if term in norm:
|
| 245 |
score += 10
|
| 246 |
+
if term in norm.split('-'): score += 5 # Exact token match bonus
|
| 247 |
|
| 248 |
+
if score > 0: results.append((url, score))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
results.sort(key=lambda x: x[1], reverse=True)
|
| 251 |
+
return [x[0] for x in results]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
def score_ai_output(output_text: str, topic: str, stage: str) -> dict:
|
| 254 |
+
"""7-Point Scoring System from Master Prompt"""
|
| 255 |
scores = {'total': 0}
|
| 256 |
lower_out = output_text.lower()
|
| 257 |
|
| 258 |
+
# 1. Relevance
|
| 259 |
+
matches = sum(lower_out.count(w) for w in normalize_str(topic).split('-'))
|
| 260 |
+
scores['Relevance'] = min(20, matches * 2)
|
|
|
|
| 261 |
|
| 262 |
+
# 2. Stage Alignment
|
| 263 |
+
stage_kws = {'TOFU': ['blog', 'guide', 'what is'], 'MOFU': ['whitepaper', 'strategy'], 'BOFU': ['case study', 'roi']}
|
| 264 |
+
stage_score = sum(5 for k in stage_kws.get(stage, []) if k in lower_out)
|
| 265 |
+
scores['Stage Alignment'] = min(20, stage_score)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
+
# 3. Structure
|
| 268 |
struct_score = 0
|
| 269 |
+
if '##' in output_text: struct_score += 5
|
| 270 |
+
if 'format:' in lower_out: struct_score += 5
|
| 271 |
+
if 'why:' in lower_out: struct_score += 5
|
| 272 |
scores['Structure'] = struct_score
|
| 273 |
|
| 274 |
+
# 4. Specificity (Numbers)
|
| 275 |
+
spec_matches = len(re.findall(r'\d+%|\$\d+', output_text))
|
| 276 |
+
scores['Specificity'] = min(10, spec_matches * 3)
|
| 277 |
|
| 278 |
+
# 5. Creativity
|
| 279 |
+
creat_matches = sum(1 for w in ['unique', 'fresh', 'story'] if w in lower_out)
|
| 280 |
+
scores['Creativity'] = min(10, creat_matches * 3)
|
|
|
|
| 281 |
|
| 282 |
+
# 6. Actionability
|
| 283 |
+
act_matches = sum(1 for w in ['step', 'template', 'execute'] if w in lower_out)
|
| 284 |
+
scores['Actionability'] = min(10, act_matches * 3)
|
|
|
|
| 285 |
|
| 286 |
scores['total'] = sum(v for k,v in scores.items() if k != 'total')
|
| 287 |
return scores
|
| 288 |
|
| 289 |
# ============================================================================
|
| 290 |
+
# 4. COMPETITOR & VISUALIZATION LOGIC
|
| 291 |
# ============================================================================
|
| 292 |
|
| 293 |
+
def generate_radar(user_urls, competitors):
|
| 294 |
+
categories = ['TOFU', 'MOFU', 'BOFU']
|
| 295 |
+
fig = go.Figure()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
+
# User
|
| 298 |
+
if user_urls:
|
| 299 |
+
stages = [classify_stage(u) for u in user_urls]
|
| 300 |
+
total = len(stages) or 1
|
| 301 |
+
stats = [(stages.count(s)/total)*100 for s in categories]
|
| 302 |
+
fig.add_trace(go.Scatterpolar(r=stats, theta=categories, fill='toself', name='You', line_color='#3b82f6'))
|
| 303 |
+
|
| 304 |
+
# Competitors
|
| 305 |
+
colors = ['#ef4444', '#10b981', '#f59e0b', '#8b5cf6']
|
| 306 |
+
for i, c in enumerate(competitors):
|
| 307 |
+
s = c['stats']
|
| 308 |
+
fig.add_trace(go.Scatterpolar(r=[s['TOFU'], s['MOFU'], s['BOFU']], theta=categories, fill='toself', name=c['domain'], line_color=colors[i%4], opacity=0.6))
|
| 309 |
+
|
| 310 |
+
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 100])), title="Funnel Strategy Radar", height=400)
|
| 311 |
+
return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
+
def analyze_gaps(user_urls, competitors, filter_topic):
|
| 314 |
+
if not user_urls: return "Need your data to compare."
|
| 315 |
+
|
| 316 |
+
def get_tokens(urls):
|
| 317 |
+
t = set()
|
| 318 |
+
for u in urls:
|
| 319 |
+
slug = path_norm(u)
|
| 320 |
+
t.update([w for w in slug.split('-') if len(w)>3 and not w.isdigit()])
|
| 321 |
+
return t
|
| 322 |
|
| 323 |
+
my_tokens = get_tokens(user_urls)
|
| 324 |
+
gaps = []
|
| 325 |
+
|
| 326 |
+
for c in competitors:
|
| 327 |
+
c_tokens = get_tokens(c['urls'])
|
| 328 |
+
diff = c_tokens - my_tokens
|
| 329 |
+
for t in diff:
|
| 330 |
+
if not filter_topic or filter_topic.lower() in t:
|
| 331 |
+
gaps.append(f"Missing '{t}' (seen on {c['domain']})")
|
| 332 |
+
|
| 333 |
+
unique_gaps = sorted(list(set(gaps)))
|
| 334 |
+
return f"### π Found {len(unique_gaps)} Gaps\n" + "\n".join(f"- {g}" for g in unique_gaps[:30])
|
| 335 |
|
| 336 |
# ============================================================================
|
| 337 |
+
# 5. UI EVENT HANDLERS
|
| 338 |
# ============================================================================
|
| 339 |
|
| 340 |
+
def ui_fetch_data(url, force):
|
| 341 |
+
urls, msg = fetch_sitemap_links(url, force)
|
| 342 |
+
cats = categorize_links(urls)
|
| 343 |
return urls, cats, msg, list(cats.keys())
|
| 344 |
|
| 345 |
+
def ui_analyze_planner(urls, category, topic, mode, syns, negs):
|
| 346 |
+
if not urls: return "Fetch data first.", None, None
|
| 347 |
+
|
| 348 |
+
matched = match_topic_urls(urls, topic, category, mode, syns, negs)
|
| 349 |
|
| 350 |
+
stages = [classify_stage(u) for u in matched]
|
| 351 |
+
total = len(stages) or 1
|
| 352 |
+
tofu = (stages.count('TOFU')/total)*100
|
| 353 |
+
mofu = (stages.count('MOFU')/total)*100
|
| 354 |
+
bofu = (stages.count('BOFU')/total)*100
|
| 355 |
|
| 356 |
+
summary = f"### Analysis: {topic}\n**Matched Pages:** {len(matched)}\n\n"
|
| 357 |
+
summary += f"**Funnel Health:**\n- TOFU: {tofu:.1f}%\n- MOFU: {mofu:.1f}%\n- BOFU: {bofu:.1f}%\n\n"
|
|
|
|
| 358 |
|
| 359 |
+
if tofu < 20: summary += "β οΈ **Recommendation:** Create more Awareness content (Blogs, Glossaries).\n"
|
| 360 |
+
if mofu < 20: summary += "β οΈ **Recommendation:** Create more Consideration content (Whitepapers, Comparisons).\n"
|
| 361 |
+
if bofu < 20: summary += "β οΈ **Recommendation:** Create more Decision content (Case Studies, ROI Tools).\n"
|
|
|
|
| 362 |
|
| 363 |
+
return summary, matched, None
|
| 364 |
+
|
| 365 |
+
def ui_generate_ideas(topic, stage):
|
| 366 |
+
# Mock AI Generation (Replace with API call in prod)
|
| 367 |
+
mock_res = f"""# π {stage} Content Ideas for {topic}
|
| 368 |
|
| 369 |
+
## 1. The Ultimate Guide to {topic}
|
| 370 |
**Format:** Blog Post
|
| 371 |
+
**Why:** Captures high-volume search traffic.
|
| 372 |
+
**Structure:** Definition, Benefits, Trends.
|
| 373 |
|
| 374 |
+
## 2. {topic} Maturity Model
|
| 375 |
**Format:** Whitepaper
|
| 376 |
+
**Why:** Helps leads evaluate their current state.
|
|
|
|
| 377 |
|
| 378 |
+
## 3. Case Study: Solving {topic} at Scale
|
| 379 |
+
**Format:** Success Story
|
| 380 |
+
**Why:** Social proof for decision makers.
|
| 381 |
"""
|
| 382 |
+
scores = score_ai_output(mock_res, topic, stage)
|
| 383 |
+
score_txt = f"### π AI Score: {scores['total']}/100\n" + "\n".join(f"- {k}: {v}" for k,v in scores.items() if k!='total')
|
| 384 |
+
return mock_res, score_txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
+
def ui_add_competitor(url, current_list):
|
| 387 |
+
urls, msg = fetch_sitemap_links(url, force_crawl=False) # Auto-detect
|
| 388 |
+
domain = urlparse(url if url.startswith('http') else f'https://{url}').netloc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
|
|
|
| 390 |
stages = [classify_stage(u) for u in urls]
|
| 391 |
total = len(stages) or 1
|
| 392 |
+
stats = {
|
| 393 |
'TOFU': (stages.count('TOFU')/total)*100,
|
| 394 |
'MOFU': (stages.count('MOFU')/total)*100,
|
| 395 |
+
'BOFU': (stages.count('BOFU')/total)*100,
|
| 396 |
+
'Count': len(urls)
|
| 397 |
}
|
| 398 |
|
| 399 |
+
new_data = {'domain': domain, 'urls': urls, 'stats': stats}
|
| 400 |
current_list.append(new_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
|
| 402 |
+
txt = "\n".join([f"β
{c['domain']}: {c['stats']['Count']} pages" for c in current_list])
|
| 403 |
+
return current_list, txt, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
+
def ui_analyze_comp_full(user_urls, competitors, gap_filter):
|
| 406 |
+
if not user_urls: return None, "Fetch your data first."
|
| 407 |
+
radar = generate_radar(user_urls, competitors)
|
| 408 |
+
gaps = analyze_gaps(user_urls, competitors, gap_filter)
|
| 409 |
+
return radar, gaps
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
|
| 411 |
# ============================================================================
|
| 412 |
+
# 6. GRADIO LAYOUT
|
| 413 |
# ============================================================================
|
| 414 |
|
| 415 |
with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
| 416 |
state_urls = gr.State([])
|
| 417 |
state_cats = gr.State({})
|
| 418 |
+
state_comps = gr.State([])
|
| 419 |
|
| 420 |
+
gr.Markdown("# π B2B Content Strategy & Deep Crawler")
|
| 421 |
|
| 422 |
with gr.Tabs():
|
| 423 |
# TAB 1: PLANNER
|
| 424 |
with gr.Tab("π Planner"):
|
| 425 |
with gr.Row():
|
| 426 |
+
url_input = gr.Textbox(label="Your Website URL")
|
| 427 |
+
force_crawl = gr.Checkbox(label="Force Deep Crawl (Unlimited)")
|
| 428 |
fetch_btn = gr.Button("Fetch Data", variant="primary")
|
| 429 |
|
| 430 |
+
fetch_log = gr.Textbox(label="Status", lines=1)
|
| 431 |
|
| 432 |
with gr.Row():
|
| 433 |
cat_dd = gr.Dropdown(label="Category", choices=[])
|
| 434 |
+
topic_in = gr.Textbox(label="Topic")
|
| 435 |
|
| 436 |
with gr.Accordion("Advanced Matching", open=False):
|
| 437 |
match_mode = gr.Radio(["fuzzy", "exact"], label="Mode", value="fuzzy")
|
| 438 |
synonyms = gr.Textbox(label="Synonyms (comma-separated)")
|
| 439 |
neg_kw = gr.Textbox(label="Negative Keywords")
|
| 440 |
|
| 441 |
+
analyze_btn = gr.Button("Analyze Content", variant="secondary")
|
| 442 |
|
| 443 |
with gr.Row():
|
| 444 |
+
plan_summary = gr.Markdown()
|
| 445 |
+
plan_urls = gr.Textbox(label="Matched URLs", lines=5)
|
| 446 |
|
| 447 |
+
gr.Markdown("### β¨ AI Generator")
|
| 448 |
with gr.Row():
|
| 449 |
+
gen_stage = gr.Dropdown(["TOFU", "MOFU", "BOFU"], label="Stage", value="TOFU")
|
|
|
|
| 450 |
gen_btn = gr.Button("Generate Ideas")
|
| 451 |
|
| 452 |
with gr.Row():
|
| 453 |
+
idea_out = gr.Markdown()
|
| 454 |
+
score_out = gr.Markdown()
|
| 455 |
|
| 456 |
# TAB 2: COMPETITORS
|
| 457 |
with gr.Tab("π Competitors"):
|
| 458 |
with gr.Row():
|
| 459 |
+
comp_url = gr.Textbox(label="Competitor URL")
|
| 460 |
+
add_comp = gr.Button("Add Competitor")
|
| 461 |
|
| 462 |
comp_display = gr.Markdown("No competitors added.")
|
| 463 |
|
| 464 |
with gr.Row():
|
| 465 |
+
gap_filter = gr.Textbox(label="Gap Topic Filter (Optional)")
|
| 466 |
+
comp_analyze = gr.Button("Analyze Strategy", variant="primary")
|
| 467 |
|
| 468 |
with gr.Row():
|
| 469 |
+
radar_plot = gr.Plot(label="Strategy Radar")
|
| 470 |
gap_res = gr.Markdown()
|
|
|
|
| 471 |
|
| 472 |
+
# EVENTS
|
| 473 |
+
fetch_btn.click(ui_fetch_data, [url_input, force_crawl], [state_urls, state_cats, fetch_log, cat_dd])
|
| 474 |
|
| 475 |
+
analyze_btn.click(ui_analyze_planner,
|
| 476 |
+
[state_urls, cat_dd, topic_in, match_mode, synonyms, neg_kw],
|
| 477 |
+
[plan_summary, plan_urls, gr.State()])
|
| 478 |
|
| 479 |
+
gen_btn.click(ui_generate_ideas, [topic_in, gen_stage], [idea_out, score_out])
|
| 480 |
|
| 481 |
+
add_comp.click(ui_add_competitor, [comp_url, state_comps], [state_comps, comp_display, comp_url])
|
| 482 |
|
| 483 |
+
comp_analyze.click(ui_analyze_comp_full, [state_urls, state_comps, gap_filter], [radar_plot, gap_res])
|
| 484 |
|
| 485 |
if __name__ == "__main__":
|
| 486 |
demo.launch()
|