File size: 5,397 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
#!/usr/bin/env python3
"""Main FastAPI application for AI Lead Generation Agency"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
import json

app = FastAPI(
    title="AI Lead Generation Agency API",
    version="1.0.0",
    description="Generate, score, and nurture B2B leads with AI"
)

# Import scoring components
import sys
sys.path.insert(0, '/home/brettanthonysjoberg179/trifecta-bro-hf-space/scripts')

# Models
class LeadInput(BaseModel):
    company: str
    job_title: str
    industry: str
    revenue: Optional[str] = None
    employees: Optional[int] = None
    tech_stack: List[str] = Field(default_factory=list)
    engagement: dict = Field(default_factory=dict)


class ScoreResponse(BaseModel):
    company: str
    job_title: str
    lead_score: int
    priority: str
    confidence: str
    next_action: str
    estimated_value: Optional[str] = None


# In-memory storage (use DB in production)
_lead_storage = {}


@app.get("/")
async def root():
    return {
        "agency": "AI Lead Generation",
        "version": "1.0.0",
        "endpoints": [
            "/api/v1/leads/score",
            "/api/v1/leads/process",
            "/api/v1/campaigns/run"
        ]
    }


@app.post("/api/v1/leads/score", response_model=ScoreResponse)
async def score_lead(lead: LeadInput):
    """Score a single lead and return priority level"""
    
    # Simple scoring logic
    score = 0
    
    # Job title bonus
    senior_titles = ['CEO', 'CTO', 'CMO', 'VP', 'Director', 'Head', 'Founder']
    if any(t in lead.job_title.upper() for t in senior_titles):
        score += 25
    
    # Company size bonus
    if lead.revenue:
        try:
            rev = float(lead.revenue.replace('$', '').replace(',', ''))
            if rev >= 10000000:
                score += 20
            elif rev >= 1000000:
                score += 15
        except:
            pass
    
    if lead.employees and lead.employees >= 50:
        score += 15
    
    # Engagement bonus
    eng = lead.engagement.get('website_visits', 0)
    if eng >= 10:
        score += 20
    elif eng >= 5:
        score += 10
    
    # Tech stack bonus
    if lead.tech_stack:
        score += min(15, len(lead.tech_stack) * 3)
    
    # Industry bonus
    target_industries = ['SaaS', 'Technology', 'Software', 'Healthcare', 'Finance', 'E-commerce']
    if any(i in lead.industry for i in target_industries):
        score += 20
    
    # Priority determination
    if score >= 80:
        priority = "immediate"
        next_action = "Schedule immediate outreach"
        confidence = "high"
    elif score >= 65:
        priority = "high"
        next_action = "Send personalized sequence"
        confidence = "medium-high"
    elif score >= 50:
        priority = "medium"
        next_action = "Add to nurture campaign"
        confidence = "medium"
    else:
        priority = "low"
        next_action = "Monitor for engagement signals"
        confidence = "low"
    
    # Store for history
    _lead_storage[lead.company] = {
        "score": score,
        "priority": priority,
        "timestamp": datetime.utcnow().isoformat()
    }
    
    return ScoreResponse(
        company=lead.company,
        job_title=lead.job_title,
        lead_score=score,
        priority=priority,
        confidence=confidence,
        next_action=next_action
    )


@app.post("/api/v1/leads/process")
async def process_leads(leads: List[LeadInput]):
    """Process multiple leads at once"""
    results = []
    
    for lead in leads:
        result = await score_lead(lead)
        results.append(result.dict())
    
    return {
        "total": len(results),
        "by_priority": {
            "immediate": len([r for r in results if r['priority'] == 'immediate']),
            "high": len([r for r in results if r['priority'] == 'high']),
            "medium": len([r for r in results if r['priority'] == 'medium']),
            "low": len([r for r in results if r['priority'] == 'low'])
        },
        "leads": results
    }


@app.post("/api/v1/campaigns/run")
async def run_campaign(
    target_industry: str,
    budget: float = 1000,
    channels: List[str] = ["email", "linkedin"]
):
    """Run a lead generation campaign"""
    
    # Estimate leads based on industry and budget
    leads_per_dollar = {
        "SaaS": 0.15,
        "Healthcare": 0.12,
        "Finance": 0.18,
        "E-commerce": 0.20,
        "Technology": 0.25,
        "default": 0.10
    }
    
    multiplier = leads_per_dollar.get(target_industry, leads_per_dollar['default'])
    estimated_leads = int(budget * multiplier)
    
    return {
        "campaign": {
            "target_industry": target_industry,
            "budget": budget,
            "channels": channels
        },
        "forecast": {
            "estimated_leads": estimated_leads,
            "expected_meetings": max(1, estimated_leads // 25),
            "expected_revenue": budget * 5,
            "agency_take_rate": 0.20
        }
    }


@app.get("/api/v1/health")
async def health_check():
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "leads_processed": len(_lead_storage)
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)