caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

194 lines
7.5 KiB
Python

"""Hook-script preview for a public App Store / Play listing.
Three opening-line hooks, written strictly from the listing's own title,
description, genre and rating. Routed through the same Railyard Relay
OpenAI-compatible surface as :mod:`app.domains.appaudit.rewrite`, with a
deterministic, offline fallback when Relay is unavailable. This is a free
*preview* only — no voiceover, no avatar, no render — so it never invents a
capability the caller has not unlocked yet (claims rules: describe what
ships before sign-up, nothing more).
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from typing import Callable, Optional
from app.domains.railyard.config import RailyardEnv, get_relay_config
LINE_MAX = 90
ANGLE_MAX = 140
HOOK_COUNT = 3
DEFAULT_MODEL = "tensorzero::model_name::anthropic::claude-haiku-4-5"
_TIMEOUT_S = 20.0
ChatFn = Callable[[str, str, str, Optional[str]], str]
@dataclass(frozen=True)
class Hook:
line: str
angle: str
@dataclass(frozen=True)
class HookPreview:
hooks: tuple[Hook, ...]
source: str # "relay" | "fallback"
def _clip(text: str, limit: int) -> str:
text = re.sub(r"\s+", " ", text or "").strip().strip('"\'')
return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0].rstrip(",;: ")
def _first_sentence(description: str) -> str:
sentence = re.split(r"(?<=[.!?])\s+|\n+", (description or "").strip(), maxsplit=1)[0]
return sentence or description or ""
def fallback_hook_preview(title: str, description: str, genre: str, store: str) -> HookPreview:
"""Deterministic hooks built only from the listing's own facts.
Three honest angles any app-install ad can open on without inventing a
feature: the task the app does, the "stop doing it the old way" framing,
and a direct install call built from the store badge the user already
sees on the listing.
"""
benefit = _clip(_first_sentence(description), LINE_MAX) or _clip(title, LINE_MAX)
category = genre or "this category"
store_label = "the App Store" if store == "app_store" else "Google Play"
hooks = (
Hook(
line=_clip(f"{title}: {benefit}" if benefit and benefit.lower() != title.lower() else f"Meet {title}.", LINE_MAX),
angle="Leads with the app's own description, so the hook never claims more than the listing already says.",
),
Hook(
line=_clip(f"I deleted every other {category.lower()} app after this one.", LINE_MAX),
angle="A replacement story that positions the app against its category rather than a named rival.",
),
Hook(
line=_clip(f"Here's {title}, live on {store_label}, in the first three seconds.", LINE_MAX),
angle="Shows the app and the store badge immediately, which install ads with a weak opening lose people on.",
),
)
return HookPreview(hooks=hooks, source="fallback")
def _build_prompt(title: str, description: str, genre: str, rating: float | None, store: str) -> str:
store_label = "App Store" if store == "app_store" else "Google Play"
facts = [
f"App name: {title}",
f"Store: {store_label}",
f"Category: {genre}" if genre else "",
f"Rating: {rating}/5" if rating else "",
f"Description (first 600 characters): {description[:600]}",
]
return "\n".join(
[
"You write opening hook lines (the first spoken line) for short vertical app-install video ads.",
"Use ONLY the facts given below. Never invent features, numbers, awards or reviews not present in the facts.",
f"Write exactly {HOOK_COUNT} different hook lines (each at most {LINE_MAX} characters) with three different angles:",
"1) the core task the app does, stated plainly; 2) a replacement/before-after story about the category, naming no rival app by name; 3) a curiosity opener about one feature from the description.",
f"For each hook also write a one-sentence 'angle' (at most {ANGLE_MAX} characters) explaining why that opening works.",
"No emoji. No quotes around the output. Plain English. Never name a competing app.",
'Return ONLY JSON: {"hooks":[{"line":"...","angle":"..."},{"line":"...","angle":"..."},{"line":"...","angle":"..."}]}',
"",
"<facts>",
"\n".join(f for f in facts if f),
"</facts>",
]
)
def _default_chat(prompt: str, base_url: str, api_key: str, model: str | None) -> str:
import httpx
response = httpx.post(
f"{base_url}/chat/completions",
json={
"model": model or DEFAULT_MODEL,
"max_tokens": 400,
"temperature": 0.7,
"messages": [{"role": "user", "content": prompt}],
},
headers={"Authorization": f"Bearer {api_key}"} if api_key else {},
timeout=_TIMEOUT_S,
)
response.raise_for_status()
data = response.json()
return (data.get("choices") or [{}])[0].get("message", {}).get("content", "") or ""
def _parse(text: str) -> tuple[Hook, ...] | None:
match = re.search(r"\{[\s\S]*\}", text or "")
if not match:
return None
try:
data = json.loads(match.group(0))
except ValueError:
return None
raw_hooks = data.get("hooks")
if not isinstance(raw_hooks, list) or not raw_hooks:
return None
hooks: list[Hook] = []
for entry in raw_hooks[:HOOK_COUNT]:
if not isinstance(entry, dict):
continue
line = _clip(str(entry.get("line") or ""), LINE_MAX)
angle = _clip(str(entry.get("angle") or ""), ANGLE_MAX)
if not line or not angle:
continue
hooks.append(Hook(line=line, angle=angle))
if len(hooks) < HOOK_COUNT:
return None
return tuple(hooks)
def _relay_env(env: Optional[RailyardEnv]) -> RailyardEnv:
"""Accept the ``RAILYARD_RELAY_*`` names the box env uses (same fallback as
``app.domains.appaudit.rewrite``) without changing the shared Railyard
config other features read."""
source = env if env is not None else os.environ
return {
**source,
"RELAY_URL": source.get("RELAY_URL") or source.get("RAILYARD_RELAY_URL") or "",
"RELAY_API_KEY": source.get("RELAY_API_KEY") or source.get("RAILYARD_RELAY_API_KEY") or "",
}
def generate_hook_preview(
title: str,
description: str,
genre: str,
rating: float | None,
store: str,
*,
env: Optional[RailyardEnv] = None,
chat: ChatFn = _default_chat,
) -> HookPreview:
"""Relay-backed hook preview when configured, else the deterministic fallback.
Any Relay failure (not configured, network error, unusable output) falls
back silently to :func:`fallback_hook_preview` — the preview always
returns three usable hooks.
"""
config = get_relay_config(_relay_env(env))
if not config.configured or not config.openai_base_url:
return fallback_hook_preview(title, description, genre, store)
prompt = _build_prompt(title, description, genre, rating, store)
try:
text = chat(prompt, config.openai_base_url, config.api_key or "", None)
except Exception: # noqa: BLE001 - any Relay failure degrades to the fallback
return fallback_hook_preview(title, description, genre, store)
hooks = _parse(text)
if hooks is None:
return fallback_hook_preview(title, description, genre, store)
return HookPreview(hooks=hooks, source="relay")
__all__ = ["HOOK_COUNT", "Hook", "HookPreview", "fallback_hook_preview", "generate_hook_preview"]