mktgtech commited on
Commit
71138f9
Β·
verified Β·
1 Parent(s): c23c527

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +313 -323
app.py CHANGED
@@ -1,7 +1,7 @@
1
  """
2
- B2B Content Strategy Planner & Competitor Intelligence (Master Version)
3
  Deployed for Hugging Face Spaces.
4
- Includes: Full Topic Packs, Advanced Matching, AI Scoring, and Radar Analytics.
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
- "Our Work": ["our-work", "work", "portfolio", "projects"],
46
- "Webinar": ["webinar", "webinars", "event", "masterclass"]
 
47
  }
48
 
49
  # ============================================================================
50
- # 2. CORE LOGIC: NORMALIZATION & EXPANSION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 slugify_topic(topic_text: str) -> str:
67
- return normalize_str(topic_text)
 
 
 
68
 
69
  def expand_topic_variants(topic_slug: str) -> set:
70
- """Expand topic into variants (hyphens, spaces, pack keywords)"""
71
- variants = set()
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
- # Check topic packs
83
  for pack_name, keywords in TOPIC_PACKS.items():
84
- # Check if the topic matches a pack keyword
85
- if any(normalize_str(kw) == topic_slug for kw in keywords):
86
  for kw in keywords:
87
- norm_kw = normalize_str(kw)
88
- variants.add(norm_kw)
89
- variants.add(norm_kw.replace('-', ''))
90
- variants.add(norm_kw.replace('-', ' '))
91
  break
92
-
93
  return variants
94
 
95
- # ============================================================================
96
- # 3. ADVANCED MATCHING & CATEGORIZATION
97
- # ============================================================================
98
-
99
- def filter_by_category(urls: list, category: str) -> list:
100
- if not category or category == "All": return urls
101
- hints = CATEGORY_HINTS.get(category, [normalize_str(category)])
102
- return [u for u in urls if any(hint in path_norm(u) for hint in hints)]
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- def match_topic_urls(links: list, topic_text: str, category: str,
105
- matching_mode: str = "fuzzy", synonyms: str = "", negative_keywords: str = "") -> list:
106
-
107
- # 1. Filter Category
108
- filtered = filter_by_category(links, category)
109
 
110
  # 2. Negative Keywords
111
- negatives = [k.strip().lower() for k in negative_keywords.split(',') if k.strip()]
112
- if negatives:
113
- filtered = [u for u in filtered if not any(neg in path_norm(u) for neg in negatives)]
114
-
115
- topic_slug = slugify_topic(topic_text)
 
116
  search_terms = {topic_slug}
117
 
118
- # Add Synonyms
119
  if synonyms:
120
- for syn in synonyms.split(','):
121
- if syn.strip(): search_terms.add(slugify_topic(syn.strip()))
122
-
123
- # 3. Matching Strategy
124
- if matching_mode == "exact":
125
- # Strict matching
126
- results = []
127
- for url in filtered:
128
- norm = path_norm(url)
129
- if any(term in norm.split('-') for term in search_terms): # Must match a whole token
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 expanded_terms:
143
  if term in norm:
144
  score += 10
145
- if term in norm.split('-'): score += 5 # Bonus for exact token match
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
- # Try Specific Hints first
162
- for cat_name, hints in CATEGORY_HINTS.items():
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
- """The 7-Criteria Scoring System from the Master Prompt"""
216
  scores = {'total': 0}
217
  lower_out = output_text.lower()
218
 
219
- # 1. Topic Relevance (20 pts)
220
- topic_words = normalize_str(topic).split('-')
221
- matches = sum(lower_out.count(w) for w in topic_words)
222
- scores['Topic Relevance'] = min(20, matches * 2)
223
 
224
- # 2. Stage Alignment (20 pts)
225
- stage_kws = {
226
- 'TOFU': ['awareness', 'guide', 'what is', 'trends', 'blog'],
227
- 'MOFU': ['comparison', 'strategy', 'whitepaper', 'best practices'],
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 (15 pts)
234
  struct_score = 0
235
- if '##' in output_text or 'Title:' in output_text: struct_score += 5
236
- if 'Description:' in output_text or 'summary' in lower_out: struct_score += 5
237
- if 'Format:' in output_text: struct_score += 5
238
  scores['Structure'] = struct_score
239
 
240
- # 4. Specificity (10 pts) (Regex for numbers, $, %)
241
- spec_matches = len(re.findall(r'\d+%|\$\d+|\d+ steps', output_text))
242
- scores['Specificity'] = min(10, spec_matches * 2)
243
 
244
- # 5. Creativity (10 pts)
245
- creative_words = ['unique', 'fresh', 'story', 'narrative', 'engaging']
246
- creat_matches = sum(1 for w in creative_words if w in lower_out)
247
- scores['Creativity'] = min(10, creat_matches * 2)
248
 
249
- # 6. Actionability (10 pts)
250
- action_words = ['step-by-step', 'implement', 'execute', 'template']
251
- act_matches = sum(1 for w in action_words if w in lower_out)
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
- # 5. CRAWLER & SITEMAP UTILS
259
  # ============================================================================
260
 
261
- def crawl_and_generate_sitemap(start_url: str, max_pages: int = 60):
262
- if not start_url.startswith(('http://', 'https://')): start_url = f'https://{start_url}'
263
- domain = urlparse(start_url).netloc
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
- while queue and len(found_urls) < max_pages:
270
- current_url = queue.pop(0)
271
- try:
272
- time.sleep(0.05)
273
- resp = requests.get(current_url, headers=headers, timeout=5)
274
- if 'text/html' not in resp.headers.get('Content-Type', '').lower(): continue
275
- if resp.status_code == 200: found_urls.append(current_url)
276
-
277
- soup = BeautifulSoup(resp.text, 'html.parser')
278
- for link in soup.find_all('a', href=True):
279
- full_url = urljoin(current_url, link['href']).split('#')[0].split('?')[0].rstrip('/')
280
- p_url = urlparse(full_url)
281
- if (p_url.netloc == domain or p_url.netloc == '') and not any(x in full_url for x in ['.pdf', '.jpg', 'login', 'cart']):
282
- if full_url not in visited:
283
- visited.add(full_url)
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
- for url in candidates:
294
- try:
295
- r = requests.get(url, timeout=10, headers={'User-Agent': 'Googlebot/2.1'})
296
- if r.status_code == 200 and '<loc>' in r.text:
297
- urls = re.findall(r'<loc>(.*?)</loc>', r.text)
298
- if len(urls) > 5: return list(set(urls)), f"βœ… Found {len(urls)} URLs via XML."
299
- except: continue
 
 
300
 
301
- return crawl_and_generate_sitemap(base_url)
 
 
 
 
 
 
 
 
 
 
 
302
 
303
  # ============================================================================
304
- # 6. GRADIO INTERFACE LOGIC
305
  # ============================================================================
306
 
307
- def ui_fetch(url):
308
- urls, msg = fetch_sitemap_links(url)
309
- cats = categorize_links_strict(urls)
310
  return urls, cats, msg, list(cats.keys())
311
 
312
- def ui_analyze(urls, category, topic, match_mode, synonyms, neg_kw):
313
- if not urls: return "Please fetch data first.", None, None
 
 
314
 
315
- matched = match_topic_urls(urls, topic, category, match_mode, synonyms, neg_kw)
316
- funnel_data = analyze_funnel_gaps(matched, topic)
 
 
 
317
 
318
- summary = f"### Analysis: {topic}\n"
319
- summary += f"**Matched URLs:** {len(matched)}\n\n"
320
- summary += "\n".join(funnel_data['recommendations'])
321
 
322
- return summary, matched[:50], funnel_data
323
-
324
- def ui_generate_ideas(topic, stage, openai_key):
325
- # Mock generation if no key (to prevent crash), normally would use OpenAI/LangChain
326
 
327
- mock_response = f"""# πŸš€ Content Ideas for {topic} ({stage})
 
 
 
 
328
 
