Spaces:
Configuration error
Configuration error
File size: 10,360 Bytes
e23172f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | #!/usr/bin/env python3
"""AI Lead Generation Agent - Main Orchestrator"""
import asyncio
import json
import os
import sys
from datetime import datetime
from typing import Dict, List, Optional
from dataclasses import dataclass, asdict
import sqlite3
# Lead scoring system
@dataclass
class LeadFeatures:
company: str
job_title: str
industry: str
revenue: Optional[str] = None
employees: Optional[int] = None
tech_stack: List[str] = None
engagement: Dict = None
def __post_init__(self):
if self.tech_stack is None:
self.tech_stack = []
if self.engagement is None:
self.engagement = {}
class LeadScorer:
"""AI-powered lead scoring engine"""
WEIGHTS = {
"job_seniority": 0.25,
"company_size": 0.20,
"digital_footprint": 0.15,
"engagement_velocity": 0.15,
"industry_fit": 0.10,
"historical_signals": 0.15
}
HIGH_VALUE_TITLES = ['CEO', 'CTO', 'CMO', 'VP', 'Director', 'Head', 'Founder']
TARGET_INDUSTRIES = ['SaaS', 'Technology', 'Software', 'E-commerce', 'Healthcare', 'Finance', 'Construction', 'Professional Services']
def score_job_seniority(self, title: str) -> float:
title_upper = title.upper()
if any(t in title_upper for t in self.HIGH_VALUE_TITLES):
return 1.0
return 0.5
def score_company_size(self, revenue: Optional[str], employees: Optional[int]) -> float:
if revenue:
try:
rev = float(revenue.replace('$', '').replace(',', ''))
if rev >= 10000000:
return 1.0
elif rev >= 1000000:
return 0.8
elif rev >= 100000:
return 0.6
except:
pass
if employees:
if employees >= 500:
return 1.0
elif employees >= 50:
return 0.7
elif employees >= 10:
return 0.4
return 0.2
def score_digital_footprint(self, tech_stack: List[str]) -> float:
known_tools = {'hubspot', 'salesforce', 'outreach', 'apollo', 'phantombuster', 'clearbit', 'hunter', 'linkedin'}
matches = sum(1 for t in tech_stack if any(k in t.lower() for k in known_tools))
return min(1.0, matches * 0.25 + 0.3)
def score_engagement(self, engagement: Dict) -> float:
score = 0
score += engagement.get('website_visits', 0) * 0.2
score += engagement.get('email_opens', 0) * 0.15
score += engagement.get('page_views', 0) * 0.1
score += engagement.get('content_downloads', 0) * 0.25
return min(1.0, score)
def score_industry(self, industry: str) -> float:
industry_lower = industry.lower()
matches = sum(1 for t in self.TARGET_INDUSTRIES if t.lower() in industry_lower)
return min(1.0, matches * 0.2)
def calculate(self, lead: LeadFeatures) -> int:
"""Calculate total lead score 0-100"""
job_score = self.score_job_seniority(lead.job_title)
company_score = self.score_company_size(lead.revenue, lead.employees)
digital_score = self.score_digital_footprint(lead.tech_stack)
engagement_score = self.score_engagement(lead.engagement)
industry_score = self.score_industry(lead.industry)
total = (
job_score * self.WEIGHTS['job_seniority'] +
company_score * self.WEIGHTS['company_size'] +
digital_score * self.WEIGHTS['digital_footprint'] +
engagement_score * self.WEIGHTS['engagement_velocity'] +
industry_score * self.WEIGHTS['industry_fit'] +
0.5 * self.WEIGHTS['historical_signals'] # Default historical
) * 100
return round(max(0, min(100, total)))
def get_priority(self, score: int) -> str:
if score >= 85:
return "immediate"
elif score >= 70:
return "high"
elif score >= 50:
return "medium"
return "low"
class PersonalizationEngine:
"""Generate personalized outreach content"""
TEMPLATES = {
"email_subject": [
"{company}'s {job_title} deserves better results",
"3 ideas for {company} from AI Lead Gen",
"Quick win for {company}'s lead pipeline?",
"{job_title} at {company} - relevant insights"
],
"email_body": """
Hi {first_name},
I noticed {company} is working on {topic}. Many teams struggle with {pain_point}, especially when dealing with {industry_specific}.
Our AI system helped {similar_company} increase qualified leads by 340% in 90 days. The approach:
1. **{step1}** - Identifies high-intent signals
2. **{step2}** - Delivers personalized outreach
3. **{step3}** - Optimizes in real-time
Would you be open to a 15-minute conversation this week?
Best,
{your_name}
""",
"linkedin_message": """
Hi {first_name},
Saw your profile and thought you might be interested in how AI is transforming lead generation for {industry} companies.
Happy to share a relevant case study if you're open to it.
Best,
{your_name}
"""
}
def personalize_email(self, lead: LeadFeatures) -> Dict:
import random
first_name = lead.company.split()[0] if lead.company else "there"
topics = {
'SaaS': 'scaling faster',
'Technology': 'product adoption',
'Healthcare': 'patient acquisition',
'Finance': 'client onboarding',
'E-commerce': 'revenue growth',
'Construction': 'project leads',
'default': 'results'
}
topic = topics.get(lead.industry, topics['default'])
pain_points = {
'SaaS': 'manual lead qualification',
'Technology': 'sales cycle length',
'Healthcare': 'patient scheduling',
'Finance': 'client retention',
'E-commerce': 'customer acquisition cost',
'Construction': 'project pipeline',
'default': 'lead quality'
}
pain_point = pain_points.get(lead.industry, pain_points['default'])
return {
"subject": random.choice(self.TEMPLATES['email_subject']).format(
company=lead.company,
job_title=lead.job_title,
first_name=first_name
),
"body": self.TEMPLATES['email_body'].format(
first_name=first_name,
company=lead.company,
topic=topic,
pain_point=pain_point,
industry_specific=lead.industry.lower(),
similar_company="a similar company",
step1="Predictive scoring",
step2="Personalized sequences",
step3="Performance analytics",
your_name="Your Lead Gen AI"
)
}
class CampaignExecutor:
"""Execute automated campaigns"""
def __init__(self, db_path: str = "leads.db"):
self.db_path = db_path
self._init_db()
def _init_db(self):
conn = sqlite3.connect(self.db_path)
conn.execute('''CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY,
company TEXT,
job_title TEXT,
industry TEXT,
score INTEGER,
priority TEXT,
status TEXT DEFAULT 'new',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
conn.execute('''CREATE TABLE IF NOT EXISTS outreach_log (
id INTEGER PRIMARY KEY,
lead_id INTEGER,
channel TEXT,
content TEXT,
sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
engagement INTEGER DEFAULT 0
)''')
conn.commit()
conn.close()
async def process_leads_batch(leads_data: List[Dict]) -> List[Dict]:
"""Process batch of leads"""
scorer = LeadScorer()
engine = PersonalizationEngine()
results = []
for lead_dict in leads_data:
lead = LeadFeatures(
company=lead_dict.get('company', ''),
job_title=lead_dict.get('job_title', ''),
industry=lead_dict.get('industry', ''),
revenue=lead_dict.get('revenue'),
employees=lead_dict.get('employees'),
tech_stack=lead_dict.get('tech_stack', []),
engagement=lead_dict.get('engagement', {})
)
score = scorer.calculate(lead)
priority = scorer.get_priority(score)
personalized = engine.personalize_email(lead)
results.append({
"lead": {"company": lead.company, "job_title": lead.job_title},
"score": score,
"priority": priority,
"next_action": "Send email" if score > 50 else "Monitor",
"email": personalized
})
return results
async def main():
"""Demo execution"""
sample_leads = [
{
"company": "TechStart Inc",
"job_title": "Marketing Director",
"industry": "SaaS",
"revenue": "$25000000",
"tech_stack": ["HubSpot", "Loom", "Zoom"],
"engagement": {"website_visits": 5, "email_opens": 3}
},
{
"company": "MediCare Hospital",
"job_title": "CTO",
"industry": "Healthcare",
"revenue": "$150000000",
"tech_stack": ["Epic", "Cerner", "Salesforce"],
"engagement": {"website_visits": 12, "content_downloads": 2}
},
{
"company": "Local Bakery",
"job_title": "Owner",
"industry": "Food & Beverage",
"employees": 15,
"engagement": {"website_visits": 1}
}
]
print("🚀 AI Lead Generation Processing...")
print("=" * 50)
results = await process_leads_batch(sample_leads)
for r in results:
print(f"\n{r['lead']['company']} - {r['lead']['job_title']}")
print(f" Score: {r['score']} | Priority: {r['priority']} | Action: {r['next_action']}")
print("\n✅ Complete - processed", len(results), "leads")
if __name__ == "__main__":
asyncio.run(main()) |