Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/AI_Brain / services/seeder_api/app.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/app.py |
| Original SHA-256 | bf2a203c1743c882783e3881849179fbf1b7085ec1e4382f6add893a43c68c3d |
| Git blob SHA | 679ad75cc5e9180ed2e8a0861f183b2b1afa8a96 |
| Reading-copy SHA-256 | bf2a203c1743c882783e3881849179fbf1b7085ec1e4382f6add893a43c68c3d |
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/app.py | codex/build-online-github-ani-hr4y0z | 366ab848896ae49159cfb3f6c201b8c5a731e9c8 | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-i3cigl | 3a6e002311c48c27ffd41ef4a2a31c63947128cd | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-jf5olo | c6653627c453ab428d665226167fa5f4aa05e9a5 | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-7nmb21 | d0f50071c85cddaaebbf9c4dd1313bd7676986da | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-hr4y0z | 366ab848896ae49159cfb3f6c201b8c5a731e9c8 | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-i3cigl | 3a6e002311c48c27ffd41ef4a2a31c63947128cd | Open original |
| Janady13/AI_Brain / services/seeder_api/app.py | codex/build-online-github-ani-jf5olo | c6653627c453ab428d665226167fa5f4aa05e9a5 | Open original |
Recovered source transcript
Download complete source text ↓1,033 lines · 33.2 KB
#!/usr/bin/env python3
import os
import time
from fastapi import FastAPI
from pydantic import BaseModel
from .intelligence import (
AmazonProductRecommendation,
AWSRevenueRecommendation,
AutomationSprint,
AutomationTask,
BudgetPlan,
CampaignMetrics,
CampaignScore,
CJAffiliateRecommendation,
CryptoMarketSnapshot,
EbayRevenuePlay,
GrowthExperiment,
GoogleCampaignPerformance,
CompetitiveSignal,
InfluencerRecommendation,
LearningLoopRecommendation,
ExcellenceSummary,
ExecutivePlaybook,
StrategicDirective,
ScenarioAnalysis,
ScenarioProjection,
MarketingIntelligenceEngine,
MarketingCampaign,
PromptDiagnostics,
StripeMonetizationPlan,
PayPalMonetizationPlan,
default_marketing_engine,
)
APP_NAME = os.getenv("APP_NAME", "HiveSeedAPI")
START_TS = time.time()
app = FastAPI(title=APP_NAME)
class Health(BaseModel):
status: str
uptime_seconds: float
class Ready(BaseModel):
ready: bool
reason: str | None = None
class MarketingQuery(BaseModel):
prompt: str
limit: int = 3
class MarketingInsight(BaseModel):
channel: str
audience: str
offer: str
objective: str
rationale: str
class MarketingResponse(BaseModel):
query: str
recommendations: list[MarketingInsight]
insight: str
class StatisticalInsight(BaseModel):
channel: str
audience: str
offer: str
objective: str
expected_roi: float
expected_ctr: float
confidence: float
rationale: str
drivers: dict[str, float]
class PortfolioInsight(BaseModel):
expected_roi: float
expected_ctr: float
confidence: float
rationale: str
strongest_drivers: dict[str, float]
class StatisticalResponse(BaseModel):
query: str
recommendations: list[StatisticalInsight]
portfolio: PortfolioInsight
class DiagnosticResponse(BaseModel):
query: str
stage: str
urgency: str
focus: str
confidence: float
recommended_kpis: list[str]
opportunities: list[str]
risk_signals: list[str]
keyword_summary: dict[str, list[str]]
class ProcessRun(BaseModel):
process: str
recommendations: list[MarketingInsight]
summary: str
class ExperimentInsight(BaseModel):
name: str
hypothesis: str
primary_metric: str
secondary_metrics: list[str]
playbook: list[str]
confidence: float
class LearningLoopInsight(BaseModel):
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
class CompetitiveLandscapeInsight(BaseModel):
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 ExcellenceInsight(BaseModel):
excellence_index: float
maturity_level: str
headline: str
strengths: list[str]
watchouts: list[str]
process_coverage: dict[str, float]
notes: str | None = None
class StrategicDirectiveInsight(BaseModel):
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
notes: str | None = None
class ExecutivePlaybookInsight(BaseModel):
headline: str
focus: str
urgency: str
north_star_metric: str
total_budget_usd: float | None
expected_revenue_usd: float | None
confidence: float
directives: list[StrategicDirectiveInsight]
summary: str
notes: str | None = None
class ScenarioProjectionInsight(BaseModel):
scenario: str
expected_revenue: float
expected_roi: float
probability: float
confidence: float
accelerators: list[str]
stabilizers: list[str]
watchouts: list[str]
source: str
notes: str | None = None
class ScenarioPlanningInsight(BaseModel):
headline: str
summary: str
projections: list[ScenarioProjectionInsight]
confidence: float
accelerators: list[str]
stabilizers: list[str]
source: str
notes: str | None = None
class MarketingProcessesResponse(BaseModel):
query: str
rag: ProcessRun
egg: list[ExperimentInsight]
google_ads: list["GoogleAdsInsight"]
cj_affiliate: list["CJAffiliateInsight"]
crypto_markets: list["CryptoMarketInsight"]
stripe: list["StripePlanInsight"]
paypal: list["PayPalPlanInsight"]
influencer_collaborations: list["InfluencerInsight"]
amazon_marketplace: list["AmazonMarketplaceInsight"]
ebay_marketplace: list["EbayMarketplaceInsight"]
aws_cloud: list["AWSRevenueInsight"]
budget_optimizer: "BudgetPlanInsight"
automation: "AutomationSprintInsight"
learning_loop: list["LearningLoopInsight"]
competitive_landscape: list["CompetitiveLandscapeInsight"]
excellence: "ExcellenceInsight"
executive_playbook: "ExecutivePlaybookInsight"
scenario_planning: "ScenarioPlanningInsight"
class GoogleAdsInsight(BaseModel):
campaign_name: str
clicks: int
impressions: int
conversions: float
cost_micros: int
ctr: float
cpc: float
roas: float
source: str
notes: str | None = None
class CJAffiliateInsight(BaseModel):
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
class CryptoMarketInsight(BaseModel):
asset: str
price_usd: float | None
change_24h: float | None
market_cap: float | None
volume_24h: float | None
source: str
notes: str | None = None
class StripePlanInsight(BaseModel):
product_name: str
price_usd: float
billing_interval: str
currency: str
rationale: str
setup_steps: list[str]
source: str
notes: str | None = None
class PayPalPlanInsight(BaseModel):
product_name: str
price_usd: float
checkout_flow: str
payout_schedule: str
rationale: str
setup_steps: list[str]
source: str
notes: str | None = None
class InfluencerInsight(BaseModel):
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 AmazonMarketplaceInsight(BaseModel):
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 EbayMarketplaceInsight(BaseModel):
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
rationale: str
url: str
source: str
notes: str | None = None
class AWSRevenueInsight(BaseModel):
program_name: str
focus: str
description: str
revenue_motion: str
primary_service: str
secondary_services: list[str]
automation_play: str
projected_roi: float
source: str
notes: str | None = None
class BudgetAllocationInsight(BaseModel):
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
class BudgetPlanInsight(BaseModel):
total_budget: float
expected_revenue: float
expected_roi: float
payback_period_weeks: float
summary: str
allocations: list[BudgetAllocationInsight]
class AutomationTaskInsight(BaseModel):
start_minute: int
end_minute: int
activity: str
outcome: str
tooling: list[str]
kpis: list[str]
automation_level: str
source: str
class AutomationSprintInsight(BaseModel):
total_minutes: int
stage: str
focus: str
summary: str
notes: str | None = None
tasks: list[AutomationTaskInsight]
source: str
try: # Pydantic v2
GoogleAdsInsight.model_rebuild()
CJAffiliateInsight.model_rebuild()
CryptoMarketInsight.model_rebuild()
StripePlanInsight.model_rebuild()
PayPalPlanInsight.model_rebuild()
InfluencerInsight.model_rebuild()
AmazonMarketplaceInsight.model_rebuild()
EbayMarketplaceInsight.model_rebuild()
AWSRevenueInsight.model_rebuild()
BudgetAllocationInsight.model_rebuild()
BudgetPlanInsight.model_rebuild()
AutomationTaskInsight.model_rebuild()
AutomationSprintInsight.model_rebuild()
LearningLoopInsight.model_rebuild()
CompetitiveLandscapeInsight.model_rebuild()
ExcellenceInsight.model_rebuild()
StrategicDirectiveInsight.model_rebuild()
ExecutivePlaybookInsight.model_rebuild()
ScenarioProjectionInsight.model_rebuild()
ScenarioPlanningInsight.model_rebuild()
MarketingProcessesResponse.model_rebuild()
except AttributeError: # pragma: no cover - pydantic v1 fallback
MarketingProcessesResponse.update_forward_refs(
GoogleAdsInsight=GoogleAdsInsight,
CJAffiliateInsight=CJAffiliateInsight,
CryptoMarketInsight=CryptoMarketInsight,
StripePlanInsight=StripePlanInsight,
PayPalPlanInsight=PayPalPlanInsight,
InfluencerInsight=InfluencerInsight,
AmazonMarketplaceInsight=AmazonMarketplaceInsight,
EbayMarketplaceInsight=EbayMarketplaceInsight,
AWSRevenueInsight=AWSRevenueInsight,
BudgetAllocationInsight=BudgetAllocationInsight,
BudgetPlanInsight=BudgetPlanInsight,
AutomationTaskInsight=AutomationTaskInsight,
AutomationSprintInsight=AutomationSprintInsight,
LearningLoopInsight=LearningLoopInsight,
CompetitiveLandscapeInsight=CompetitiveLandscapeInsight,
ExcellenceInsight=ExcellenceInsight,
StrategicDirectiveInsight=StrategicDirectiveInsight,
ExecutivePlaybookInsight=ExecutivePlaybookInsight,
ScenarioProjectionInsight=ScenarioProjectionInsight,
ScenarioPlanningInsight=ScenarioPlanningInsight,
)
@app.get("/healthz", response_model=Health)
def healthz() -> Health:
return Health(status="ok", uptime_seconds=time.time() - START_TS)
@app.get("/readyz", response_model=Ready)
def readyz() -> Ready:
# Minimal readiness: enumerations exist or DRY_RUN enabled
base = os.path.join(os.path.dirname(__file__), "..", "..", "daemon", "enumerations")
files = [
os.path.join(base, "math_model_500.txt"),
os.path.join(base, "agent_500.txt"),
os.path.join(base, "language_500.txt"),
os.path.join(base, "prophecy_500.txt"),
os.path.join(base, "marketing_500.txt"),
]
if all(os.path.isfile(p) for p in files):
return Ready(ready=True)
if os.getenv("DRY_RUN", "0") in {"1", "true", "TRUE", "yes", "on"}:
return Ready(ready=True, reason="DRY_RUN enabled")
return Ready(ready=False, reason="Enumerations missing; run make enumerations")
def _campaign_to_insight(engine: MarketingIntelligenceEngine, query: str, campaign: MarketingCampaign) -> MarketingInsight:
tokens = engine.keywords(query)
matches: list[str] = []
normalized = {
"channel": campaign.channel.lower(),
"audience": campaign.audience.lower(),
"offer": campaign.offer.lower(),
"objective": campaign.objective.lower(),
}
for token in tokens:
for feature, text in normalized.items():
if token in text and feature not in matches:
matches.append(feature)
rationale = "Matched: " + ", ".join(matches) if matches else "General fit from curated library"
return MarketingInsight(
channel=campaign.channel,
audience=campaign.audience,
offer=campaign.offer,
objective=campaign.objective,
rationale=rationale,
)
def _campaign_to_statistical_insight(
engine: MarketingIntelligenceEngine,
query: str,
scored: CampaignScore,
) -> StatisticalInsight:
matches: list[str] = []
for feature, count in scored.keyword_coverage.items():
if count:
matches.append(feature)
if matches:
rationale = f"Matched {', '.join(sorted(matches))} intent with statistical lift."
else:
rationale = "Benchmark-driven pick from marketing corpus."
strongest = sorted(scored.metrics.drivers.items(), key=lambda item: item[1], reverse=True)
if strongest:
rationale += f" Top driver: {strongest[0][0]} ROI {strongest[0][1]:.2f}."
return StatisticalInsight(
channel=scored.campaign.channel,
audience=scored.campaign.audience,
offer=scored.campaign.offer,
objective=scored.campaign.objective,
expected_roi=round(scored.metrics.expected_roi, 2),
expected_ctr=round(scored.metrics.expected_ctr, 4),
confidence=round(scored.metrics.confidence, 2),
rationale=rationale,
drivers={key: round(value, 2) for key, value in scored.metrics.drivers.items()},
)
def _portfolio_to_insight(query: str, portfolio: CampaignMetrics, tokens: list[str]) -> PortfolioInsight:
highlights = ", ".join(sorted(set(tokens))) or "broad"
strongest = sorted(portfolio.drivers.items(), key=lambda item: item[1], reverse=True)
driver_text = strongest[0][0] if strongest else "channel"
rationale = (
f"Statistical blend for '{query}' optimized for {highlights} focus; strongest lift from {driver_text}."
)
return PortfolioInsight(
expected_roi=round(portfolio.expected_roi, 2),
expected_ctr=round(portfolio.expected_ctr, 4),
confidence=round(portfolio.confidence, 2),
rationale=rationale,
strongest_drivers={key: round(value, 2) for key, value in portfolio.drivers.items()},
)
@app.post("/intelligence/marketing", response_model=MarketingResponse)
def marketing_intelligence(query: MarketingQuery) -> MarketingResponse:
engine = default_marketing_engine()
campaigns = engine.recommend(query.prompt, query.limit)
insights = [_campaign_to_insight(engine, query.prompt, campaign) for campaign in campaigns]
narrative = engine.summarize(query.prompt, campaigns)
return MarketingResponse(query=query.prompt, recommendations=insights, insight=narrative)
@app.post("/intelligence/marketing/statistical", response_model=StatisticalResponse)
def marketing_statistical_intelligence(query: MarketingQuery) -> StatisticalResponse:
engine = default_marketing_engine()
ranked = engine.recommend_statistical(query.prompt, query.limit)
insights = [
_campaign_to_statistical_insight(engine, query.prompt, scored) for scored in ranked
]
tokens = engine.keywords(query.prompt)
portfolio_metrics = engine.portfolio(query.prompt, ranked)
portfolio = _portfolio_to_insight(query.prompt, portfolio_metrics, tokens)
return StatisticalResponse(query=query.prompt, recommendations=insights, portfolio=portfolio)
def _diagnostics_payload(query: str, diagnostics: PromptDiagnostics) -> DiagnosticResponse:
return DiagnosticResponse(
query=query,
stage=diagnostics.stage,
urgency=diagnostics.urgency,
focus=diagnostics.focus,
confidence=diagnostics.confidence,
recommended_kpis=diagnostics.recommended_kpis,
opportunities=diagnostics.opportunities,
risk_signals=diagnostics.risk_signals,
keyword_summary=diagnostics.keyword_summary,
)
def _experiment_payload(experiment: GrowthExperiment) -> ExperimentInsight:
return ExperimentInsight(
name=experiment.name,
hypothesis=experiment.hypothesis,
primary_metric=experiment.primary_metric,
secondary_metrics=experiment.secondary_metrics,
playbook=experiment.playbook,
confidence=experiment.confidence,
)
def _google_ads_payload(performance: GoogleCampaignPerformance) -> "GoogleAdsInsight":
return GoogleAdsInsight(
campaign_name=performance.campaign_name,
clicks=performance.clicks,
impressions=performance.impressions,
conversions=performance.conversions,
cost_micros=performance.cost_micros,
ctr=performance.ctr,
cpc=performance.cpc,
roas=performance.roas,
source=performance.source,
notes=performance.notes,
)
def _cj_affiliate_payload(recommendation: CJAffiliateRecommendation) -> "CJAffiliateInsight":
return CJAffiliateInsight(
program_name=recommendation.program_name,
advertiser_id=recommendation.advertiser_id,
category=recommendation.category,
commission_rate=recommendation.commission_rate,
epc=recommendation.epc,
seven_day_epc=recommendation.seven_day_epc,
projected_epc=recommendation.projected_epc,
projected_monthly_revenue=recommendation.projected_monthly_revenue,
network_rank=recommendation.network_rank,
payout_terms=recommendation.payout_terms,
landing_url=recommendation.landing_url,
rationale=recommendation.rationale,
source=recommendation.source,
notes=recommendation.notes,
)
def _crypto_market_payload(snapshot: CryptoMarketSnapshot) -> "CryptoMarketInsight":
return CryptoMarketInsight(
asset=snapshot.asset,
price_usd=snapshot.price_usd,
change_24h=snapshot.change_24h,
market_cap=snapshot.market_cap,
volume_24h=snapshot.volume_24h,
source=snapshot.source,
notes=snapshot.notes,
)
def _stripe_plan_payload(plan: StripeMonetizationPlan) -> "StripePlanInsight":
return StripePlanInsight(
product_name=plan.product_name,
price_usd=plan.price_usd,
billing_interval=plan.billing_interval,
currency=plan.currency,
rationale=plan.rationale,
setup_steps=plan.setup_steps,
source=plan.source,
notes=plan.notes,
)
def _paypal_plan_payload(plan: PayPalMonetizationPlan) -> "PayPalPlanInsight":
return PayPalPlanInsight(
product_name=plan.product_name,
price_usd=plan.price_usd,
checkout_flow=plan.checkout_flow,
payout_schedule=plan.payout_schedule,
rationale=plan.rationale,
setup_steps=plan.setup_steps,
source=plan.source,
notes=plan.notes,
)
def _influencer_payload(
recommendation: InfluencerRecommendation,
) -> "InfluencerInsight":
return InfluencerInsight(
name=recommendation.name,
platform=recommendation.platform,
niche=recommendation.niche,
collab_format=recommendation.collab_format,
audience_size=recommendation.audience_size,
engagement_rate=recommendation.engagement_rate,
estimated_reach=recommendation.estimated_reach,
projected_cpm=recommendation.projected_cpm,
projected_leads=recommendation.projected_leads,
projected_revenue=recommendation.projected_revenue,
projected_roi=recommendation.projected_roi,
rationale=recommendation.rationale,
source=recommendation.source,
notes=recommendation.notes,
)
def _amazon_listing_payload(
recommendation: AmazonProductRecommendation,
) -> "AmazonMarketplaceInsight":
return AmazonMarketplaceInsight(
asin=recommendation.asin,
title=recommendation.title,
category=recommendation.category,
price_usd=recommendation.price_usd,
commission_rate=recommendation.commission_rate,
rating=recommendation.rating,
reviews=recommendation.reviews,
estimated_monthly_sales=recommendation.estimated_monthly_sales,
buy_box_share=recommendation.buy_box_share,
prime_eligible=recommendation.prime_eligible,
fulfillment_model=recommendation.fulfillment_model,
projected_monthly_revenue=recommendation.projected_monthly_revenue,
rationale=recommendation.rationale,
url=recommendation.url,
source=recommendation.source,
notes=recommendation.notes,
)
def _ebay_listing_payload(recommendation: EbayRevenuePlay) -> "EbayMarketplaceInsight":
return EbayMarketplaceInsight(
item_id=recommendation.item_id,
title=recommendation.title,
category=recommendation.category,
price_usd=recommendation.price_usd,
affiliate_rate=recommendation.affiliate_rate,
seller_level=recommendation.seller_level,
seller_rating=recommendation.seller_rating,
conversion_rate=recommendation.conversion_rate,
sold_per_month=recommendation.sold_per_month,
projected_monthly_revenue=recommendation.projected_monthly_revenue,
projected_profit_margin=recommendation.projected_profit_margin,
shipping_days=recommendation.shipping_days,
rationale=recommendation.rationale,
url=recommendation.url,
source=recommendation.source,
notes=recommendation.notes,
)
def _aws_revenue_payload(recommendation: AWSRevenueRecommendation) -> "AWSRevenueInsight":
return AWSRevenueInsight(
program_name=recommendation.program_name,
focus=recommendation.focus,
description=recommendation.description,
revenue_motion=recommendation.revenue_motion,
primary_service=recommendation.primary_service,
secondary_services=recommendation.secondary_services,
automation_play=recommendation.automation_play,
projected_roi=recommendation.projected_roi,
source=recommendation.source,
notes=recommendation.notes,
)
def _budget_plan_payload(plan: BudgetPlan) -> "BudgetPlanInsight":
allocations = [
BudgetAllocationInsight(
channel=allocation.channel,
audience_focus=allocation.audience_focus,
offer=allocation.offer,
objective=allocation.objective,
allocation_usd=allocation.allocation_usd,
allocation_weight=allocation.allocation_weight,
expected_leads=allocation.expected_leads,
expected_revenue=allocation.expected_revenue,
rationale=allocation.rationale,
source=allocation.source,
notes=allocation.notes,
)
for allocation in plan.allocations
]
return BudgetPlanInsight(
total_budget=plan.total_budget,
expected_revenue=plan.expected_revenue,
expected_roi=plan.expected_roi,
payback_period_weeks=plan.payback_period_weeks,
summary=plan.summary,
allocations=allocations,
)
def _automation_task_payload(task: AutomationTask) -> AutomationTaskInsight:
return AutomationTaskInsight(
start_minute=task.start_minute,
end_minute=task.end_minute,
activity=task.activity,
outcome=task.outcome,
tooling=task.tooling,
kpis=task.kpis,
automation_level=task.automation_level,
source=task.source,
)
def _automation_sprint_payload(sprint: AutomationSprint) -> AutomationSprintInsight:
return AutomationSprintInsight(
total_minutes=sprint.total_minutes,
stage=sprint.stage,
focus=sprint.focus,
summary=sprint.summary,
notes=sprint.notes,
tasks=[_automation_task_payload(task) for task in sprint.tasks],
source=sprint.source,
)
def _learning_loop_payload(recommendation: LearningLoopRecommendation) -> "LearningLoopInsight":
return LearningLoopInsight(
play_name=recommendation.play_name,
stage=recommendation.stage,
audience_focus=recommendation.audience_focus,
channel=recommendation.channel,
learning=recommendation.learning,
wins=recommendation.wins,
losses=recommendation.losses,
next_actions=recommendation.next_actions,
kpi_focus=recommendation.kpi_focus,
confidence=recommendation.confidence,
source=recommendation.source,
notes=recommendation.notes,
)
def _competitive_signal_payload(signal: CompetitiveSignal) -> "CompetitiveLandscapeInsight":
return CompetitiveLandscapeInsight(
competitor=signal.competitor,
channel=signal.channel,
summary=signal.summary,
strengths=signal.strengths,
weaknesses=signal.weaknesses,
recommended_play=signal.recommended_play,
share_of_voice=signal.share_of_voice,
signal_intensity=signal.signal_intensity,
threat_level=signal.threat_level,
focus_alignment=signal.focus_alignment,
source=signal.source,
notes=signal.notes,
)
def _excellence_payload(summary: ExcellenceSummary) -> ExcellenceInsight:
return ExcellenceInsight(
excellence_index=summary.excellence_index,
maturity_level=summary.maturity_level,
headline=summary.headline,
strengths=summary.strengths,
watchouts=summary.watchouts,
process_coverage=summary.process_coverage,
notes=summary.notes,
)
def _directive_payload(directive: StrategicDirective) -> StrategicDirectiveInsight:
return StrategicDirectiveInsight(
name=directive.name,
priority=directive.priority,
objective=directive.objective,
primary_channel=directive.primary_channel,
supporting_channels=directive.supporting_channels,
investment_usd=directive.investment_usd,
expected_revenue_usd=directive.expected_revenue_usd,
confidence=directive.confidence,
time_horizon_hours=directive.time_horizon_hours,
north_star_metric=directive.north_star_metric,
supporting_metrics=directive.supporting_metrics,
action_steps=directive.action_steps,
dependencies=directive.dependencies,
risk_mitigations=directive.risk_mitigations,
inspiration=directive.inspiration,
source=directive.source,
notes=directive.notes,
)
def _playbook_payload(playbook: ExecutivePlaybook) -> ExecutivePlaybookInsight:
return ExecutivePlaybookInsight(
headline=playbook.headline,
focus=playbook.focus,
urgency=playbook.urgency,
north_star_metric=playbook.north_star_metric,
total_budget_usd=playbook.total_budget_usd,
expected_revenue_usd=playbook.expected_revenue_usd,
confidence=playbook.confidence,
directives=[_directive_payload(directive) for directive in playbook.directives],
summary=playbook.summary,
notes=playbook.notes,
)
def _scenario_projection_payload(projection: ScenarioProjection) -> ScenarioProjectionInsight:
return ScenarioProjectionInsight(
scenario=projection.scenario,
expected_revenue=projection.expected_revenue,
expected_roi=projection.expected_roi,
probability=projection.probability,
confidence=projection.confidence,
accelerators=projection.accelerators,
stabilizers=projection.stabilizers,
watchouts=projection.watchouts,
source=projection.source,
notes=projection.notes,
)
def _scenario_planning_payload(analysis: ScenarioAnalysis) -> ScenarioPlanningInsight:
return ScenarioPlanningInsight(
headline=analysis.headline,
summary=analysis.summary,
projections=[_scenario_projection_payload(proj) for proj in analysis.projections],
confidence=analysis.confidence,
accelerators=analysis.accelerators,
stabilizers=analysis.stabilizers,
source=analysis.source,
notes=analysis.notes,
)
@app.post("/intelligence/marketing/diagnostics", response_model=DiagnosticResponse)
def marketing_diagnostics(query: MarketingQuery) -> DiagnosticResponse:
engine = default_marketing_engine()
diagnostics = engine.diagnose(query.prompt)
return _diagnostics_payload(query.prompt, diagnostics)
@app.post("/intelligence/marketing/processes", response_model=MarketingProcessesResponse)
def marketing_processes(query: MarketingQuery) -> MarketingProcessesResponse:
engine = default_marketing_engine()
rag_campaigns = engine.recommend(query.prompt, query.limit)
rag_insights = [
_campaign_to_insight(engine, query.prompt, campaign) for campaign in rag_campaigns
]
rag_summary = engine.summarize(query.prompt, rag_campaigns)
ranked = engine.recommend_statistical(query.prompt, query.limit)
egg_experiments = engine.expansion_grid(query.prompt, ranked)
google_ads_data = engine.google_ads_enrichment(query.prompt, ranked, query.limit)
cj_affiliate = engine.cj_affiliate_enrichment(query.prompt, ranked, query.limit)
crypto_markets = engine.crypto_market_enrichment(query.prompt, query.limit)
stripe_plans = engine.stripe_checkout_enrichment(query.prompt, ranked, query.limit)
paypal_plans = engine.paypal_checkout_enrichment(query.prompt, ranked, query.limit)
influencer_partners = engine.influencer_collaboration_enrichment(
query.prompt, ranked, query.limit
)
amazon_listings = engine.amazon_marketplace_enrichment(query.prompt, ranked, query.limit)
ebay_listings = engine.ebay_marketplace_enrichment(query.prompt, ranked, query.limit)
aws_programs = engine.aws_cloud_enrichment(query.prompt, ranked, query.limit)
budget_plan = engine.budget_optimizer(query.prompt, ranked, query.limit)
automation_run = engine.automation_sprint(query.prompt, ranked, query.limit)
learning_recommendations = engine.learning_loop(query.prompt, ranked, query.limit)
competitive_signals = engine.competitive_landscape(query.prompt, ranked, query.limit)
excellence = engine.excellence_summary(
query.prompt,
ranked,
limit=query.limit,
rag=rag_campaigns,
egg=egg_experiments,
google_ads=google_ads_data,
cj_affiliate=cj_affiliate,
crypto_markets=crypto_markets,
stripe=stripe_plans,
paypal=paypal_plans,
influencers=influencer_partners,
amazon=amazon_listings,
ebay=ebay_listings,
aws=aws_programs,
budget=budget_plan,
automation=automation_run,
learning_loop=learning_recommendations,
competitive=competitive_signals,
)
scenario_analysis = engine.scenario_planning(
query.prompt,
ranked,
limit=query.limit,
budget=budget_plan,
google_ads=google_ads_data,
cj_affiliate=cj_affiliate,
amazon=amazon_listings,
ebay=ebay_listings,
aws=aws_programs,
stripe=stripe_plans,
paypal=paypal_plans,
influencers=influencer_partners,
crypto=crypto_markets,
)
playbook = engine.executive_playbook(
query.prompt,
ranked,
limit=query.limit,
rag=rag_campaigns,
egg=egg_experiments,
google_ads=google_ads_data,
cj_affiliate=cj_affiliate,
amazon=amazon_listings,
ebay=ebay_listings,
paypal=paypal_plans,
influencers=influencer_partners,
budget=budget_plan,
automation=automation_run,
learning_loop=learning_recommendations,
competitive=competitive_signals,
excellence=excellence,
)
amazon_listings = engine.amazon_marketplace_enrichment(query.prompt, ranked, query.limit)
aws_programs = engine.aws_cloud_enrichment(query.prompt, ranked, query.limit)
return MarketingProcessesResponse(
query=query.prompt,
rag=ProcessRun(process="rag", recommendations=rag_insights, summary=rag_summary),
egg=[_experiment_payload(experiment) for experiment in egg_experiments],
google_ads=[_google_ads_payload(performance) for performance in google_ads_data],
cj_affiliate=[_cj_affiliate_payload(rec) for rec in cj_affiliate],
crypto_markets=[_crypto_market_payload(snapshot) for snapshot in crypto_markets],
stripe=[_stripe_plan_payload(plan) for plan in stripe_plans],
paypal=[_paypal_plan_payload(plan) for plan in paypal_plans],
influencer_collaborations=[
_influencer_payload(partner) for partner in influencer_partners
],
amazon_marketplace=[_amazon_listing_payload(rec) for rec in amazon_listings],
ebay_marketplace=[_ebay_listing_payload(rec) for rec in ebay_listings],
aws_cloud=[_aws_revenue_payload(rec) for rec in aws_programs],
budget_optimizer=_budget_plan_payload(budget_plan),
automation=_automation_sprint_payload(automation_run),
learning_loop=[_learning_loop_payload(rec) for rec in learning_recommendations],
competitive_landscape=[_competitive_signal_payload(signal) for signal in competitive_signals],
excellence=_excellence_payload(excellence),
executive_playbook=_playbook_payload(playbook),
scenario_planning=_scenario_planning_payload(scenario_analysis),
amazon_marketplace=[_amazon_listing_payload(rec) for rec in amazon_listings],
aws_cloud=[_aws_revenue_payload(rec) for rec in aws_programs],
)