329
- ## 1. The Complete Guide to {topic}
330
  **Format:** Blog Post
331
- **Why:** Addresses high-volume search intent. Matches {stage} needs for education.
332
- **Steps:** 1. Define {topic}. 2. Benefits (ROI of 30%). 3. Implementation.
333
 
334
- ## 2. {topic} Strategy Template
335
  **Format:** Whitepaper
336
- **Why:** Actionable resource.
337
- **Details:** Includes step-by-step framework.
338
 
339
- ## 3. Case Study: How Company X Solved {topic}
340
- **Format:** Case Study
341
- **Why:** Proof point for decision makers.
342
  """
343
-
344
- # Calculate Score
345
- scores = score_ai_output(mock_response, topic, stage)
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
- # --- COMPETITOR LOGIC ---
353
-
354
- def ui_add_competitor(comp_url, current_list):
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
- new_data['stats'] = {
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
- def get_tokens(urls):
383
- t = set()
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
- my_tokens = get_tokens(user_urls)
390
- gaps = []
391
-
392
- for c in competitors:
393
- c_tokens = get_tokens(c['urls'])
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
- # 7. UI LAYOUT
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
- state_competitors = gr.State([])
429
 
430
- gr.Markdown("# πŸš€ B2B Content Strategy Planner & Competitor Intelligence")
431
 
432
  with gr.Tabs():
433
  # TAB 1: PLANNER
434
  with gr.Tab("πŸ“‹ Planner"):
435
  with gr.Row():
436
- url_input = gr.Textbox(label="Sitemap URL", placeholder="example.com")
 
437
  fetch_btn = gr.Button("Fetch Data", variant="primary")
438
 
439
- fetch_log = gr.Textbox(label="Status", visible=True)
440
 
441
  with gr.Row():
442
  cat_dd = gr.Dropdown(label="Category", choices=[])
443
- topic_input = gr.Textbox(label="Topic")
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="primary")
451
 
452
  with gr.Row():
453
- res_summary = gr.Markdown()
454
- res_list = gr.Textbox(label="Matched URLs", lines=5)
455
 
456
- gr.Markdown("### ✨ AI Content Generation")
457
  with gr.Row():
458
- stage_dd = gr.Dropdown(["TOFU", "MOFU", "BOFU"], label="Funnel Stage", value="TOFU")
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
- idea_output = gr.Markdown()
464
- score_output = gr.Markdown()
465
 
466
  # TAB 2: COMPETITORS
467
  with gr.Tab("πŸ† Competitors"):
468
  with gr.Row():
469
- comp_input = gr.Textbox(label="Competitor Domain")
470
- add_comp_btn = gr.Button("Add Competitor")
471
 
472
  comp_display = gr.Markdown("No competitors added.")
473
 
474
  with gr.Row():
475
- gap_filter = gr.Textbox(label="Filter Gaps (Topic)")
476
- comp_analyze_btn = gr.Button("Analyze Gaps & Radar")
477
 
478
  with gr.Row():
 
479
  gap_res = gr.Markdown()
480
- radar_plot = gr.Plot()
481
 
482
- # EVENT HANDLERS
483
- fetch_btn.click(ui_fetch, url_input, [state_urls, state_cats, fetch_log, cat_dd])
484
 
485
- analyze_btn.click(ui_analyze,
486
- [state_urls, cat_dd, topic_input, match_mode, synonyms, neg_kw],
487
- [res_summary, res_list, gr.State()])
488
 
489
- gen_btn.click(ui_generate_ideas, [topic_input, stage_dd, api_key], [idea_output, score_output])
490
 
491
- add_comp_btn.click(ui_add_competitor, [comp_input, state_competitors], [state_competitors, comp_display, comp_input])
492
 
493
- comp_analyze_btn.click(ui_analyze_gaps, [state_urls, state_competitors, gap_filter], [gap_res, radar_plot])
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()