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 | 11aa50ef5d7692e8abd1b8d74ae31c5c29201b14 |
| Branch | codex/build-online-github-ani-irqa7y |
| Path or archive member | services/seeder_api/intelligence.py |
| Original SHA-256 | 8d39bbdad6c168385be29ead54d0633cb7d274f1048effa8ef6de95e15e3a1b2 |
| Git blob SHA | ac266ccac81ca259943092242a4c3284d965adce |
| Reading-copy SHA-256 | d45eba8b9d914c66188a85b9d3b0db6829e7f8d48b7c6fcee60e7ba5df09a792 |
Every recorded occurrence
These 3 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-irqa7y | 11aa50ef5d7692e8abd1b8d74ae31c5c29201b14 | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-0etkns | e250b19d446bdffd542c9eea31cead12e30800d6 | Open original |
| Janady13/AI_Brain / services/seeder_api/intelligence.py | codex/build-online-github-ani-irqa7y | 11aa50ef5d7692e8abd1b8d74ae31c5c29201b14 | Open original |
Recovered source transcript
Download complete source text ↓5,617 lines · 212.6 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 math
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
try: # pragma: no cover - optional dependency for Postgres persistence
import psycopg2 # type: ignore
from psycopg2.extras import Json # type: ignore
except Exception: # pragma: no cover - handle environments without psycopg2
psycopg2 = None # type: ignore
Json = 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",
)
STOCK_MARKETS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"global_stock_markets.json",
)
STATISTICAL_PRIORS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"statistical_reasoning.json",
)
COGNITIVE_CAPABILITIES_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"cognitive_capabilities.json",
)
AGENTIC_SYSTEMS_DATASET = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"daemon",
"datasets",
"agentic_systems.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 StatisticalPrior:
"""Historical statistical benchmark for a marketing dimension."""
feature: str
feature_type: str
mean_roi: float
std_roi: float
mean_ctr: float
std_ctr: float
sample_size: int
weight: float
baseline_budget: float
notes: str
@dataclass(slots=True)
class CognitiveCapability:
"""Represents a cognitive pillar the ANI can operationalize."""
name: str
pillar: str
description: str
signal_keywords: List[str]
prompt_strategies: List[str]
frameworks: List[str]
tooling: List[str]
metrics: List[str]
knowledge_assets: List[str]
play: str
@classmethod
def from_dict(cls, payload: Dict[str, Any]) -> "CognitiveCapability":
return cls(
name=payload["name"],
pillar=payload["pillar"],
description=payload["description"],
signal_keywords=[keyword.lower() for keyword in payload["signal_keywords"]],
prompt_strategies=payload["prompt_strategies"],
frameworks=payload["frameworks"],
tooling=payload["tooling"],
metrics=payload["metrics"],
knowledge_assets=payload["knowledge_assets"],
play=payload["play"],
)
@dataclass(slots=True)
class CognitiveCapabilityPlan:
"""Cognitive orchestration outcome derived from prompt and campaign context."""
capability: str
pillar: str
maturity: str
description: str
reasoning: str
prompt_strategy: str
frameworks: List[str]
tooling: List[str]
metrics: List[str]
knowledge_assets: List[str]
orchestration_steps: List[str]
source: str
@dataclass(slots=True)
class AgenticCapability:
"""Represents an agentic system capability that can be activated."""
name: str
domain: str
description: str
controller: str
trigger_keywords: List[str]
frameworks: List[str]
toolchain: List[str]
data_interfaces: List[str]
knowledge_sources: List[str]
revenue_programs: List[str]
risk_controls: List[str]
maturity_signals: List[str]
base_maturity: str
metrics: List[str]
@classmethod
def from_dict(cls, payload: Dict[str, Any]) -> "AgenticCapability":
return cls(
name=payload["name"],
domain=payload["domain"],
description=payload["description"],
controller=payload.get("controller", "Agent controller"),
trigger_keywords=[keyword.lower() for keyword in payload.get("trigger_keywords", [])],
frameworks=payload.get("frameworks", []),
toolchain=payload.get("toolchain", []),
data_interfaces=payload.get("data_interfaces", []),
knowledge_sources=payload.get("knowledge_sources", []),
revenue_programs=payload.get("revenue_programs", []),
risk_controls=payload.get("risk_controls", []),
maturity_signals=payload.get("maturity_signals", []),
base_maturity=payload.get("base_maturity", "foundational"),
metrics=payload.get("metrics", []),
)
@dataclass(slots=True)
class AgenticSystemPlan:
"""Structured plan describing how the ANI activates agentic systems."""
system_name: str
domain: str
controller: str
maturity: str
reasoning: str
orchestration_steps: List[str]
toolchain: List[str]
data_interfaces: List[str]
knowledge_sources: List[str]
revenue_programs: List[str]
risk_controls: List[str]
metrics: List[str]
source: str
notes: str | None = None
@dataclass(slots=True)
class StatisticalEvidence:
"""Posterior insight after blending priors with live campaign metrics."""
feature: str
feature_type: str
posterior_roi: float
posterior_ctr: float
confidence: float
lift_vs_benchmark: float
sample_size: int
weight: float
rationale: str
@dataclass(slots=True)
class StatisticalReasoningSummary:
"""Aggregated statistical reasoning powering marketing ANI."""
expected_roi: float
expected_revenue: float
confidence: float
success_probability: float
volatility_adjustment: float
scenario_spread: Dict[str, float]
driver_confidence: Dict[str, float]
evidence: List[StatisticalEvidence]
narrative: str
source: str = "statistical_reasoning"
notes: str | None = None
@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,
stocks: Sequence[StockMarketForecast] | None,
statistics: StatisticalReasoningSummary | None,
cognitive: Sequence[CognitiveCapabilityPlan] | None,
agentic: Sequence[AgenticSystemPlan] | 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"
)
if stocks:
avg_return = mean(forecast.forecast_return_90d for forecast in stocks)
avg_conf = mean(forecast.confidence for forecast in stocks)
if avg_return > 0.12 and avg_conf >= 0.55:
accelerators.append(
f"Equity momentum projects {avg_return*100:.0f}% upside supporting budget expansion"
)
elif avg_conf >= 0.6:
accelerators.append("Stock market baselines stabilizing capital access for growth plays")
if statistics and statistics.success_probability >= 0.75:
accelerators.append(
f"Statistical reasoning signals {statistics.success_probability:.0%} success with {statistics.expected_roi:.2f}x ROI"
)
if cognitive:
top_capability = cognitive[0]
accelerators.append(
f"Cognitive architecture {top_capability.maturity} on {top_capability.capability} keeps orchestration sharp"
)
if agentic:
system = agentic[0]
if system.maturity in {"elite", "autonomous"}:
accelerators.append(
f"Agentic system {system.system_name} operating at {system.maturity} maturity automates multi-tool execution"
)
else:
accelerators.append(
f"Agentic system {system.system_name} activates {system.toolchain[0] if system.toolchain else 'orchestration'} for rapid deployment"
)
return accelerators
@staticmethod
def _stabilizers(
diagnostics: PromptDiagnostics,
budget: BudgetPlan | None,
statistics: StatisticalReasoningSummary | None,
cognitive: Sequence[CognitiveCapabilityPlan] | None,
agentic: Sequence[AgenticSystemPlan] | 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")
if statistics:
stabilizers.append(
f"Recompute statistical priors weekly to maintain {statistics.success_probability:.0%} success guardrails"
)
if cognitive:
stabilizers.append(
f"Audit cognitive capability '{cognitive[0].capability}' to preserve prompt and reasoning quality"
)
if agentic:
stabilizers.append(
f"Schedule agentic system '{agentic[0].system_name}' health checks to keep tool calling compliant"
)
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,
stocks: Sequence[StockMarketForecast] | None,
statistics: StatisticalReasoningSummary | None,
cognitive: Sequence[CognitiveCapabilityPlan] | None,
agentic: Sequence[AgenticSystemPlan] | None,
limit: int = 3,
) -> ScenarioAnalysis:
if not campaigns:
raise ValueError("Scenario planning requires campaign scores")
top = list(campaigns[: max(1, limit)])
agentic = list(agentic or [])
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)
if statistics:
inferred_budget = (
statistics.expected_revenue / max(statistics.expected_roi, 0.1)
if statistics.expected_roi > 0
else base_budget
)
base_budget = max(base_budget, inferred_budget)
base_revenue = max(base_revenue, statistics.expected_revenue)
base_roi = max(base_roi, statistics.expected_roi)
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
if stocks and any(forecast.volatility > 0.3 for forecast in stocks):
volatility += 0.04
elif stocks and mean(forecast.volatility for forecast in stocks) < 0.12:
volatility -= 0.02
if statistics:
volatility = max(volatility, statistics.volatility_adjustment)
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)
if statistics:
blended_base = statistics.success_probability * 0.6 + base_prob * 0.4
base_prob = min(0.85, max(0.25, blended_base))
residual = max(0.15, 1.0 - base_prob)
share_denominator = max(optimistic_prob + conservative_prob, 0.01)
optimistic_share = optimistic_prob / share_denominator
optimistic_prob = min(0.6, residual * optimistic_share)
conservative_prob = max(0.1, residual - optimistic_prob)
total = optimistic_prob + base_prob + conservative_prob
optimistic_prob = round(max(0.05, optimistic_prob / total), 2)
base_prob = round(max(0.1, base_prob / total), 2)
conservative_prob = round(max(0.05, conservative_prob / total), 2)
accelerators = self._signal_accelerators(
google_ads,
cj_affiliate,
amazon,
ebay,
aws,
stripe,
paypal,
influencers,
stocks,
statistics,
cognitive,
agentic,
)
stabilizers = self._stabilizers(diagnostics, budget, statistics, cognitive, agentic)
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"
)
if statistics:
notes += (
f" | Statistical reasoning forecasts {statistics.expected_roi:.2f}x ROI with "
f"{statistics.success_probability:.0%} success probability"
)
if agentic:
notes += (
f" | Agentic system {agentic[0].system_name} ({agentic[0].maturity}) orchestrates tool calling"
)
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: