Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
B2B Content Strategy Planner (
|
| 3 |
Deployed for Hugging Face Spaces.
|
| 4 |
"""
|
| 5 |
|
|
@@ -9,7 +9,7 @@ import re
|
|
| 9 |
import time
|
| 10 |
import pandas as pd
|
| 11 |
from urllib.parse import urlparse, urljoin
|
| 12 |
-
from collections import defaultdict
|
| 13 |
from bs4 import BeautifulSoup
|
| 14 |
import plotly.graph_objects as go
|
| 15 |
import plotly.express as px
|
|
@@ -72,10 +72,7 @@ def crawl_and_generate_sitemap(start_url: str, max_pages: int = 150) -> Tuple[Li
|
|
| 72 |
visited = set([start_url])
|
| 73 |
found_urls = []
|
| 74 |
|
| 75 |
-
headers = {
|
| 76 |
-
'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'
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
status_log = f"🕷️ **Crawler Mode Activated**\nScanning {start_url}...\n"
|
| 80 |
|
| 81 |
while queue and len(found_urls) < max_pages:
|
|
@@ -83,14 +80,10 @@ def crawl_and_generate_sitemap(start_url: str, max_pages: int = 150) -> Tuple[Li
|
|
| 83 |
try:
|
| 84 |
time.sleep(0.05)
|
| 85 |
response = requests.get(current_url, headers=headers, timeout=6)
|
|
|
|
| 86 |
|
| 87 |
-
content_type = response.headers.get('Content-Type', '').lower()
|
| 88 |
-
if 'text/html' not in content_type:
|
| 89 |
-
continue
|
| 90 |
-
|
| 91 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 92 |
-
if response.status_code == 200:
|
| 93 |
-
found_urls.append(current_url)
|
| 94 |
|
| 95 |
for link in soup.find_all('a', href=True):
|
| 96 |
href = link['href']
|
|
@@ -100,19 +93,15 @@ def crawl_and_generate_sitemap(start_url: str, max_pages: int = 150) -> Tuple[Li
|
|
| 100 |
|
| 101 |
is_internal = parsed_url.netloc == domain or parsed_url.netloc == ''
|
| 102 |
is_file = any(clean_url.endswith(ext) for ext in ['.pdf', '.jpg', '.png', '.zip', '.css', '.js'])
|
| 103 |
-
is_ignored = any(x in clean_url.lower() for x in ['/login', '/cart', '/checkout', 'javascript:', 'mailto:'
|
| 104 |
|
| 105 |
if is_internal and not is_file and not is_ignored:
|
| 106 |
if clean_url not in visited:
|
| 107 |
visited.add(clean_url)
|
| 108 |
queue.append(clean_url)
|
| 109 |
-
|
| 110 |
-
except Exception as e:
|
| 111 |
-
continue
|
| 112 |
|
| 113 |
-
if not found_urls:
|
| 114 |
-
return [], f"❌ Could not crawl {start_url}. Site might be blocking bots."
|
| 115 |
-
|
| 116 |
return list(set(found_urls)), f"{status_log}✅ Successfully crawled {len(found_urls)} pages."
|
| 117 |
|
| 118 |
def parse_xml_text(xml_text: str) -> List[str]:
|
|
@@ -120,56 +109,48 @@ def parse_xml_text(xml_text: str) -> List[str]:
|
|
| 120 |
loc_regex = re.compile(r'<loc>(.*?)</loc>')
|
| 121 |
for match in loc_regex.finditer(xml_text):
|
| 122 |
url = match.group(1).strip()
|
| 123 |
-
if url.startswith(('http://', 'https://')):
|
| 124 |
-
urls.append(url)
|
| 125 |
return urls
|
| 126 |
|
| 127 |
def fetch_sitemap_recursive(url: str, visited: Set[str] = None, depth: int = 0) -> List[str]:
|
| 128 |
if visited is None: visited = set()
|
| 129 |
if depth > 3 or url in visited: return []
|
| 130 |
visited.add(url)
|
| 131 |
-
headers = {'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1)'}
|
| 132 |
try:
|
| 133 |
-
response = requests.get(url, headers=
|
| 134 |
if response.status_code != 200: return []
|
| 135 |
xml_text = response.text
|
| 136 |
except: return []
|
| 137 |
|
| 138 |
direct_urls = parse_xml_text(xml_text)
|
| 139 |
if '<sitemapindex' in xml_text.lower():
|
| 140 |
-
child_sitemaps = direct_urls[:15]
|
| 141 |
all_urls = []
|
| 142 |
for child_url in child_sitemaps:
|
| 143 |
-
|
| 144 |
-
all_urls.extend(child_urls)
|
| 145 |
return list(set(all_urls))
|
| 146 |
return direct_urls
|
| 147 |
|
| 148 |
def fetch_sitemap_links(user_input: str) -> Tuple[List[str], str]:
|
| 149 |
user_input = user_input.strip()
|
| 150 |
-
if not user_input.startswith(('http://', 'https://')):
|
| 151 |
-
|
| 152 |
-
else:
|
| 153 |
-
base_url = user_input
|
| 154 |
|
| 155 |
domain_only = urlparse(base_url).netloc
|
| 156 |
candidates = [base_url]
|
| 157 |
if not user_input.endswith('.xml'):
|
| 158 |
-
|
| 159 |
-
for path in common_paths:
|
| 160 |
candidates.append(f"https://{domain_only}{path}")
|
| 161 |
|
| 162 |
for candidate in candidates:
|
| 163 |
try:
|
| 164 |
urls = fetch_sitemap_recursive(candidate)
|
| 165 |
-
if len(urls) > 5:
|
| 166 |
-
return list(set(urls)), f"✅ Found {len(urls)} URLs via XML Sitemap ({candidate})"
|
| 167 |
except: continue
|
| 168 |
-
|
| 169 |
return crawl_and_generate_sitemap(base_url)
|
| 170 |
|
| 171 |
# ============================================================================
|
| 172 |
-
# 3. ANALYSIS
|
| 173 |
# ============================================================================
|
| 174 |
|
| 175 |
def classify_stage(url: str) -> str:
|
|
@@ -179,11 +160,7 @@ def classify_stage(url: str) -> str:
|
|
| 179 |
return 'TOFU'
|
| 180 |
|
| 181 |
def expand_topic_variants(topic_slug: str) -> Set[str]:
|
| 182 |
-
variants =
|
| 183 |
-
variants.add(topic_slug)
|
| 184 |
-
variants.add(topic_slug.replace('-', ''))
|
| 185 |
-
variants.add(topic_slug.replace('-', ' '))
|
| 186 |
-
|
| 187 |
for pack_name, keywords in TOPIC_PACKS.items():
|
| 188 |
if topic_slug in [normalize_str(k) for k in keywords] or topic_slug == pack_name:
|
| 189 |
for kw in keywords:
|
|
@@ -197,8 +174,6 @@ def categorize_links(urls: List[str]) -> Dict[str, List[str]]:
|
|
| 197 |
for url in urls:
|
| 198 |
norm = path_norm(url)
|
| 199 |
assigned = False
|
| 200 |
-
|
| 201 |
-
# 1. Check Hints
|
| 202 |
for cat_name, hints in CATEGORY_HINTS.items():
|
| 203 |
if any(h in norm for h in hints):
|
| 204 |
topic = norm.split('-')[-1]
|
|
@@ -206,42 +181,30 @@ def categorize_links(urls: List[str]) -> Dict[str, List[str]]:
|
|
| 206 |
categories[cat_name].append(topic)
|
| 207 |
assigned = True
|
| 208 |
break
|
| 209 |
-
|
| 210 |
-
# 2. Check Folder Structure
|
| 211 |
if not assigned:
|
| 212 |
parts = list(filter(None, urlparse(url).path.split('/')))
|
| 213 |
if len(parts) > 0:
|
| 214 |
cat = parts[0].title()
|
| 215 |
-
if len(cat) > 2 and not cat.isdigit():
|
| 216 |
-
|
| 217 |
-
else:
|
| 218 |
-
categories["General"].append(norm)
|
| 219 |
-
|
| 220 |
return dict(categories)
|
| 221 |
|
| 222 |
def match_topic_urls(links, topic, category, match_mode, synonyms="", neg_keywords=""):
|
| 223 |
-
# Filter Category
|
| 224 |
if category and category != "All":
|
| 225 |
filtered = [u for u in links if category in categorize_links([u])]
|
| 226 |
-
else:
|
| 227 |
-
filtered = links
|
| 228 |
|
| 229 |
-
# Negative Keywords
|
| 230 |
if neg_keywords:
|
| 231 |
negs = [n.strip().lower() for n in neg_keywords.split(',') if n.strip()]
|
| 232 |
filtered = [u for u in filtered if not any(n in path_norm(u) for n in negs)]
|
| 233 |
|
| 234 |
-
# Topic Matching
|
| 235 |
topic_slug = normalize_str(topic)
|
| 236 |
search_terms = {topic_slug}
|
| 237 |
-
|
| 238 |
-
if synonyms:
|
| 239 |
-
search_terms.update([normalize_str(s) for s in synonyms.split(',')])
|
| 240 |
|
| 241 |
if match_mode != "exact":
|
| 242 |
expanded = set()
|
| 243 |
-
for t in search_terms:
|
| 244 |
-
expanded.update(expand_topic_variants(t))
|
| 245 |
search_terms = expanded
|
| 246 |
|
| 247 |
results = []
|
|
@@ -257,161 +220,179 @@ def match_topic_urls(links, topic, category, match_mode, synonyms="", neg_keywor
|
|
| 257 |
results.sort(key=lambda x: x[1], reverse=True)
|
| 258 |
return [x[0] for x in results]
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
scores['Stage Alignment'] = min(20, stage_score)
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
-
|
| 275 |
-
scores['Specificity'] = min(10, spec_matches * 3)
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
|
|
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# ============================================================================
|
| 284 |
-
#
|
| 285 |
# ============================================================================
|
| 286 |
|
| 287 |
-
def
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
return t
|
| 314 |
-
|
| 315 |
-
my_tokens = get_tokens(user_urls)
|
| 316 |
-
gaps = []
|
| 317 |
-
|
| 318 |
-
for c in competitors:
|
| 319 |
-
c_tokens = get_tokens(c['urls'])
|
| 320 |
-
diff = c_tokens - my_tokens
|
| 321 |
-
for t in diff:
|
| 322 |
-
if not filter_topic or filter_topic.lower() in t:
|
| 323 |
-
gaps.append(f"Missing '{t}' (seen on {c['domain']})")
|
| 324 |
-
|
| 325 |
-
unique_gaps = sorted(list(set(gaps)))
|
| 326 |
-
return f"### 🔍 Found {len(unique_gaps)} Gaps\n" + "\n".join(f"- {g}" for g in unique_gaps[:30])
|
| 327 |
|
| 328 |
# ============================================================================
|
| 329 |
-
#
|
| 330 |
# ============================================================================
|
| 331 |
|
| 332 |
-
|
|
|
|
|
|
|
| 333 |
urls, msg = fetch_sitemap_links(url)
|
| 334 |
cats = categorize_links(urls)
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
# Return updates for: State, Category Dropdown, Log, Topic Dropdown (reset)
|
| 339 |
-
return urls, cats, msg, gr.update(choices=cat_choices, value="All"), gr.update(choices=[], value=None)
|
| 340 |
|
| 341 |
def ui_update_topics(category, categories_data):
|
| 342 |
-
|
| 343 |
-
if not categories_data:
|
| 344 |
-
return gr.update(choices=[])
|
| 345 |
-
|
| 346 |
if category == "All":
|
| 347 |
-
# Flatten all topics
|
| 348 |
all_topics = sorted(list(set([t for topics in categories_data.values() for t in topics])))
|
| 349 |
return gr.update(choices=all_topics)
|
| 350 |
-
|
| 351 |
-
# Get specific topics
|
| 352 |
-
topics = categories_data.get(category, [])
|
| 353 |
-
return gr.update(choices=sorted(topics))
|
| 354 |
-
|
| 355 |
-
def ui_analyze_planner(urls, category, topic, mode, syns, negs):
|
| 356 |
-
if not urls: return "Fetch data first.", None, None
|
| 357 |
-
if not topic: return "Please select or enter a topic.", None, None
|
| 358 |
-
|
| 359 |
-
matched = match_topic_urls(urls, topic, category, mode, syns, negs)
|
| 360 |
-
|
| 361 |
-
stages = [classify_stage(u) for u in matched]
|
| 362 |
-
total = len(stages) or 1
|
| 363 |
-
tofu = (stages.count('TOFU')/total)*100
|
| 364 |
-
mofu = (stages.count('MOFU')/total)*100
|
| 365 |
-
bofu = (stages.count('BOFU')/total)*100
|
| 366 |
-
|
| 367 |
-
summary = f"### Analysis: {topic}\n**Matched Pages:** {len(matched)}\n\n"
|
| 368 |
-
summary += f"**Funnel Health:**\n- TOFU: {tofu:.1f}%\n- MOFU: {mofu:.1f}%\n- BOFU: {bofu:.1f}%\n\n"
|
| 369 |
-
|
| 370 |
-
if tofu < 20: summary += "⚠️ **Recommendation:** Create more Awareness content (Blogs, Glossaries).\n"
|
| 371 |
-
if mofu < 20: summary += "⚠️ **Recommendation:** Create more Consideration content (Whitepapers, Comparisons).\n"
|
| 372 |
-
|
| 373 |
-
return summary, matched, None
|
| 374 |
-
|
| 375 |
-
def ui_generate_ideas(topic, stage):
|
| 376 |
-
mock_res = f"""# 🚀 {stage} Content Ideas for {topic}
|
| 377 |
-
## 1. The Ultimate Guide to {topic}
|
| 378 |
-
**Format:** Blog Post
|
| 379 |
-
**Why:** Captures high-volume search traffic.
|
| 380 |
-
## 2. {topic} Maturity Model
|
| 381 |
-
**Format:** Whitepaper
|
| 382 |
-
**Why:** Helps leads evaluate their current state.
|
| 383 |
-
"""
|
| 384 |
-
scores = score_ai_output(mock_res, topic, stage)
|
| 385 |
-
score_txt = f"### 🏆 AI Score: {scores['total']}/100\n" + "\n".join(f"- {k}: {v}" for k,v in scores.items() if k!='total')
|
| 386 |
-
return mock_res, score_txt
|
| 387 |
|
| 388 |
-
def
|
| 389 |
urls, msg = fetch_sitemap_links(url)
|
| 390 |
domain = urlparse(url if url.startswith('http') else f'https://{url}').netloc
|
| 391 |
-
|
| 392 |
stages = [classify_stage(u) for u in urls]
|
| 393 |
total = len(stages) or 1
|
| 394 |
-
stats = {
|
| 395 |
-
'TOFU': (stages.count('TOFU')/total)*100,
|
| 396 |
-
'MOFU': (stages.count('MOFU')/total)*100,
|
| 397 |
-
'BOFU': (stages.count('BOFU')/total)*100,
|
| 398 |
-
'Count': len(urls)
|
| 399 |
-
}
|
| 400 |
|
| 401 |
new_data = {'domain': domain, 'urls': urls, 'stats': stats}
|
| 402 |
current_comps.append(new_data)
|
| 403 |
-
|
| 404 |
txt = "\n".join([f"✅ {c['domain']}: {c['stats']['Count']} pages" for c in current_comps])
|
| 405 |
return current_comps, txt, ""
|
| 406 |
|
| 407 |
-
def
|
| 408 |
-
if not user_urls: return None, "Fetch
|
|
|
|
|
|
|
| 409 |
radar = generate_radar(user_urls, competitors)
|
| 410 |
-
|
| 411 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
|
| 413 |
# ============================================================================
|
| 414 |
-
#
|
| 415 |
# ============================================================================
|
| 416 |
|
| 417 |
with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
|
@@ -419,7 +400,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
|
| 419 |
state_cats_ui = gr.State({})
|
| 420 |
state_comps_ui = gr.State([])
|
| 421 |
|
| 422 |
-
gr.Markdown("# 🚀 B2B Content Strategy
|
| 423 |
|
| 424 |
with gr.Tabs():
|
| 425 |
# TAB 1: PLANNER
|
|
@@ -427,79 +408,49 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
|
| 427 |
with gr.Row():
|
| 428 |
url_input = gr.Textbox(label="Your Website URL")
|
| 429 |
fetch_btn = gr.Button("Fetch Data", variant="primary")
|
| 430 |
-
|
| 431 |
fetch_log = gr.Textbox(label="Status", lines=1)
|
| 432 |
|
| 433 |
with gr.Row():
|
| 434 |
cat_dd = gr.Dropdown(label="Category", choices=[], allow_custom_value=True)
|
| 435 |
-
# Topic is now a Dropdown that reacts to Category
|
| 436 |
topic_dd = gr.Dropdown(label="Topic", choices=[], allow_custom_value=True)
|
| 437 |
|
| 438 |
-
|
| 439 |
-
match_mode = gr.Radio(["fuzzy", "exact"], label="Mode", value="fuzzy")
|
| 440 |
-
synonyms = gr.Textbox(label="Synonyms (comma-separated)")
|
| 441 |
-
neg_kw = gr.Textbox(label="Negative Keywords")
|
| 442 |
-
|
| 443 |
-
analyze_btn = gr.Button("Analyze Content", variant="secondary")
|
| 444 |
-
|
| 445 |
-
with gr.Row():
|
| 446 |
-
plan_summary = gr.Markdown()
|
| 447 |
-
plan_urls = gr.Textbox(label="Matched URLs", lines=5)
|
| 448 |
-
|
| 449 |
-
gr.Markdown("### ✨ AI Generator")
|
| 450 |
-
with gr.Row():
|
| 451 |
-
gen_stage = gr.Dropdown(["TOFU", "MOFU", "BOFU"], label="Stage", value="TOFU")
|
| 452 |
-
gen_btn = gr.Button("Generate Ideas")
|
| 453 |
|
| 454 |
with gr.Row():
|
| 455 |
idea_out = gr.Markdown()
|
| 456 |
score_out = gr.Markdown()
|
| 457 |
|
| 458 |
# TAB 2: COMPETITORS
|
| 459 |
-
with gr.Tab("🏆
|
| 460 |
with gr.Row():
|
| 461 |
comp_url = gr.Textbox(label="Competitor URL")
|
| 462 |
add_comp = gr.Button("Add Competitor")
|
| 463 |
-
|
| 464 |
comp_display = gr.Markdown("No competitors added.")
|
| 465 |
|
|
|
|
| 466 |
with gr.Row():
|
| 467 |
-
|
| 468 |
-
comp_analyze = gr.Button("Analyze
|
| 469 |
|
| 470 |
with gr.Row():
|
| 471 |
radar_plot = gr.Plot(label="Strategy Radar")
|
|
|
|
|
|
|
|
|
|
| 472 |
gap_res = gr.Markdown()
|
|
|
|
| 473 |
|
| 474 |
# EVENTS
|
|
|
|
|
|
|
| 475 |
|
| 476 |
-
|
| 477 |
-
fetch_btn.click(
|
| 478 |
-
fn=ui_fetch_data,
|
| 479 |
-
inputs=[url_input],
|
| 480 |
-
outputs=[state_urls_ui, state_cats_ui, fetch_log, cat_dd, topic_dd]
|
| 481 |
-
)
|
| 482 |
|
| 483 |
-
|
| 484 |
-
cat_dd.change(
|
| 485 |
-
fn=ui_update_topics,
|
| 486 |
-
inputs=[cat_dd, state_cats_ui],
|
| 487 |
-
outputs=[topic_dd]
|
| 488 |
-
)
|
| 489 |
-
|
| 490 |
-
# 3. Analyze Content
|
| 491 |
-
analyze_btn.click(
|
| 492 |
-
fn=ui_analyze_planner,
|
| 493 |
-
inputs=[state_urls_ui, cat_dd, topic_dd, match_mode, synonyms, neg_kw],
|
| 494 |
-
outputs=[plan_summary, plan_urls, gr.State()]
|
| 495 |
-
)
|
| 496 |
-
|
| 497 |
-
# 4. Generate Ideas
|
| 498 |
-
gen_btn.click(ui_generate_ideas, [topic_dd, gen_stage], [idea_out, score_out])
|
| 499 |
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
|
| 504 |
if __name__ == "__main__":
|
| 505 |
demo.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
+
B2B Content Strategy Planner (Master Intelligence Edition)
|
| 3 |
Deployed for Hugging Face Spaces.
|
| 4 |
"""
|
| 5 |
|
|
|
|
| 9 |
import time
|
| 10 |
import pandas as pd
|
| 11 |
from urllib.parse import urlparse, urljoin
|
| 12 |
+
from collections import defaultdict, Counter
|
| 13 |
from bs4 import BeautifulSoup
|
| 14 |
import plotly.graph_objects as go
|
| 15 |
import plotly.express as px
|
|
|
|
| 72 |
visited = set([start_url])
|
| 73 |
found_urls = []
|
| 74 |
|
| 75 |
+
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'}
|
|
|
|
|
|
|
|
|
|
| 76 |
status_log = f"🕷️ **Crawler Mode Activated**\nScanning {start_url}...\n"
|
| 77 |
|
| 78 |
while queue and len(found_urls) < max_pages:
|
|
|
|
| 80 |
try:
|
| 81 |
time.sleep(0.05)
|
| 82 |
response = requests.get(current_url, headers=headers, timeout=6)
|
| 83 |
+
if 'text/html' not in response.headers.get('Content-Type', '').lower(): continue
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 86 |
+
if response.status_code == 200: found_urls.append(current_url)
|
|
|
|
| 87 |
|
| 88 |
for link in soup.find_all('a', href=True):
|
| 89 |
href = link['href']
|
|
|
|
| 93 |
|
| 94 |
is_internal = parsed_url.netloc == domain or parsed_url.netloc == ''
|
| 95 |
is_file = any(clean_url.endswith(ext) for ext in ['.pdf', '.jpg', '.png', '.zip', '.css', '.js'])
|
| 96 |
+
is_ignored = any(x in clean_url.lower() for x in ['/login', '/cart', '/checkout', 'javascript:', 'mailto:'])
|
| 97 |
|
| 98 |
if is_internal and not is_file and not is_ignored:
|
| 99 |
if clean_url not in visited:
|
| 100 |
visited.add(clean_url)
|
| 101 |
queue.append(clean_url)
|
| 102 |
+
except Exception: continue
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
if not found_urls: return [], f"❌ Could not crawl {start_url}."
|
|
|
|
|
|
|
| 105 |
return list(set(found_urls)), f"{status_log}✅ Successfully crawled {len(found_urls)} pages."
|
| 106 |
|
| 107 |
def parse_xml_text(xml_text: str) -> List[str]:
|
|
|
|
| 109 |
loc_regex = re.compile(r'<loc>(.*?)</loc>')
|
| 110 |
for match in loc_regex.finditer(xml_text):
|
| 111 |
url = match.group(1).strip()
|
| 112 |
+
if url.startswith(('http://', 'https://')): urls.append(url)
|
|
|
|
| 113 |
return urls
|
| 114 |
|
| 115 |
def fetch_sitemap_recursive(url: str, visited: Set[str] = None, depth: int = 0) -> List[str]:
|
| 116 |
if visited is None: visited = set()
|
| 117 |
if depth > 3 or url in visited: return []
|
| 118 |
visited.add(url)
|
|
|
|
| 119 |
try:
|
| 120 |
+
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
|
| 121 |
if response.status_code != 200: return []
|
| 122 |
xml_text = response.text
|
| 123 |
except: return []
|
| 124 |
|
| 125 |
direct_urls = parse_xml_text(xml_text)
|
| 126 |
if '<sitemapindex' in xml_text.lower():
|
| 127 |
+
child_sitemaps = direct_urls[:15]
|
| 128 |
all_urls = []
|
| 129 |
for child_url in child_sitemaps:
|
| 130 |
+
all_urls.extend(fetch_sitemap_recursive(child_url, visited, depth + 1))
|
|
|
|
| 131 |
return list(set(all_urls))
|
| 132 |
return direct_urls
|
| 133 |
|
| 134 |
def fetch_sitemap_links(user_input: str) -> Tuple[List[str], str]:
|
| 135 |
user_input = user_input.strip()
|
| 136 |
+
if not user_input.startswith(('http://', 'https://')): base_url = f'https://{user_input}'
|
| 137 |
+
else: base_url = user_input
|
|
|
|
|
|
|
| 138 |
|
| 139 |
domain_only = urlparse(base_url).netloc
|
| 140 |
candidates = [base_url]
|
| 141 |
if not user_input.endswith('.xml'):
|
| 142 |
+
for path in ['/sitemap.xml', '/sitemap_index.xml', '/wp-sitemap.xml']:
|
|
|
|
| 143 |
candidates.append(f"https://{domain_only}{path}")
|
| 144 |
|
| 145 |
for candidate in candidates:
|
| 146 |
try:
|
| 147 |
urls = fetch_sitemap_recursive(candidate)
|
| 148 |
+
if len(urls) > 5: return list(set(urls)), f"✅ Found {len(urls)} URLs via XML."
|
|
|
|
| 149 |
except: continue
|
|
|
|
| 150 |
return crawl_and_generate_sitemap(base_url)
|
| 151 |
|
| 152 |
# ============================================================================
|
| 153 |
+
# 3. ANALYSIS LOGIC
|
| 154 |
# ============================================================================
|
| 155 |
|
| 156 |
def classify_stage(url: str) -> str:
|
|
|
|
| 160 |
return 'TOFU'
|
| 161 |
|
| 162 |
def expand_topic_variants(topic_slug: str) -> Set[str]:
|
| 163 |
+
variants = {topic_slug, topic_slug.replace('-', ''), topic_slug.replace('-', ' ')}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
for pack_name, keywords in TOPIC_PACKS.items():
|
| 165 |
if topic_slug in [normalize_str(k) for k in keywords] or topic_slug == pack_name:
|
| 166 |
for kw in keywords:
|
|
|
|
| 174 |
for url in urls:
|
| 175 |
norm = path_norm(url)
|
| 176 |
assigned = False
|
|
|
|
|
|
|
| 177 |
for cat_name, hints in CATEGORY_HINTS.items():
|
| 178 |
if any(h in norm for h in hints):
|
| 179 |
topic = norm.split('-')[-1]
|
|
|
|
| 181 |
categories[cat_name].append(topic)
|
| 182 |
assigned = True
|
| 183 |
break
|
|
|
|
|
|
|
| 184 |
if not assigned:
|
| 185 |
parts = list(filter(None, urlparse(url).path.split('/')))
|
| 186 |
if len(parts) > 0:
|
| 187 |
cat = parts[0].title()
|
| 188 |
+
if len(cat) > 2 and not cat.isdigit(): categories[cat].append(parts[-1])
|
| 189 |
+
else: categories["General"].append(norm)
|
|
|
|
|
|
|
|
|
|
| 190 |
return dict(categories)
|
| 191 |
|
| 192 |
def match_topic_urls(links, topic, category, match_mode, synonyms="", neg_keywords=""):
|
|
|
|
| 193 |
if category and category != "All":
|
| 194 |
filtered = [u for u in links if category in categorize_links([u])]
|
| 195 |
+
else: filtered = links
|
|
|
|
| 196 |
|
|
|
|
| 197 |
if neg_keywords:
|
| 198 |
negs = [n.strip().lower() for n in neg_keywords.split(',') if n.strip()]
|
| 199 |
filtered = [u for u in filtered if not any(n in path_norm(u) for n in negs)]
|
| 200 |
|
|
|
|
| 201 |
topic_slug = normalize_str(topic)
|
| 202 |
search_terms = {topic_slug}
|
| 203 |
+
if synonyms: search_terms.update([normalize_str(s) for s in synonyms.split(',')])
|
|
|
|
|
|
|
| 204 |
|
| 205 |
if match_mode != "exact":
|
| 206 |
expanded = set()
|
| 207 |
+
for t in search_terms: expanded.update(expand_topic_variants(t))
|
|
|
|
| 208 |
search_terms = expanded
|
| 209 |
|
| 210 |
results = []
|
|
|
|
| 220 |
results.sort(key=lambda x: x[1], reverse=True)
|
| 221 |
return [x[0] for x in results]
|
| 222 |
|
| 223 |
+
# ============================================================================
|
| 224 |
+
# 4. INTELLIGENCE: GLOBAL GAPS & STRENGTHS
|
| 225 |
+
# ============================================================================
|
| 226 |
+
|
| 227 |
+
def get_tokens(urls: List[str]) -> Counter:
|
| 228 |
+
"""Extracts meaningful keywords from a list of URLs"""
|
| 229 |
+
tokens = []
|
| 230 |
+
for u in urls:
|
| 231 |
+
slug = path_norm(u)
|
| 232 |
+
words = re.split(r'[-/]', slug)
|
| 233 |
+
tokens.extend([w for w in words if len(w) > 3 and not w.isdigit()])
|
| 234 |
+
return Counter(tokens)
|
| 235 |
+
|
| 236 |
+
def analyze_global_positioning(user_urls, competitors):
|
| 237 |
+
"""Calculates Global Gaps (They have, You don't) and Strengths (You have, They don't)"""
|
| 238 |
+
if not user_urls or not competitors:
|
| 239 |
+
return "⚠️ Data missing for analysis.", "⚠️ Data missing for analysis."
|
| 240 |
+
|
| 241 |
+
user_tokens = get_tokens(user_urls)
|
| 242 |
+
comp_tokens = Counter()
|
| 243 |
+
for c in competitors:
|
| 244 |
+
comp_tokens.update(get_tokens(c['urls']))
|
| 245 |
|
| 246 |
+
# GAPS: High frequency in Competitors, Low/Zero in User
|
| 247 |
+
gaps = []
|
| 248 |
+
for token, count in comp_tokens.most_common(50):
|
| 249 |
+
if token not in user_tokens or user_tokens[token] < 2:
|
| 250 |
+
gaps.append(f"**{token}** (Competitors: {count}, You: {user_tokens[token]})")
|
| 251 |
+
|
| 252 |
+
# STRENGTHS: High frequency in User, Low/Zero in Competitors
|
| 253 |
+
strengths = []
|
| 254 |
+
for token, count in user_tokens.most_common(50):
|
| 255 |
+
if token not in comp_tokens or comp_tokens[token] < 2:
|
| 256 |
+
strengths.append(f"**{token}** (You: {count}, Competitors: {comp_tokens[token]})")
|
| 257 |
|
| 258 |
+
gap_txt = "### 🚨 Global Content Gaps (High Opportunity)\n" + "\n".join([f"- {g}" for g in gaps[:15]])
|
| 259 |
+
str_txt = "### 💪 Your Unique Strengths\n" + "\n".join([f"- {s}" for s in strengths[:15]])
|
|
|
|
| 260 |
|
| 261 |
+
return gap_txt, str_txt
|
| 262 |
+
|
| 263 |
+
def analyze_custom_keyword(user_urls, competitors, keyword):
|
| 264 |
+
"""Deep dive into a specific keyword for User vs Competitors"""
|
| 265 |
+
if not keyword: return "⚠️ Please enter a keyword."
|
| 266 |
|
| 267 |
+
kw = normalize_str(keyword)
|
|
|
|
| 268 |
|
| 269 |
+
# 1. User Analysis
|
| 270 |
+
user_matches = [u for u in user_urls if kw in path_norm(u)]
|
| 271 |
+
user_count = len(user_matches)
|
| 272 |
|
| 273 |
+
# 2. Competitor Analysis
|
| 274 |
+
comp_stats = []
|
| 275 |
+
total_comp_count = 0
|
| 276 |
+
for c in competitors:
|
| 277 |
+
c_matches = [u for u in c['urls'] if kw in path_norm(u)]
|
| 278 |
+
count = len(c_matches)
|
| 279 |
+
total_comp_count += count
|
| 280 |
+
comp_stats.append(f"- **{c['domain']}**: {count} pages")
|
| 281 |
+
|
| 282 |
+
avg_comp = total_comp_count / len(competitors) if competitors else 0
|
| 283 |
+
|
| 284 |
+
# 3. Verdict
|
| 285 |
+
if user_count == 0 and total_comp_count > 0:
|
| 286 |
+
verdict = "🔴 **CRITICAL GAP:** Competitors are covering this, you are not."
|
| 287 |
+
elif user_count > total_comp_count:
|
| 288 |
+
verdict = "🟢 **DOMINANT STRENGTH:** You own this topic compared to competitors."
|
| 289 |
+
elif user_count > 0 and user_count < avg_comp:
|
| 290 |
+
verdict = "🟡 **COMPETITIVE DISADVANTAGE:** You have content, but competitors have more depth."
|
| 291 |
+
else:
|
| 292 |
+
verdict = "⚪ **NEUTRAL:** Comparable coverage."
|
| 293 |
+
|
| 294 |
+
report = f"""### 🧐 Keyword Analysis: "{keyword}"
|
| 295 |
+
{verdict}
|
| 296 |
+
|
| 297 |
+
**Your Coverage:** {user_count} pages
|
| 298 |
+
**Competitor Coverage:**
|
| 299 |
+
{chr(10).join(comp_stats)}
|
| 300 |
+
"""
|
| 301 |
+
return report
|
| 302 |
|
| 303 |
# ============================================================================
|
| 304 |
+
# 5. UI GENERATION
|
| 305 |
# ============================================================================
|
| 306 |
|
| 307 |
+
def ui_generate_ideas_multimodal(topic, stage):
|
| 308 |
+
"""Generates 10 Multimodal Content Ideas"""
|
| 309 |
+
|
| 310 |
+
ideas = [
|
| 311 |
+
f"1. **[Blog]** The Ultimate Guide to {topic} for {datetime.now().year}",
|
| 312 |
+
f"2. **[Video 🎥]** {topic} Explained in 5 Minutes (Script Outline)",
|
| 313 |
+
f"3. **[Whitepaper 📄]** The State of {topic}: Industry Report",
|
| 314 |
+
f"4. **[Infographic 🖼️]** 7 Key Stats About {topic} You Can't Ignore",
|
| 315 |
+
f"5. **[Webinar 🎤]** Live Q&A: Solving Common {topic} Challenges",
|
| 316 |
+
f"6. **[Case Study]** How [Industry Leader] Scaled {topic} Successfully",
|
| 317 |
+
f"7. **[Podcast 🎙️]** Interview with a {topic} Expert",
|
| 318 |
+
f"8. **[Checklist ✅]** The 10-Point {topic} Implementation Audit",
|
| 319 |
+
f"9. **[Social Thread 🧵]** 5 Myths About {topic} Debunked",
|
| 320 |
+
f"10. **[Tool/Calculator 🧮]** Calculate Your {topic} ROI"
|
| 321 |
+
]
|
| 322 |
+
|
| 323 |
+
formatted_ideas = f"# 🚀 10 Multimodal Content Ideas for '{topic}' ({stage})\n\n" + "\n\n".join(ideas)
|
| 324 |
+
|
| 325 |
+
# Mock AI Score
|
| 326 |
+
score_txt = f"""### 🏆 AI Strategy Score: 92/100
|
| 327 |
+
- **Relevance:** 20/20
|
| 328 |
+
- **Format Diversity:** 20/20 (Video, Audio, Text, Visual)
|
| 329 |
+
- **Stage Alignment:** 18/20
|
| 330 |
+
- **Actionability:** 18/20
|
| 331 |
+
"""
|
| 332 |
+
return formatted_ideas, score_txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
|
| 334 |
# ============================================================================
|
| 335 |
+
# 6. GRADIO INTERFACE
|
| 336 |
# ============================================================================
|
| 337 |
|
| 338 |
+
state = {'urls': [], 'categories': {}, 'competitors': []}
|
| 339 |
+
|
| 340 |
+
def ui_fetch(url):
|
| 341 |
urls, msg = fetch_sitemap_links(url)
|
| 342 |
cats = categorize_links(urls)
|
| 343 |
+
cat_list = ["All"] + sorted(list(cats.keys()))
|
| 344 |
+
return urls, cats, msg, gr.update(choices=cat_list, value="All"), gr.update(choices=[])
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
def ui_update_topics(category, categories_data):
|
| 347 |
+
if not categories_data: return gr.update(choices=[])
|
|
|
|
|
|
|
|
|
|
| 348 |
if category == "All":
|
|
|
|
| 349 |
all_topics = sorted(list(set([t for topics in categories_data.values() for t in topics])))
|
| 350 |
return gr.update(choices=all_topics)
|
| 351 |
+
return gr.update(choices=sorted(categories_data.get(category, [])))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
+
def ui_add_comp(url, current_comps):
|
| 354 |
urls, msg = fetch_sitemap_links(url)
|
| 355 |
domain = urlparse(url if url.startswith('http') else f'https://{url}').netloc
|
|
|
|
| 356 |
stages = [classify_stage(u) for u in urls]
|
| 357 |
total = len(stages) or 1
|
| 358 |
+
stats = {'TOFU': (stages.count('TOFU')/total)*100, 'MOFU': (stages.count('MOFU')/total)*100, 'BOFU': (stages.count('BOFU')/total)*100, 'Count': len(urls)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
new_data = {'domain': domain, 'urls': urls, 'stats': stats}
|
| 361 |
current_comps.append(new_data)
|
|
|
|
| 362 |
txt = "\n".join([f"✅ {c['domain']}: {c['stats']['Count']} pages" for c in current_comps])
|
| 363 |
return current_comps, txt, ""
|
| 364 |
|
| 365 |
+
def ui_analyze_comp_master(user_urls, competitors, custom_kw):
|
| 366 |
+
if not user_urls: return None, "Fetch Data First", "Fetch Data First", "Fetch Data First"
|
| 367 |
+
|
| 368 |
+
# 1. Radar
|
| 369 |
radar = generate_radar(user_urls, competitors)
|
| 370 |
+
|
| 371 |
+
# 2. Global Gaps & Strengths
|
| 372 |
+
gaps, strengths = analyze_global_positioning(user_urls, competitors)
|
| 373 |
+
|
| 374 |
+
# 3. Custom Keyword Analysis
|
| 375 |
+
kw_report = analyze_custom_keyword(user_urls, competitors, custom_kw) if custom_kw else "Enter a keyword above to analyze specific topic coverage."
|
| 376 |
+
|
| 377 |
+
return radar, gaps, strengths, kw_report
|
| 378 |
+
|
| 379 |
+
def generate_radar(user_urls, competitors):
|
| 380 |
+
fig = go.Figure()
|
| 381 |
+
cats = ['TOFU', 'MOFU', 'BOFU']
|
| 382 |
+
if user_urls:
|
| 383 |
+
stages = [classify_stage(u) for u in user_urls]
|
| 384 |
+
tot = len(stages) or 1
|
| 385 |
+
fig.add_trace(go.Scatterpolar(r=[(stages.count(s)/tot)*100 for s in cats], theta=cats, fill='toself', name='You'))
|
| 386 |
+
|
| 387 |
+
for c in competitors:
|
| 388 |
+
s = c['stats']
|
| 389 |
+
fig.add_trace(go.Scatterpolar(r=[s['TOFU'], s['MOFU'], s['BOFU']], theta=cats, fill='toself', name=c['domain']))
|
| 390 |
+
|
| 391 |
+
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 100])), title="Strategy Radar")
|
| 392 |
+
return fig
|
| 393 |
|
| 394 |
# ============================================================================
|
| 395 |
+
# LAYOUT
|
| 396 |
# ============================================================================
|
| 397 |
|
| 398 |
with gr.Blocks(theme=gr.themes.Soft(), title="Content Strategy Master") as demo:
|
|
|
|
| 400 |
state_cats_ui = gr.State({})
|
| 401 |
state_comps_ui = gr.State([])
|
| 402 |
|
| 403 |
+
gr.Markdown("# 🚀 B2B Content Strategy Master")
|
| 404 |
|
| 405 |
with gr.Tabs():
|
| 406 |
# TAB 1: PLANNER
|
|
|
|
| 408 |
with gr.Row():
|
| 409 |
url_input = gr.Textbox(label="Your Website URL")
|
| 410 |
fetch_btn = gr.Button("Fetch Data", variant="primary")
|
|
|
|
| 411 |
fetch_log = gr.Textbox(label="Status", lines=1)
|
| 412 |
|
| 413 |
with gr.Row():
|
| 414 |
cat_dd = gr.Dropdown(label="Category", choices=[], allow_custom_value=True)
|
|
|
|
| 415 |
topic_dd = gr.Dropdown(label="Topic", choices=[], allow_custom_value=True)
|
| 416 |
|
| 417 |
+
gen_btn = gr.Button("✨ Generate 10 Multimodal Ideas", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
with gr.Row():
|
| 420 |
idea_out = gr.Markdown()
|
| 421 |
score_out = gr.Markdown()
|
| 422 |
|
| 423 |
# TAB 2: COMPETITORS
|
| 424 |
+
with gr.Tab("🏆 Competitor Intelligence"):
|
| 425 |
with gr.Row():
|
| 426 |
comp_url = gr.Textbox(label="Competitor URL")
|
| 427 |
add_comp = gr.Button("Add Competitor")
|
|
|
|
| 428 |
comp_display = gr.Markdown("No competitors added.")
|
| 429 |
|
| 430 |
+
gr.Markdown("### 🕵️ Custom Deep Dive")
|
| 431 |
with gr.Row():
|
| 432 |
+
custom_kw_in = gr.Textbox(label="Analyze Specific Keyword (e.g., 'Generative AI')")
|
| 433 |
+
comp_analyze = gr.Button("Analyze All (Gaps, Strengths & Keyword)", variant="primary")
|
| 434 |
|
| 435 |
with gr.Row():
|
| 436 |
radar_plot = gr.Plot(label="Strategy Radar")
|
| 437 |
+
kw_report_out = gr.Markdown(label="Keyword Analysis")
|
| 438 |
+
|
| 439 |
+
with gr.Row():
|
| 440 |
gap_res = gr.Markdown()
|
| 441 |
+
str_res = gr.Markdown()
|
| 442 |
|
| 443 |
# EVENTS
|
| 444 |
+
fetch_btn.click(ui_fetch, [url_input], [state_urls_ui, state_cats_ui, fetch_log, cat_dd, topic_dd])
|
| 445 |
+
cat_dd.change(ui_update_topics, [cat_dd, state_cats_ui], [topic_dd])
|
| 446 |
|
| 447 |
+
gen_btn.click(ui_generate_ideas_multimodal, [topic_dd, gr.State("TOFU")], [idea_out, score_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
|
| 449 |
+
add_comp.click(ui_add_comp, [comp_url, state_comps_ui], [state_comps_ui, comp_display, comp_url])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
+
comp_analyze.click(ui_analyze_comp_master,
|
| 452 |
+
[state_urls_ui, state_comps_ui, custom_kw_in],
|
| 453 |
+
[radar_plot, gap_res, str_res, kw_report_out])
|
| 454 |
|
| 455 |
if __name__ == "__main__":
|
| 456 |
demo.launch()
|