Spaces:
Sleeping

curium-intel / generator.py
Piers Lyon
Claude Opus 4.6
Add annual report text mining and CQC inspection triggers
aa0f1ab
Raw History Blame Contribute Delete
24.5 kB
"""
Generator Module (generator.py)
Smart mission generator that creates targeted hunting tasks.
Defines hunting grounds and generates daily mission queues.
"""
import yaml
from datetime import datetime, timedelta
from typing import Optional
import random
# =============================================================================
# HUNTING GROUNDS CONFIGURATION
# =============================================================================
HUNTING_GROUNDS = {
# -------------------------------------------------------------------------
# 1. LINKEDIN JOBS
# -------------------------------------------------------------------------
"linkedin_jobs": {
"name": "LinkedIn Jobs",
"type": "jobs",
"enabled": True,
"base_url": "https://www.linkedin.com/jobs/search/",
"keywords": [
# High-value CODE keywords
"Head of Transformation",
"Director of Change",
"Head of Leadership Development",
"Chief People Officer",
"Head of Organisational Development",
"VP People & Culture",
"Head of Culture",
"Director of HR Transformation",
"Head of Team Effectiveness",
"Leadership Capability Lead",
# Medium-value keywords
"Transformation Lead",
"Change Director",
"Culture Change Manager",
"Organisational Design Lead",
"People Strategy Director",
],
"locations": ["United Kingdom", "London", "Manchester", "Birmingham"],
"filters": {
"date_posted": "past-24-hours", # r86400
"experience_level": ["Director", "Executive"],
"job_type": "full-time",
},
"priority": "high",
"rate_limit": 3, # Max searches per run
},
# -------------------------------------------------------------------------
# 2. GOOGLE NEWS - Company Strategic Signals
# -------------------------------------------------------------------------
"google_news_strategic": {
"name": "Google News - Strategic Reviews",
"type": "news",
"enabled": True,
"base_url": "https://news.google.com/search",
"query_templates": [
'"{company}" strategic review',
'"{company}" transformation programme',
'"{company}" restructuring',
'"{company}" new CEO',
'"{company}" leadership change',
'"{company}" culture change',
'"{company}" workforce transformation',
],
"companies": [], # Populated from config.yaml
"priority": "high",
"rate_limit": 10,
},
# -------------------------------------------------------------------------
# 3. GOOGLE NEWS - Sector Challenges
# -------------------------------------------------------------------------
"google_news_sector": {
"name": "Google News - Sector Challenges",
"type": "news",
"enabled": True,
"base_url": "https://news.google.com/search",
"query_templates": [
'"{sector}" challenges UK',
'"{sector}" crisis UK',
'"{sector}" restructuring UK',
'"{sector}" job cuts UK',
'"{sector}" transformation UK',
'"{sector}" profit warning',
],
"sectors": [], # Populated from config.yaml
"priority": "medium",
"rate_limit": 6,
},
# -------------------------------------------------------------------------
# 4. UK GOVERNMENT TENDERS
# -------------------------------------------------------------------------
"uk_tenders": {
"name": "UK Government Tenders",
"type": "tenders",
"enabled": True,
"api_url": "https://www.find-tender.service.gov.uk/api/1.0/ocdsReleasePackages",
"keywords": [
"transformation",
"organisational design",
"leadership development",
"change management",
"culture change",
"team effectiveness",
"executive coaching",
"360 feedback",
"employee engagement",
"behavioural change",
"workforce development",
"people strategy",
],
"lookback_hours": 24,
"min_value": 50000,
"priority": "high",
"rate_limit": 1, # Single API call with filters
},
# -------------------------------------------------------------------------
# 5. SPECIALIST SITES - Sector-Specific News
# -------------------------------------------------------------------------
"specialist_retail": {
"name": "The Grocer (Retail)",
"type": "specialist_news",
"enabled": True,
"sector": "UK Retail",
"base_url": "https://www.thegrocer.co.uk",
"search_url": "https://www.thegrocer.co.uk/search",
"rss_url": "https://www.thegrocer.co.uk/rss",
"keywords": [
"restructuring",
"new CEO",
"transformation",
"store closures",
"job cuts",
"strategic review",
"leadership",
],
"priority": "medium",
"rate_limit": 2,
},
"specialist_construction": {
"name": "Construction Enquirer",
"type": "specialist_news",
"enabled": False, # Enable if targeting construction
"sector": "UK Construction",
"base_url": "https://www.constructionenquirer.com",
"search_url": "https://www.constructionenquirer.com/?s=",
"keywords": [
"restructuring",
"administration",
"new CEO",
"transformation",
"job cuts",
],
"priority": "medium",
"rate_limit": 2,
},
"specialist_financial": {
"name": "Financial News (City AM)",
"type": "specialist_news",
"enabled": True,
"sector": "UK Financial Services",
"base_url": "https://www.cityam.com",
"search_url": "https://www.cityam.com/?s=",
"keywords": [
"bank restructuring",
"fintech transformation",
"CEO change",
"leadership reshuffle",
"job cuts banking",
],
"priority": "medium",
"rate_limit": 2,
},
"specialist_healthcare": {
"name": "HSJ (Healthcare)",
"type": "specialist_news",
"enabled": True,
"sector": "UK Healthcare",
"base_url": "https://www.hsj.co.uk",
"search_url": "https://www.hsj.co.uk/search",
"keywords": [
"NHS transformation",
"trust restructuring",
"leadership change",
"workforce strategy",
"ICS transformation",
],
"priority": "medium",
"rate_limit": 2,
},
"specialist_manufacturing": {
"name": "The Manufacturer",
"type": "specialist_news",
"enabled": True,
"sector": "UK Manufacturing",
"base_url": "https://www.themanufacturer.com",
"search_url": "https://www.themanufacturer.com/?s=",
"keywords": [
"factory closure",
"restructuring",
"transformation",
"new leadership",
"workforce change",
],
"priority": "medium",
"rate_limit": 2,
},
# -------------------------------------------------------------------------
# 6. REMOTEOK - Backup Job Board (More Reliable)
# -------------------------------------------------------------------------
"remoteok_jobs": {
"name": "RemoteOK Jobs",
"type": "jobs",
"enabled": True,
"base_url": "https://remoteok.com",
"search_urls": [
"https://remoteok.com/remote-exec-jobs",
"https://remoteok.com/remote-hr-jobs",
"https://remoteok.com/remote-marketing-jobs",
"https://remoteok.com/remote-management-jobs",
],
"priority": "low", # Fallback/supplement
"rate_limit": 3,
},
}
# =============================================================================
# MISSION GENERATOR
# =============================================================================
def load_config(config_path: str = "config.yaml") -> dict:
"""Load configuration from YAML file."""
try:
with open(config_path, 'r') as f:
return yaml.safe_load(f)
except Exception as e:
print(f"Warning: Could not load config: {e}")
return {}
def get_target_companies(config: dict) -> list[str]:
"""Extract all target companies from config."""
companies = []
for sector in config.get('target_sectors', []):
companies.extend(sector.get('companies', []))
return [c for c in companies if c] # Filter empty strings
def get_target_sectors(config: dict) -> list[str]:
"""Extract sector names from config."""
return [s.get('name', '') for s in config.get('target_sectors', [])]
def generate_linkedin_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate LinkedIn job search tasks."""
tasks = []
keywords = ground.get('keywords', [])
locations = ground.get('locations', ['United Kingdom'])
rate_limit = ground.get('rate_limit', 3)
# Rotate keywords - pick a subset each day
day_of_year = datetime.now().timetuple().tm_yday
keyword_offset = (day_of_year * 3) % len(keywords)
selected_keywords = keywords[keyword_offset:keyword_offset + rate_limit]
# If we went past the end, wrap around
if len(selected_keywords) < rate_limit:
selected_keywords += keywords[:rate_limit - len(selected_keywords)]
for keyword in selected_keywords:
location = random.choice(locations)
# Build LinkedIn URL
query = keyword.replace(' ', '%20')
url = f"{ground['base_url']}?keywords={query}&location={location}&f_TPR=r86400"
tasks.append({
'id': f"linkedin_{keyword.lower().replace(' ', '_')}",
'source': 'linkedin_jobs',
'source_name': ground['name'],
'type': 'job_search',
'keyword': keyword,
'location': location,
'url': url,
'priority': ground.get('priority', 'medium'),
'method': 'scrape', # Requires browser scraping
'notes': f"Search for '{keyword}' roles in {location}",
})
return tasks
def generate_google_news_company_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate Google News search tasks for specific companies."""
tasks = []
companies = get_target_companies(config)
templates = ground.get('query_templates', [])
rate_limit = ground.get('rate_limit', 10)
# Rotate companies - pick different ones each day
day_of_week = datetime.now().weekday()
companies_per_day = max(1, len(companies) // 7 + 1)
start_idx = (day_of_week * companies_per_day) % len(companies) if companies else 0
selected_companies = companies[start_idx:start_idx + companies_per_day]
# Rotate templates
template_idx = day_of_week % len(templates) if templates else 0
selected_template = templates[template_idx] if templates else '"{company}" news'
for company in selected_companies[:rate_limit]:
query = selected_template.format(company=company)
encoded_query = query.replace(' ', '+').replace('"', '%22')
url = f"{ground['base_url']}?q={encoded_query}&hl=en-GB&gl=GB&ceid=GB:en"
tasks.append({
'id': f"gnews_company_{company.lower().replace(' ', '_')}",
'source': 'google_news_strategic',
'source_name': ground['name'],
'type': 'news_search',
'company': company,
'query': query,
'url': url,
'priority': ground.get('priority', 'high'),
'method': 'scrape',
'notes': f"Scan news for '{company}' strategic signals",
})
return tasks
def generate_google_news_sector_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate Google News search tasks for sector-wide signals."""
tasks = []
sectors = get_target_sectors(config)
templates = ground.get('query_templates', [])
rate_limit = ground.get('rate_limit', 6)
# Pick template based on day
day_of_week = datetime.now().weekday()
template_idx = day_of_week % len(templates) if templates else 0
selected_template = templates[template_idx] if templates else '"{sector}" UK news'
for sector in sectors[:rate_limit]:
# Extract key term from sector name (e.g., "UK Retail" -> "retail")
sector_term = sector.replace('UK ', '').lower()
query = selected_template.format(sector=sector_term)
encoded_query = query.replace(' ', '+').replace('"', '%22')
url = f"{ground['base_url']}?q={encoded_query}&hl=en-GB&gl=GB&ceid=GB:en"
tasks.append({
'id': f"gnews_sector_{sector_term.replace(' ', '_')}",
'source': 'google_news_sector',
'source_name': ground['name'],
'type': 'news_search',
'sector': sector,
'query': query,
'url': url,
'priority': ground.get('priority', 'medium'),
'method': 'scrape',
'notes': f"Scan for {sector} sector-wide challenges",
})
return tasks
def generate_tender_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate UK Government tender search task."""
tasks = []
# Single API task that will search multiple keywords
tasks.append({
'id': 'uk_tenders_daily',
'source': 'uk_tenders',
'source_name': ground['name'],
'type': 'tender_search',
'api_url': ground['api_url'],
'keywords': ground.get('keywords', []),
'lookback_hours': ground.get('lookback_hours', 24),
'min_value': ground.get('min_value', 50000),
'priority': ground.get('priority', 'high'),
'method': 'api',
'notes': f"Check FTS API for new tenders (last {ground.get('lookback_hours', 24)}h)",
})
return tasks
def generate_specialist_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate specialist site search tasks."""
tasks = []
sector = ground.get('sector', '')
keywords = ground.get('keywords', [])
rate_limit = ground.get('rate_limit', 2)
# Check if this sector is in our target list
target_sectors = get_target_sectors(config)
if sector and sector not in target_sectors:
return [] # Skip if sector not targeted
# Rotate keywords daily
day_of_week = datetime.now().weekday()
keyword_idx = day_of_week % len(keywords) if keywords else 0
selected_keywords = keywords[keyword_idx:keyword_idx + rate_limit]
for keyword in selected_keywords:
search_url = ground.get('search_url', ground['base_url'])
if '?' in search_url:
url = f"{search_url}&q={keyword.replace(' ', '+')}"
else:
url = f"{search_url}?q={keyword.replace(' ', '+')}"
tasks.append({
'id': f"specialist_{ground['name'].lower().replace(' ', '_')}_{keyword.replace(' ', '_')}",
'source': ground.get('name', 'specialist').lower().replace(' ', '_'),
'source_name': ground['name'],
'type': 'specialist_news',
'sector': sector,
'keyword': keyword,
'url': url,
'base_url': ground['base_url'],
'priority': ground.get('priority', 'medium'),
'method': 'scrape',
'notes': f"Check {ground['name']} for '{keyword}'",
})
return tasks
def generate_remoteok_tasks(ground: dict, config: dict) -> list[dict]:
"""Generate RemoteOK job search tasks."""
tasks = []
urls = ground.get('search_urls', [])
rate_limit = ground.get('rate_limit', 3)
for url in urls[:rate_limit]:
category = url.split('/')[-1].replace('-jobs', '').replace('remote-', '')
tasks.append({
'id': f"remoteok_{category}",
'source': 'remoteok_jobs',
'source_name': ground['name'],
'type': 'job_search',
'category': category,
'url': url,
'priority': ground.get('priority', 'low'),
'method': 'scrape',
'notes': f"Scrape RemoteOK {category} jobs",
})
return tasks
def generate_daily_missions(config_path: str = "config.yaml") -> dict:
"""
Generate the complete daily mission queue.
This function creates a structured to-do list for the scraper,
organized by hunting ground and priority.
Returns:
dict: Mission plan with tasks organized by priority and type
"""
config = load_config(config_path)
mission = {
'generated_at': datetime.now().isoformat(),
'date': datetime.now().strftime('%Y-%m-%d'),
'day_name': datetime.now().strftime('%A'),
'total_tasks': 0,
'tasks_by_priority': {
'high': [],
'medium': [],
'low': [],
},
'tasks_by_type': {
'job_search': [],
'news_search': [],
'tender_search': [],
'specialist_news': [],
},
'all_tasks': [],
'hunting_grounds_used': [],
'summary': {},
}
# Process each hunting ground
for ground_id, ground in HUNTING_GROUNDS.items():
if not ground.get('enabled', True):
continue
tasks = []
ground_type = ground.get('type', '')
# Generate tasks based on ground type
if ground_id == 'linkedin_jobs':
tasks = generate_linkedin_tasks(ground, config)
elif ground_id == 'google_news_strategic':
tasks = generate_google_news_company_tasks(ground, config)
elif ground_id == 'google_news_sector':
tasks = generate_google_news_sector_tasks(ground, config)
elif ground_id == 'uk_tenders':
tasks = generate_tender_tasks(ground, config)
elif ground_id == 'remoteok_jobs':
tasks = generate_remoteok_tasks(ground, config)
elif ground_type == 'specialist_news':
tasks = generate_specialist_tasks(ground, config)
if tasks:
mission['hunting_grounds_used'].append(ground['name'])
for task in tasks:
priority = task.get('priority', 'medium')
task_type = task.get('type', 'other')
mission['tasks_by_priority'][priority].append(task)
if task_type in mission['tasks_by_type']:
mission['tasks_by_type'][task_type].append(task)
mission['all_tasks'].append(task)
# Calculate totals
mission['total_tasks'] = len(mission['all_tasks'])
mission['summary'] = {
'high_priority': len(mission['tasks_by_priority']['high']),
'medium_priority': len(mission['tasks_by_priority']['medium']),
'low_priority': len(mission['tasks_by_priority']['low']),
'job_searches': len(mission['tasks_by_type']['job_search']),
'news_searches': len(mission['tasks_by_type']['news_search']),
'tender_searches': len(mission['tasks_by_type']['tender_search']),
'specialist_news': len(mission['tasks_by_type']['specialist_news']),
'hunting_grounds': len(mission['hunting_grounds_used']),
}
return mission
def print_mission_briefing(mission: dict) -> str:
"""Generate a formatted briefing of the day's missions."""
lines = []
lines.append("=" * 70)
lines.append(f"🎯 DAILY MISSION BRIEFING - {mission['day_name'].upper()} {mission['date']}")
lines.append("=" * 70)
lines.append(f"Generated: {mission['generated_at']}")
lines.append("")
# Summary
s = mission['summary']
lines.append("πŸ“Š MISSION SUMMARY")
lines.append("-" * 40)
lines.append(f" Total Tasks: {mission['total_tasks']}")
lines.append(f" πŸ”΄ High Priority: {s['high_priority']}")
lines.append(f" 🟑 Medium Priority: {s['medium_priority']}")
lines.append(f" 🟒 Low Priority: {s['low_priority']}")
lines.append("")
lines.append(f" πŸ’Ό Job Searches: {s['job_searches']}")
lines.append(f" πŸ“° News Searches: {s['news_searches']}")
lines.append(f" πŸ›οΈ Tender Checks: {s['tender_searches']}")
lines.append(f" πŸ” Specialist Sites: {s['specialist_news']}")
lines.append("")
# Hunting Grounds
lines.append("🎯 HUNTING GROUNDS ACTIVE")
lines.append("-" * 40)
for ground in mission['hunting_grounds_used']:
lines.append(f" βœ“ {ground}")
lines.append("")
# High Priority Tasks
if mission['tasks_by_priority']['high']:
lines.append("πŸ”΄ HIGH PRIORITY TASKS")
lines.append("-" * 40)
for i, task in enumerate(mission['tasks_by_priority']['high'], 1):
lines.append(f" {i}. [{task['source_name']}] {task['notes']}")
lines.append("")
# Medium Priority Tasks
if mission['tasks_by_priority']['medium']:
lines.append("🟑 MEDIUM PRIORITY TASKS")
lines.append("-" * 40)
for i, task in enumerate(mission['tasks_by_priority']['medium'], 1):
lines.append(f" {i}. [{task['source_name']}] {task['notes']}")
lines.append("")
# Low Priority Tasks
if mission['tasks_by_priority']['low']:
lines.append("🟒 LOW PRIORITY TASKS")
lines.append("-" * 40)
for i, task in enumerate(mission['tasks_by_priority']['low'], 1):
lines.append(f" {i}. [{task['source_name']}] {task['notes']}")
lines.append("")
lines.append("=" * 70)
lines.append("End of Briefing")
lines.append("=" * 70)
return "\n".join(lines)
def get_tasks_for_execution(mission: dict, priority_filter: str = None) -> list[dict]:
"""
Get tasks ready for execution, optionally filtered by priority.
Args:
mission: The mission dict from generate_daily_missions()
priority_filter: 'high', 'medium', 'low', or None for all
Returns:
List of task dicts ordered by priority (high first)
"""
if priority_filter:
return mission['tasks_by_priority'].get(priority_filter, [])
# Return all tasks, high priority first
tasks = []
tasks.extend(mission['tasks_by_priority']['high'])
tasks.extend(mission['tasks_by_priority']['medium'])
tasks.extend(mission['tasks_by_priority']['low'])
return tasks
# =============================================================================
# CLI INTERFACE
# =============================================================================
if __name__ == "__main__":
import argparse
import json
parser = argparse.ArgumentParser(description='Generate daily hunting missions')
parser.add_argument('--json', action='store_true', help='Output as JSON')
parser.add_argument('--priority', choices=['high', 'medium', 'low'], help='Filter by priority')
parser.add_argument('--type', choices=['job_search', 'news_search', 'tender_search', 'specialist_news'],
help='Filter by task type')
args = parser.parse_args()
# Generate missions
mission = generate_daily_missions()
if args.json:
# Output as JSON
if args.priority:
print(json.dumps(mission['tasks_by_priority'][args.priority], indent=2))
elif args.type:
print(json.dumps(mission['tasks_by_type'].get(args.type, []), indent=2))
else:
print(json.dumps(mission, indent=2))
else:
# Output formatted briefing
print(print_mission_briefing(mission))
if args.priority or args.type:
print("\n" + "=" * 70)
print("FILTERED TASKS:")
print("-" * 70)
if args.priority:
tasks = mission['tasks_by_priority'][args.priority]
elif args.type:
tasks = mission['tasks_by_type'].get(args.type, [])
for task in tasks:
print(f"\nTask: {task['id']}")
print(f" Source: {task['source_name']}")
print(f" URL: {task.get('url', 'N/A')}")
print(f" Method: {task.get('method', 'unknown')}")
print(f" Notes: {task.get('notes', '')}")