Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/AI_Brain / services/seeder_api/intelligence.py |
| Date | Not specified in source |
| Repository | Janady13/AI_Brain |
| Revision | 366ab848896ae49159cfb3f6c201b8c5a731e9c8 |
| Branch | codex/build-online-github-ani-hr4y0z |
| Path or archive member | services/seeder_api/intelligence.py |
| Original SHA-256 | f7540cd2def861863d0bb263a48f96f5e57f10e0d353d3db1d77781e072172e3 |
| Git blob SHA | 3b3347a5baef1872934053f5e35620c16f713e05 |
| Reading-copy SHA-256 | 93af525a50b7bc69a544bdacf110aafecf1892817b3b991ca7962c0aa99c50c9 |
Every recorded occurrence
These 7 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-hr4y0z | 366ab848896ae49159cfb3f6c201b8c5a731e9c8 | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-i3cigl | 3a6e002311c48c27ffd41ef4a2a31c63947128cd | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-jf5olo | c6653627c453ab428d665226167fa5f4aa05e9a5 | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-7nmb21 | d0f50071c85cddaaebbf9c4dd1313bd7676986da | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-hr4y0z | 366ab848896ae49159cfb3f6c201b8c5a731e9c8 | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-i3cigl | 3a6e002311c48c27ffd41ef4a2a31c63947128cd | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-jf5olo | c6653627c453ab428d665226167fa5f4aa05e9a5 | Open original |
Recovered source transcript
Download complete source text ↓4,340 lines · 162.2 KB
Credential-bearing and unrelated personal details were removed from this reading copy. The source identity and original checksum remain recorded.
"""Marketing intelligence engine that ranks and scores enumerated campaigns."""
from __future__ import annotations
import base64
import importlib
import json
import os
import re
from dataclasses import dataclass
from functools import lru_cache
from statistics import mean
from typing import Any, Dict, List, Sequence, Tuple
try: # pragma: no cover - optional dependency that may not be installed in tests
from google.ads.googleads.client import GoogleAdsClient # type: ignore
except ImportError: # pragma: no cover - gracefully handled when SDK missing
GoogleAdsClient = None # type: ignore
try: # pragma: no cover - optional dependency that may not be installed in tests
from google.oauth2 import service_account # type: ignore
except ImportError: # pragma: no cover - gracefully handled when SDK missing
service_account = None # type: ignore
try: # pragma: no cover - optional dependency that may not be installed in tests
import stripe # type: ignore
except ImportError: # pragma: no cover - gracefully handled when SDK missing
stripe = None # type: ignore
try: # pragma: no cover - optional dependency that may not be installed in tests
from paypalcheckoutsdk.core import ( # type: ignore
PayPalHttpClient,
LiveEnvironment,
SandboxEnvironment,
)
except ImportError: # pragma: no cover - gracefully handled when SDK missing
PayPalHttpClient = None # type: ignore
LiveEnvironment = None # type: ignore
SandboxEnvironment = None # type: ignore
try: # pragma: no cover - optional dependency for AWS integrations
import boto3 # type: ignore
except ImportError: # pragma: no cover - gracefully handled when SDK missing
boto3 = None # type: ignore
MARKETING_ENUMERATION = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "enumerations", "marketing_500.txt"
)
MARKETING_BENCHMARKS = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "marketing_benchmarks.json"
)
CJ_OFFERS_DATASET = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "cj_offers.json"
)
AMAZON_MARKETPLACE_DATASET = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "amazon_marketplace.json"
)
EBAY_MARKETPLACE_DATASET = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "ebay_marketplace.json"
)
AWS_GROWTH_PLAYBOOKS = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "aws_growth_playbooks.json"
)
CHANNEL_INVESTMENTS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"channel_investments.json",
)
AUTOMATION_SPRINTS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"automation_sprints.json",
)
PERFORMANCE_MEMORY_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"performance_memory.json",
)
COMPETITIVE_LANDSCAPE_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"competitive_landscape.json",
)
INFLUENCER_PARTNERS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"influencer_partners.json",
)
AWS_GROWTH_PLAYBOOKS = os.path.join(
os.path.dirname(__file__), "..", "..", "daemon", "datasets", "aws_growth_playbooks.json"
)
requests_spec = importlib.util.find_spec("requests")
requests = importlib.import_module("requests") if requests_spec else None
def _load_lines(path: str) -> List[str]:
with open(path, "r", encoding="utf-8") as handle:
return [line.strip() for line in handle if line.strip()]
@dataclass(slots=True)
class MarketingCampaign:
"""Structured representation for one marketing campaign idea."""
raw: str
channel: str
audience: str
offer: str
objective: str
@classmethod
def parse(cls, raw: str) -> "MarketingCampaign":
text = raw.strip().rstrip(".")
if not text.lower().startswith("campaign:"):
raise ValueError(f"Unsupported campaign format: {raw}")
body = text[len("Campaign:") :].strip()
try:
channel, remainder = body.split("targeting", 1)
audience, remainder = remainder.split("leveraging", 1)
offer, objective = remainder.split(" to ", 1)
except ValueError as exc: # pragma: no cover - enumeration should be well formed
raise ValueError(f"Malformed campaign sentence: {raw}") from exc
return cls(
raw=raw,
channel=channel.strip(),
audience=audience.strip(),
offer=offer.strip(),
objective=objective.strip().rstrip("."),
)
@dataclass(slots=True)
class CampaignMetrics:
"""Statistical expectations for a marketing campaign."""
expected_roi: float
expected_ctr: float
confidence: float
drivers: Dict[str, float]
@dataclass(slots=True)
class BudgetProfile:
"""Baseline investment expectations for a marketing channel."""
channel: str
keywords: List[str]
baseline_cpc: float
baseline_cpl: float
avg_conversion_rate: float
avg_roi: float
recommended_monthly_spend: float
@dataclass(slots=True)
class BudgetAllocation:
"""Recommended allocation for a marketing campaign channel."""
channel: str
audience_focus: str
offer: str
objective: str
allocation_usd: float
allocation_weight: float
expected_leads: float
expected_revenue: float
rationale: str
source: str
notes: str | None = None
@dataclass(slots=True)
class BudgetPlan:
"""Portfolio-level budget recommendation summary."""
total_budget: float
allocations: List[BudgetAllocation]
expected_revenue: float
expected_roi: float
payback_period_weeks: float
summary: str
@dataclass(slots=True)
class AutomationTask:
"""Time-boxed task within an automation sprint."""
start_minute: int
end_minute: int
activity: str
outcome: str
tooling: List[str]
kpis: List[str]
automation_level: str
source: str
@dataclass(slots=True)
class AutomationSprint:
"""Three-hour automation run composed of sequential tasks."""
total_minutes: int
stage: str
focus: str
summary: str
tasks: List[AutomationTask]
notes: str | None = None
source: str = "automation_playbooks"
@dataclass(slots=True)
class PerformanceMemoryEntry:
"""Historical marketing learning captured from closed-loop experiments."""
play_name: str
stage: str
audience_focus: str
channel: str
tags: List[str]
summary: str
wins: List[str]
losses: List[str]
next_actions: List[str]
kpi_focus: List[str]
confidence: float
source: str = "performance_memory"
notes: str | None = None
@dataclass(slots=True)
class LearningLoopRecommendation:
"""Actionable recommendation generated from the learning memory."""
play_name: str
stage: str
audience_focus: str
channel: str
learning: str
wins: List[str]
losses: List[str]
next_actions: List[str]
kpi_focus: List[str]
confidence: float
source: str
notes: str | None = None
@dataclass(slots=True)
class ExcellenceSummary:
"""Composite readiness score describing how robust the ANI recommendations are."""
excellence_index: float
maturity_level: str
headline: str
strengths: List[str]
watchouts: List[str]
process_coverage: Dict[str, float]
notes: str | None = None
@dataclass(slots=True)
class StrategicDirective:
"""Directive that fuses multiple process signals into a prioritized motion."""
name: str
priority: int
objective: str
primary_channel: str
supporting_channels: List[str]
investment_usd: float | None
expected_revenue_usd: float | None
confidence: float
time_horizon_hours: int
north_star_metric: str
supporting_metrics: List[str]
action_steps: List[str]
dependencies: List[str]
risk_mitigations: List[str]
inspiration: str
source: str = "ani_orchestration"
notes: str | None = None
@dataclass(slots=True)
class ExecutivePlaybook:
"""Cross-process action plan that guides autonomous execution."""
headline: str
focus: str
urgency: str
north_star_metric: str
total_budget_usd: float | None
expected_revenue_usd: float | None
confidence: float
directives: List[StrategicDirective]
summary: str
notes: str | None = None
@dataclass(slots=True)
class ScenarioProjection:
"""Scenario-level forecast for autonomous marketing execution."""
scenario: str
expected_revenue: float
expected_roi: float
probability: float
confidence: float
accelerators: List[str]
stabilizers: List[str]
watchouts: List[str]
source: str = "scenario_planner"
notes: str | None = None
@dataclass(slots=True)
class ScenarioAnalysis:
"""Aggregated scenario planning summary."""
headline: str
summary: str
projections: List[ScenarioProjection]
confidence: float
accelerators: List[str]
stabilizers: List[str]
source: str = "scenario_planner"
notes: str | None = None
class ScenarioPlanningProcess:
"""Synthesizes optimistic, base, and conservative revenue scenarios."""
def __init__(self, volatility_floor: float = 0.15) -> None:
self._volatility_floor = volatility_floor
def _estimate_budget(
self, diagnostics: PromptDiagnostics, campaigns: Sequence[CampaignScore]
) -> float:
stage_baseline = {
"awareness": 18000.0,
"consideration": 22000.0,
"conversion": 28000.0,
"retention": 20000.0,
}
base = stage_baseline.get(diagnostics.stage, 22000.0)
focus = diagnostics.focus.lower()
if "enterprise" in focus:
base *= 1.45
elif "startup" in focus:
base *= 0.9
elif "consumer" in focus:
base *= 0.8
if diagnostics.urgency == "urgent":
base *= 1.25
elif diagnostics.urgency == "time-sensitive":
base *= 1.1
avg_roi = mean(score.metrics.expected_roi for score in campaigns)
base *= max(0.8, min(1.6, avg_roi / 2.0))
return round(max(7500.0, base), 2)
@staticmethod
def _signal_accelerators(
google_ads: Sequence[GoogleCampaignPerformance] | None,
cj_affiliate: Sequence[CJAffiliateRecommendation] | None,
amazon: Sequence[AmazonProductRecommendation] | None,
ebay: Sequence[EbayRevenuePlay] | None,
aws: Sequence[AWSRevenueRecommendation] | None,
stripe: Sequence[StripeMonetizationPlan] | None,
paypal: Sequence[PayPalMonetizationPlan] | None,
influencers: Sequence[InfluencerRecommendation] | None,
) -> List[str]:
accelerators: List[str] = []
if google_ads:
roas = mean(perf.roas for perf in google_ads)
if roas >= 3.5:
accelerators.append(f"Google Ads ROAS averaging {roas:.2f}x supports paid scale")
if cj_affiliate:
revenue = mean(rec.projected_monthly_revenue for rec in cj_affiliate)
if revenue > 15000:
accelerators.append(
f"CJ affiliate programs forecast ${revenue:,.0f} monthly expansion"
)
if amazon:
conversion = mean(rec.rating for rec in amazon)
if conversion >= 4.2:
accelerators.append("Amazon marketplace sentiment reinforces conversion confidence")
if ebay:
margin = mean(play.projected_profit_margin for play in ebay)
velocity = mean(play.sold_per_month for play in ebay)
if margin >= 0.25 and velocity >= 100:
accelerators.append(
"eBay partner inventory blends high-margin payouts with rapid sell-through"
)
if aws:
roi = mean(rec.projected_roi for rec in aws)
if roi >= 2.5:
accelerators.append("AWS growth plays carry multi-service ROI leverage")
if stripe:
price = mean(plan.price_usd for plan in stripe)
if price >= 99:
accelerators.append("Stripe monetization supports premium pricing uplift")
if paypal:
payout_focus = {plan.payout_schedule for plan in paypal}
if "daily" in payout_focus:
accelerators.append("PayPal payouts unlocked daily revenue capture velocity")
elif paypal:
accelerators.append("PayPal commerce streamlines cashflow-ready offers")
if influencers:
avg_roi = mean(rec.projected_roi for rec in influencers)
avg_reach = mean(rec.estimated_reach for rec in influencers)
if avg_roi >= 4.0:
accelerators.append(
f"Influencer partnerships forecast {avg_roi:.1f}x ROI with amplified reach"
)
elif avg_reach >= 5000:
accelerators.append(
f"Influencer partners extend campaigns to {avg_reach:,.0f}+ engaged prospects"
)
return accelerators
@staticmethod
def _stabilizers(diagnostics: PromptDiagnostics, budget: BudgetPlan | None) -> List[str]:
stabilizers: List[str] = []
if diagnostics.recommended_kpis:
stabilizers.append(f"Instrument KPI guardrails around {diagnostics.recommended_kpis[0]}")
if budget and budget.allocations:
top_channel = budget.allocations[0].channel
stabilizers.append(f"Phase spend across {top_channel} with weekly optimization cycles")
return stabilizers
def analyze(
self,
prompt: str,
diagnostics: PromptDiagnostics,
campaigns: Sequence[CampaignScore],
*,
budget: BudgetPlan | None,
google_ads: Sequence[GoogleCampaignPerformance] | None,
cj_affiliate: Sequence[CJAffiliateRecommendation] | None,
amazon: Sequence[AmazonProductRecommendation] | None,
ebay: Sequence[EbayRevenuePlay] | None,
aws: Sequence[AWSRevenueRecommendation] | None,
stripe: Sequence[StripeMonetizationPlan] | None,
paypal: Sequence[PayPalMonetizationPlan] | None,
crypto: Sequence[CryptoMarketSnapshot] | None,
influencers: Sequence[InfluencerRecommendation] | None,
limit: int = 3,
) -> ScenarioAnalysis:
if not campaigns:
raise ValueError("Scenario planning requires campaign scores")
top = list(campaigns[: max(1, limit)])
avg_roi = mean(score.metrics.expected_roi for score in top)
avg_confidence = mean(score.metrics.confidence for score in top)
avg_ctr = mean(score.metrics.expected_ctr for score in top)
base_budget = (
budget.total_budget if budget and budget.total_budget > 0 else self._estimate_budget(diagnostics, top)
)
base_revenue = (
budget.expected_revenue
if budget and budget.expected_revenue > 0
else round(base_budget * max(1.1, avg_roi), 2)
)
base_roi = round(base_revenue / base_budget, 2) if base_budget else round(avg_roi, 2)
volatility = self._volatility_floor
if diagnostics.urgency == "urgent":
volatility += 0.1
elif diagnostics.urgency == "time-sensitive":
volatility += 0.05
if diagnostics.risk_signals:
volatility += 0.08
if crypto and any(snapshot.change_24h and abs(snapshot.change_24h) > 5 for snapshot in crypto):
volatility += 0.05
volatility = min(0.5, max(self._volatility_floor, volatility))
optimistic_multiplier = 1 + volatility
conservative_multiplier = max(0.45, 1 - volatility)
optimistic_revenue = round(base_revenue * optimistic_multiplier, 2)
conservative_revenue = round(base_revenue * conservative_multiplier, 2)
optimistic_roi = round(base_roi * (1 + volatility / 1.5), 2)
conservative_roi = round(base_roi * (1 - volatility / 1.2), 2)
optimistic_conf = min(0.99, avg_confidence + (0.12 - volatility / 2))
base_conf = min(0.95, max(0.25, avg_confidence))
conservative_conf = max(0.2, avg_confidence - volatility / 2)
optimistic_prob = max(0.18, 0.32 - (volatility - self._volatility_floor) * 0.6)
conservative_prob = max(0.22, 0.28 + (volatility - self._volatility_floor) * 0.5)
base_prob = max(0.3, 1.0 - optimistic_prob - conservative_prob)
total = optimistic_prob + base_prob + conservative_prob
optimistic_prob = round(optimistic_prob / total, 2)
base_prob = round(base_prob / total, 2)
conservative_prob = round(conservative_prob / total, 2)
accelerators = self._signal_accelerators(
google_ads, cj_affiliate, amazon, ebay, aws, stripe, paypal, influencers
)
stabilizers = self._stabilizers(diagnostics, budget)
if avg_ctr > 0.6:
accelerators.append("Benchmark CTR momentum indicates creative resonance")
if len(accelerators) < 2:
accelerators.append("Cross-process enrichment unlocks multi-channel leverage")
if not stabilizers:
stabilizers.append("Institute weekly analytics reviews to course-correct")
risk_watchouts = diagnostics.risk_signals[:2]
if not risk_watchouts:
risk_watchouts = ["Monitor acquisition efficiency as spend scales"]
projections = [
ScenarioProjection(
scenario="optimistic",
expected_revenue=optimistic_revenue,
expected_roi=optimistic_roi,
probability=optimistic_prob,
confidence=round(optimistic_conf, 2),
accelerators=accelerators,
stabilizers=stabilizers,
watchouts=["Ensure fulfillment capacity scales with demand"],
),
ScenarioProjection(
scenario="base",
expected_revenue=round(base_revenue, 2),
expected_roi=round(base_roi, 2),
probability=base_prob,
confidence=round(base_conf, 2),
accelerators=accelerators,
stabilizers=stabilizers,
watchouts=risk_watchouts,
),
ScenarioProjection(
scenario="conservative",
expected_revenue=conservative_revenue,
expected_roi=round(conservative_roi, 2),
probability=round(conservative_prob, 2),
confidence=round(conservative_conf, 2),
accelerators=accelerators,
stabilizers=stabilizers,
watchouts=["Reserve contingency budget to reallocate into proven channels"],
),
]
primary_channels = {score.campaign.channel for score in top[:2]}
summary = (
f"Model optimistic, base, and conservative revenue trajectories for {diagnostics.stage} "
f"outcomes targeting {diagnostics.focus}."
)
headline = (
f"Scenario coverage for {', '.join(sorted(primary_channels))} anchored in {diagnostics.focus}."
)
notes = (
f"Volatility factor {volatility:.2f} derives from urgency={diagnostics.urgency} and risk signals"
)
return ScenarioAnalysis(
headline=headline,
summary=summary,
projections=projections,
confidence=round(base_conf, 2),
accelerators=accelerators,
stabilizers=stabilizers,
notes=notes,
)
class PerformanceMemory:
"""Loads and scores historical marketing learnings."""
def __init__(self, entries: Sequence[PerformanceMemoryEntry]):
if not entries:
raise ValueError("PerformanceMemory requires at least one entry")
self._entries = list(entries)
@classmethod
def from_file(cls, path: str = PERFORMANCE_MEMORY_DATASET) -> "PerformanceMemory":
with open(path, "r", encoding="utf-8") as handle:
payload = json.load(handle)
entries = []
for record in payload:
entries.append(
PerformanceMemoryEntry(
play_name=record["play_name"],
stage=record["stage"],
audience_focus=record["audience_focus"],
channel=record["channel"],
tags=[tag.lower() for tag in record.get("tags", [])],
summary=record["summary"],
wins=record.get("wins", []),
losses=record.get("losses", []),
next_actions=record.get("next_actions", []),
kpi_focus=[str(kpi) for kpi in record.get("kpi_focus", [])],
confidence=float(record.get("confidence", 0.5)),
source=record.get("source", "performance_memory"),
notes=record.get("notes"),
)
)
return cls(entries)
@property
def entries(self) -> List[PerformanceMemoryEntry]:
return list(self._entries)
@dataclass(slots=True)
class CompetitiveLandscapeEntry:
"""Competitive signal captured from market monitoring."""
competitor: str
channel: str
summary: str
strengths: List[str]
weaknesses: List[str]
recommended_play: str
share_of_voice: float
signal_intensity: float
keywords: List[str]
maturity: str
source: str
notes: str | None = None
@dataclass(slots=True)
class CompetitiveSignal:
"""Recommendation derived from the competitive landscape dataset."""
competitor: str
channel: str
summary: str
strengths: List[str]
weaknesses: List[str]
recommended_play: str
share_of_voice: float
signal_intensity: float
threat_level: str
focus_alignment: float
source: str
notes: str | None = None
class CompetitiveLandscape:
"""Loads competitive marketing signals from curated monitoring."""
def __init__(self, entries: Sequence[CompetitiveLandscapeEntry]):
if not entries:
raise ValueError("CompetitiveLandscape requires at least one entry")
self._entries = list(entries)
@classmethod
def from_file(
cls, path: str = COMPETITIVE_LANDSCAPE_DATASET
) -> "CompetitiveLandscape":
with open(path, "r", encoding="utf-8") as handle:
payload = json.load(handle)
entries: List[CompetitiveLandscapeEntry] = []
for record in payload:
entries.append(
CompetitiveLandscapeEntry(
competitor=record["competitor"],
channel=record["channel"],
summary=record["summary"],
strengths=list(record.get("strengths", [])),
weaknesses=list(record.get("weaknesses", [])),
recommended_play=record["recommended_play"],
share_of_voice=float(record.get("share_of_voice", 0.0)),
signal_intensity=float(record.get("signal_intensity", 0.0)),
keywords=[str(token).lower() for token in record.get("keywords", [])],
maturity=record.get("maturity", "growth"),
source=record.get("source", "competitive_monitor"),
notes=record.get("notes"),
)
)
return cls(entries)
@property
def entries(self) -> List[CompetitiveLandscapeEntry]:
return list(self._entries)
class LearningLoopProcess:
"""Transforms prompt intelligence into closed-loop learning recommendations."""
def __init__(self, memory: PerformanceMemory | None = None):
self._memory = memory or PerformanceMemory.from_file()
def recommend(
self,
prompt: str,
diagnostics: "PromptDiagnostics",
campaigns: Sequence["CampaignScore"],
limit: int = 3,
) -> List[LearningLoopRecommendation]:
tokens = MarketingIntelligenceEngine._keyword_set(prompt)
diag_tokens: set[str] = set()
for bucket in (diagnostics.opportunities, diagnostics.recommended_kpis):
for item in bucket:
diag_tokens.update(MarketingIntelligenceEngine._keyword_set(item))
focus_tokens = set(MarketingIntelligenceEngine._keyword_set(diagnostics.focus))
urgency_bonus = 0.6 if diagnostics.urgency != "standard" else 0.0
channels = {score.campaign.channel.lower() for score in campaigns}
audiences = {score.campaign.audience.lower() for score in campaigns}
scored: List[Tuple[float, PerformanceMemoryEntry]] = []
for entry in self._memory.entries:
entry_tags = set(entry.tags)
kpi_tokens: set[str] = set()
for kpi in entry.kpi_focus:
kpi_tokens.update(MarketingIntelligenceEngine._keyword_set(kpi))
combined_tags = entry_tags.union(kpi_tokens)
tag_hits = len(combined_tags.intersection(tokens))
diag_hits = len(combined_tags.intersection(diag_tokens))
focus_hits = len(combined_tags.intersection(focus_tokens))
stage_bonus = 1.8 if entry.stage.lower() == diagnostics.stage.lower() else 0.0
channel_bonus = 1.0 if entry.channel.lower() in channels else 0.0
audience_bonus = 0.0
for audience in audiences:
if entry.audience_focus.lower() in audience or any(tag in audience for tag in combined_tags):
audience_bonus = 0.9
break
focus_bonus = 0.7 if focus_hits else 0.0
opportunity_bonus = 0.5 * diag_hits
keyword_bonus = 0.4 * tag_hits
score = (
entry.confidence
+ keyword_bonus
+ opportunity_bonus
+ focus_bonus
+ stage_bonus
+ channel_bonus
+ audience_bonus
+ urgency_bonus
)
scored.append((score, entry))
ranked = sorted(scored, key=lambda item: item[0], reverse=True)[: max(1, limit)]
recommendations: List[LearningLoopRecommendation] = []
for _, entry in ranked:
recommendations.append(
LearningLoopRecommendation(
play_name=entry.play_name,
stage=entry.stage,
audience_focus=entry.audience_focus,
channel=entry.channel,
learning=entry.summary,
wins=entry.wins,
losses=entry.losses,
next_actions=entry.next_actions,
kpi_focus=entry.kpi_focus,
confidence=round(min(0.99, max(0.0, entry.confidence)), 2),
source=entry.source,
notes=entry.notes,
)
)
return recommendations
class CompetitiveIntelligenceProcess:
"""Turns competitive monitoring into counter-moves for the marketing ANI."""
def __init__(self, landscape: CompetitiveLandscape | None = None):
self._landscape = landscape or CompetitiveLandscape.from_file()
def signals(
self,
prompt: str,
diagnostics: "PromptDiagnostics",
campaigns: Sequence["CampaignScore"],
limit: int = 3,
) -> List[CompetitiveSignal]:
prompt_tokens = set(MarketingIntelligenceEngine._keyword_set(prompt))
focus_tokens = set(MarketingIntelligenceEngine._keyword_set(diagnostics.focus))
combined_tokens = prompt_tokens.union(focus_tokens)
campaign_channels = {score.campaign.channel.lower() for score in campaigns}
stage_alignment = {
"paid search": "conversion",
"paid social": "consideration",
"content syndication": "awareness",
"outbound sdr": "conversion",
"lifecycle automation": "retention",
"partner ecosystem": "consideration",
}
scored: List[Tuple[float, CompetitiveLandscapeEntry, float]] = []
for entry in self._landscape.entries:
entry_tokens = set(entry.keywords)
keyword_hits = len(entry_tokens.intersection(prompt_tokens))
focus_hits = len(entry_tokens.intersection(focus_tokens))
overlap_hits = len(entry_tokens.intersection(combined_tokens))
share_component = entry.share_of_voice * 1.5
intensity_component = entry.signal_intensity
keyword_component = 0.25 * keyword_hits
focus_component = 0.35 * focus_hits
channel_component = 0.6 if entry.channel.lower() in campaign_channels else 0.0
stage_tag = stage_alignment.get(entry.channel.lower())
stage_component = 0.4 if stage_tag == diagnostics.stage.lower() else 0.0
maturity_component = 0.3 if entry.maturity.lower() in diagnostics.focus.lower() else 0.0
total_score = (
share_component
+ intensity_component
+ keyword_component
+ focus_component
+ channel_component
+ stage_component
+ maturity_component
)
focus_alignment = min(1.0, overlap_hits / max(1, len(entry_tokens)))
scored.append((total_score, entry, focus_alignment))
ranked = sorted(scored, key=lambda item: item[0], reverse=True)[: max(1, limit)]
signals: List[CompetitiveSignal] = []
for total_score, entry, alignment in ranked:
threat_index = entry.share_of_voice * 1.5 + entry.signal_intensity
if threat_index >= 1.65:
threat_level = "high"
elif threat_index >= 1.15:
threat_level = "medium"
else:
threat_level = "low"
signals.append(
CompetitiveSignal(
competitor=entry.competitor,
channel=entry.channel,
summary=entry.summary,
strengths=entry.strengths,
weaknesses=entry.weaknesses,
recommended_play=entry.recommended_play,
share_of_voice=round(entry.share_of_voice, 2),
signal_intensity=round(entry.signal_intensity, 2),
threat_level=threat_level,
focus_alignment=round(alignment, 2),
source=entry.source,
notes=entry.notes,
)
)
return signals
class MarketingBenchmarks:
"""Loads benchmark statistics and produces campaign metrics."""
def __init__(self, baseline: Dict[str, float], components: Dict[str, Dict[str, Dict[str, float]]]):
self._baseline = baseline
self._components = components
@classmethod
def from_file(cls, path: str = MARKETING_BENCHMARKS) -> "MarketingBenchmarks":
with open(path, "r", encoding="utf-8") as handle:
payload = json.load(handle)
baseline = payload.get("baseline", {"roi": 2.0, "ctr": 0.02, "confidence": 0.6})
components: Dict[str, Dict[str, Dict[str, float]]] = {}
for feature, entries in payload.items():
if feature == "baseline":
continue
components[feature] = {key.lower(): value for key, value in entries.items()}
return cls(baseline, components)
def _lookup(self, feature: str, value: str) -> Dict[str, float]:
cohort = self._components.get(feature, {})
return cohort.get(value.lower(), self._baseline)
def metrics_for(self, campaign: MarketingCampaign) -> CampaignMetrics:
weights = {
"channels": 0.32,
"audiences": 0.3,
"offers": 0.22,
"objectives": 0.16,
}
baseline_weight = max(0.0, 1.0 - sum(weights.values()))
base_roi = self._baseline.get("roi", 2.0)
base_ctr = self._baseline.get("ctr", 0.02)
base_conf = self._baseline.get("confidence", 0.6)
roi = base_roi * baseline_weight
ctr = base_ctr * baseline_weight
confidence = base_conf * baseline_weight
drivers: Dict[str, float] = {}
features = {
"channels": campaign.channel,
"audiences": campaign.audience,
"offers": campaign.offer,
"objectives": campaign.objective,
}
for feature, value in features.items():
stats = self._lookup(feature, value)
weight = weights[feature]
roi += stats.get("roi", base_roi) * weight
ctr += stats.get("ctr", base_ctr) * weight
confidence += stats.get("confidence", base_conf) * weight
drivers[feature.rstrip("s")] = stats.get("roi", base_roi)
return CampaignMetrics(
expected_roi=roi,
expected_ctr=ctr,
confidence=min(0.99, max(0.01, confidence)),
drivers=drivers,
)
@dataclass(slots=True)
class CampaignScore:
"""Composite score for a marketing campaign."""
campaign: MarketingCampaign
score: float
metrics: CampaignMetrics
keyword_coverage: Dict[str, int]
@dataclass(slots=True)
class PromptDiagnostics:
"""Structured analysis of a marketing prompt."""
stage: str
urgency: str
focus: str
recommended_kpis: List[str]
opportunities: List[str]
risk_signals: List[str]
keyword_summary: Dict[str, List[str]]
confidence: float
@dataclass(slots=True)
class GrowthExperiment:
"""Experiment plan produced by the Experiment Growth Grid (EGG) process."""
name: str
hypothesis: str
primary_metric: str
secondary_metrics: List[str]
playbook: List[str]
confidence: float
@dataclass(slots=True)
class CJAffiliateOffer:
"""Offer metadata sourced from the Commission Junction catalog."""
program_name: str
advertiser_id: str
category: str
commission_rate: float
epc: float
seven_day_epc: float
network_rank: int
payout_terms: str
landing_url: str
description: str
keywords: List[str]
@dataclass(slots=True)
class CJAffiliateRecommendation:
"""Recommendation returned by the CJ affiliate process."""
program_name: str
advertiser_id: str
category: str
commission_rate: float
epc: float
seven_day_epc: float
projected_epc: float
projected_monthly_revenue: float
network_rank: int
payout_terms: str
landing_url: str
rationale: str
source: str
notes: str | None = None
@dataclass(slots=True)
class InfluencerPartner:
"""Influencer metadata captured from curated partner intelligence."""
name: str
platform: str
niche: str
audience_size: int
engagement_rate: float
avg_cpm: float
collab_formats: List[str]
regions: List[str]
conversion_focus: str
keywords: List[str]
case_study: str
@dataclass(slots=True)
class InfluencerRecommendation:
"""Recommendation returned by the influencer collaboration process."""
name: str
platform: str
niche: str
collab_format: str
audience_size: int
engagement_rate: float
estimated_reach: int
projected_cpm: float
projected_leads: int
projected_revenue: float
projected_roi: float
rationale: str
source: str
notes: str | None = None
class InfluencerNetworkCatalog:
"""Loads curated influencer partner records for offline orchestration."""
def __init__(self, partners: Sequence[InfluencerPartner] | None = None) -> None:
if partners is not None:
self._partners = list(partners)
else:
with open(INFLUENCER_PARTNERS_DATASET, "r", encoding="utf-8") as handle:
data = json.load(handle)
self._partners = [InfluencerPartner(**entry) for entry in data]
def match_partners(
self, tokens: Sequence[str], focus: str | None, limit: int
) -> List[Tuple[float, InfluencerPartner]]:
token_set = {token.lower() for token in tokens}
focus_tokens = {token.lower() for token in re.findall(r"[a-zA-Z0-9]+", focus or "")}
ranked: List[Tuple[float, InfluencerPartner]] = []
for partner in self._partners:
haystack = (
f"{partner.name} {partner.platform} {partner.niche} {partner.conversion_focus} "
f"{' '.join(partner.keywords)} {partner.case_study}"
).lower()
score = 0.0
keyword_hits = 0
for token in token_set:
if token in haystack:
score += 1.8
keyword_hits += 1
if token in {keyword.lower() for keyword in partner.keywords}:
score += 1.5
keyword_hits += 1
for token in focus_tokens:
if token and token in haystack:
score += 1.2
if focus and focus.lower() in partner.conversion_focus.lower():
score += 1.0
if focus and focus.lower() in partner.niche.lower():
score += 0.8
score += min(partner.engagement_rate * 20, 2.4)
score += min(partner.audience_size / 150000.0, 2.0)
score += min(keyword_hits * 0.2, 1.5)
if "ai" in token_set and "ai" in {k.lower() for k in partner.keywords}:
score += 0.6
ranked.append((score, partner))
ranked.sort(key=lambda item: item[0], reverse=True)
return ranked[: max(1, limit)]
@dataclass(slots=True)
class AmazonMarketplaceListing:
"""Amazon or AWS Marketplace listing metadata."""
asin: str
title: str
category: str
price_usd: float
commission_rate: float
rating: float
reviews: int
url: str
keywords: List[str]
estimated_monthly_sales: int
buy_box_share: float
prime_eligible: bool
fulfillment_model: str
@dataclass(slots=True)
class AmazonProductRecommendation:
"""Recommendation payload produced by the Amazon marketplace process."""
asin: str
title: str
category: str
price_usd: float
commission_rate: float
rating: float
reviews: int
estimated_monthly_sales: int
buy_box_share: float
prime_eligible: bool
fulfillment_model: str
projected_monthly_revenue: float
rationale: str
url: str
source: str
notes: str | None = None
class AmazonMarketplaceCatalog:
"""Loads curated Amazon and AWS marketplace listings for offline use."""
def __init__(self, listings: Sequence[AmazonMarketplaceListing] | None = None):
if listings is not None:
self._listings = list(listings)
else:
with open(AMAZON_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle:
data = json.load(handle)
self._listings = [AmazonMarketplaceListing(**entry) for entry in data]
def match_listings(
self, tokens: Sequence[str], limit: int, focus: str | None = None
) -> List[Tuple[float, AmazonMarketplaceListing]]:
ranked: List[Tuple[float, AmazonMarketplaceListing]] = []
token_set = {token.lower() for token in tokens}
for listing in self._listings:
haystack = f"{listing.title} {listing.category} {' '.join(listing.keywords)}".lower()
score = 0.0
keyword_hits = 0
for token in token_set:
if token in haystack:
score += 1.5
keyword_hits += 1
if token in {keyword.lower() for keyword in listing.keywords}:
score += 1.8
if focus:
if focus.lower() in listing.category.lower():
score += 1.2
if focus.lower() in haystack:
score += 0.8
score += min(listing.rating / 5.0, 1.0)
score += min(listing.reviews / 500.0, 1.0)
score += min(listing.estimated_monthly_sales / 400.0, 1.2)
score += min(listing.buy_box_share, 1.0)
if listing.prime_eligible:
score += 0.35
if listing.fulfillment_model.lower().startswith("fba"):
score += 0.25
score += keyword_hits * 0.1
ranked.append((score, listing))
ranked.sort(key=lambda item: item[0], reverse=True)
return ranked[: max(1, limit)]
class AmazonMarketplaceProcess:
"""Transforms marketplace listings into revenue plans with optional SDK enrichment."""
REQUIRED_ENV_VARS = {
"AMAZON_PAAPI_ACCESS_KEY": "access_key",
"AMAZON_PAAPI_SECRET_KEY": "[credential removed]",
"AMAZON_PAAPI_PARTNER_TAG": "partner_tag",
}
OPTIONAL_ENV_VARS = {
"AWS_REGION": "region",
"AWS_PROFILE": "profile",
}
def __init__(
self,
catalog: AmazonMarketplaceCatalog | None = None,
config: Dict[str, Any] | None = None,
) -> None:
self._catalog = catalog or AmazonMarketplaceCatalog()
self._config = config or self._config_from_env()
self._session = self._build_session()
def _build_session(self) -> Any | None:
if not self.configured or boto3 is None:
return None
try: # pragma: no cover - requires boto3 dependency
return boto3.session.Session(
aws_access_key_id=self._config.get("access_key"),
aws_secret_access_key=[credential removed]"secret_key"),
region_name=self._config.get("region"),
profile_name=self._config.get("profile"),
)
except Exception:
return None
@classmethod
def _config_from_env(cls) -> Dict[str, Any]:
config: Dict[str, Any] = {}
for env_var, key in {**cls.REQUIRED_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items():
value = os.getenv(env_var)
if value:
config[key] = value
return config
@property
def configured(self) -> bool:
required = {key for key in self.REQUIRED_ENV_VARS.values()}
return required <= self._config.keys()
def listings(
self,
prompt: str,
campaigns: Sequence[CampaignScore],
limit: int,
) -> List[AmazonProductRecommendation]:
tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower())
focus = None
if campaigns:
focus = campaigns[0].campaign.channel.split()[0]
matches = self._catalog.match_listings(tokens, limit, focus)
if not matches:
return []
avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.1
avg_ctr = mean([score.metrics.expected_ctr for score in campaigns]) if campaigns else 0.025
avg_confidence = (
mean([score.metrics.confidence for score in campaigns]) if campaigns else 0.55
)
recommendations: List[AmazonProductRecommendation] = []
for match_score, listing in matches:
keyword_overlap = sorted(
{
token
for token in tokens
if token in {kw.lower() for kw in listing.keywords}
or token in listing.title.lower()
}
)
intensity = max(0.1, min(2.0, match_score / 4.0))
volume_estimate = listing.estimated_monthly_sales * max(0.4, avg_roi / 2.5)
buy_box_lift = 0.75 + listing.buy_box_share * 0.6
prime_lift = 1.18 if listing.prime_eligible else 0.9
confidence_lift = 0.85 + avg_confidence * 0.3
intent_multiplier = 0.35 + intensity * 0.25 + avg_ctr * 9.5
projected_revenue = round(
listing.price_usd
* listing.commission_rate
* volume_estimate
* buy_box_lift
* prime_lift
* confidence_lift
* intent_multiplier
/ 100,
2,
)
if keyword_overlap:
rationale = (
f"Aligns {listing.category.lower()} offer with {', '.join(keyword_overlap)} demand signals."
)
else:
rationale = (
f"High rating and volume listing positioned for {listing.category.lower()} expansion."
)
source = "amazon_paapi" if self._session else "amazon_catalog"
notes = None
if not self._session:
notes = (
"Simulated listing intelligence; supply Amazon PA-API credentials to activate live harvesting."
)
recommendations.append(
AmazonProductRecommendation(
asin=listing.asin,
title=listing.title,
category=listing.category,
price_usd=listing.price_usd,
commission_rate=listing.commission_rate,
rating=listing.rating,
reviews=listing.reviews,
estimated_monthly_sales=listing.estimated_monthly_sales,
buy_box_share=listing.buy_box_share,
prime_eligible=listing.prime_eligible,
fulfillment_model=listing.fulfillment_model,
projected_monthly_revenue=projected_revenue,
rationale=rationale,
url=listing.url,
source=source,
notes=notes,
)
)
return recommendations
@dataclass(slots=True)
class EbayMarketplaceListing:
"""eBay marketplace listing metadata for revenue planning."""
item_id: str
title: str
category: str
price_usd: float
affiliate_rate: float
seller_level: str
seller_rating: float
conversion_rate: float
sold_per_month: int
shipping_days: int
playbook: List[str]
confidence: float
@dataclass(slots=True)
class CJAffiliateOffer:
"""Offer metadata sourced from the Commission Junction catalog."""
program_name: str
advertiser_id: str
category: str
commission_rate: float
epc: float
seven_day_epc: float
network_rank: int
payout_terms: str
landing_url: str
description: str
keywords: List[str]
@dataclass(slots=True)
class CJAffiliateRecommendation:
"""Recommendation returned by the CJ affiliate process."""
program_name: str
advertiser_id: str
category: str
commission_rate: float
epc: float
seven_day_epc: float
projected_epc: float
projected_monthly_revenue: float
network_rank: int
payout_terms: str
landing_url: str
rationale: str
source: str
notes: str | None = None
@dataclass(slots=True)
class AmazonMarketplaceListing:
"""Amazon or AWS Marketplace listing metadata."""
asin: str
title: str
category: str
price_usd: float
commission_rate: float
rating: float
reviews: int
url: str
keywords: List[str]
@dataclass(slots=True)
class EbayRevenuePlay:
"""Recommendation payload produced by the eBay marketplace process."""
item_id: str
title: str
category: str
price_usd: float
affiliate_rate: float
seller_level: str
seller_rating: float
conversion_rate: float
sold_per_month: int
projected_monthly_revenue: float
projected_profit_margin: float
shipping_days: int
class AmazonProductRecommendation:
"""Recommendation payload produced by the Amazon marketplace process."""
asin: str
title: str
category: str
price_usd: float
commission_rate: float
rating: float
reviews: int
projected_monthly_revenue: float
rationale: str
url: str
source: str
notes: str | None = None
class EbayMarketplaceCatalog:
"""Loads curated eBay marketplace listings for offline use."""
def __init__(self, listings: Sequence[EbayMarketplaceListing] | None = None):
if listings is not None:
self._listings = list(listings)
else:
with open(EBAY_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle:
data = json.load(handle)
self._listings = [EbayMarketplaceListing(**entry) for entry in data]
def match_listings(
self, tokens: Sequence[str], limit: int, focus: str | None = None
) -> List[Tuple[float, EbayMarketplaceListing]]:
ranked: List[Tuple[float, EbayMarketplaceListing]] = []
token_set = {token.lower() for token in tokens}
for listing in self._listings:
haystack = (
f"{listing.title} {listing.category} {' '.join(listing.keywords)}"
).lower()
class AmazonMarketplaceCatalog:
"""Loads curated Amazon and AWS marketplace listings for offline use."""
def __init__(self, listings: Sequence[AmazonMarketplaceListing] | None = None):
if listings is not None:
self._listings = list(listings)
else:
with open(AMAZON_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle:
data = json.load(handle)
self._listings = [AmazonMarketplaceListing(**entry) for entry in data]
def match_listings(
self, tokens: Sequence[str], limit: int, focus: str | None = None
) -> List[Tuple[float, AmazonMarketplaceListing]]:
ranked: List[Tuple[float, AmazonMarketplaceListing]] = []
token_set = {token.lower() for token in tokens}
for listing in self._listings:
haystack = f"{listing.title} {listing.category} {' '.join(listing.keywords)}".lower()
score = 0.0
keyword_hits = 0
for token in token_set:
if token in haystack:
score += 1.4
keyword_hits += 1
if token in {keyword.lower() for keyword in listing.keywords}:
score += 1.6
if focus:
focus_lower = focus.lower()
if focus_lower in listing.category.lower():
score += 1.0
if focus_lower in haystack:
score += 0.6
score += min(listing.seller_rating / 5.0, 1.0)
score += min(listing.conversion_rate * 80.0, 1.2)
score += min(listing.sold_per_month / 350.0, 1.2)
if listing.seller_level.lower().startswith("top"):