Spaces:
Sleeping
Sleeping
feat: wow_anchors + diversity + custom product modal + stronger reasoning strip
Browse filesFiles changed (11)
- .pytest_cache/v/cache/lastfailedAdded+1
- aether_ad/core/engine.py+58-9
- aether_ad/core/wow_anchors.pyAdded+47
- aether_ad/llm/base.py+31-3
- aether_ad/llm/fireworks_kimi.py+9-6
- aether_ad/llm/prompts/apply_collision.txt+27-10
- aether_ad/llm/prompts/generate_product_genome.txtAdded+58
- app.py+170-23
- static/app.js+196-11
- static/index.html+71-2
- static/styles.css+189
1{}3 unmodified lines4567893 unmodified lines13141516171833 unmodified lines52535455565728 unmodified lines8687888990919293949596979815 unmodified lines1141151161171181198 unmodified lines1281291301311321331341354 unmodified lines14014114214314414559 unmodified lines2052062072082092104 unmodified lines2152162172182192203 unmodified lines2242252262272282292303 unmodified linesimport loggingimport randomfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Literal3 unmodified linesfrom aether_ad.blending.spaces import BlendingSpaceSet, build_spacesfrom aether_ad.core.collision import ALL_RULES, CollisionRule, sample_rulesfrom aether_ad.core.narrative import Beat, PixarSpineRendererfrom aether_ad.core.wow_filter import CreativityScore, WowFilterif TYPE_CHECKING:33 unmodified linesbeats: list[BeatModel] = Field(default_factory=list)raw_collision: str | None = Noneraw_spine: str | None = Noneclass ScoredSeed(BaseModel):28 unmodified linesspaces = build_spaces(product, tension, persona_text)log.info("stage=encoding inputs=%d generic=%d", len(spaces.inputs), len(spaces.generic))plans = []for i in range(self.seed_count_per_run):n_rules = self.rng.randint(*rules_per_seed)rules = sample_rules(n_rules, self.rng)atom = self.rng.choice(product.functional_atoms)potential = self.rng.choice(atom.abstract_potentials)plans.append({"index": i, "rules": rules, "atom": atom, "potential": potential})log.info("stage=incubation_planning count=%d", len(plans))raw_seeds = self._parallel_build_concepts(15 unmodified linesscored.sort(key=lambda x: x.score.final, reverse=True)return scored[: self.keep_top_k]def _parallel_build_concepts(self,plans: list[dict],8 unmodified linesrules = plan["rules"]atom = plan["atom"]potential = plan["potential"]concept, raw = self._apply_rules(spaces, rules, product, tension, persona_text, atom, potential)return AdSeed(seed_id=f"{product.product_id}_{tension.id}_{i:03d}",4 unmodified linesconcept=concept,duration=duration,raw_collision=raw,)if self.llm is None or len(plans) <= 1:59 unmodified linespersona_text: str,atom,potential: str,) -> tuple[str, str | None]:if self.llm is not None:try:4 unmodified linestension=tension,persona=persona_text,product=product,)return concept, rawexcept Exception as e:3 unmodified linesreturn (f"[{atom.name}] '{potential}' → "f"{tension.greimas_square.S1} vs {tension.greimas_square.S2} 충돌 "f"({persona_text}). 규칙: {rule_fragments}",None,)3 unmodified lines456789103 unmodified lines1415161718192033 unmodified lines5455565758596028 unmodified lines8990919293949515 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631648 unmodified lines1731741751761771781791801814 unmodified lines18618718818919019119259 unmodified lines2522532542552562572584 unmodified lines2632642652662672682693 unmodified lines2732742752762772782793 unmodified linesimport loggingimport randomfrom collections import Counterfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Literal3 unmodified linesfrom aether_ad.blending.spaces import BlendingSpaceSet, build_spacesfrom aether_ad.core.collision import ALL_RULES, CollisionRule, sample_rulesfrom aether_ad.core.narrative import Beat, PixarSpineRendererfrom aether_ad.core.wow_anchors import pick_anchorfrom aether_ad.core.wow_filter import CreativityScore, WowFilterif TYPE_CHECKING:33 unmodified linesbeats: list[BeatModel] = Field(default_factory=list)raw_collision: str | None = Noneraw_spine: str | None = Nonewow_anchor: str | None = Noneclass ScoredSeed(BaseModel):28 unmodified linesspaces = build_spaces(product, tension, persona_text)log.info("stage=encoding inputs=%d generic=%d", len(spaces.inputs), len(spaces.generic))plans = self._build_diverse_plans(product, rules_per_seed)log.info("stage=incubation_planning count=%d", len(plans))raw_seeds = self._parallel_build_concepts(15 unmodified linesscored.sort(key=lambda x: x.score.final, reverse=True)return scored[: self.keep_top_k]def _build_diverse_plans(self,product: "ProductGenome",rules_per_seed: tuple[int, int],) -> list[dict]:"""Build per-seed plans with forced diversity along 3 axes:- wow_anchor: each seed gets a different anchor from WOW_ANCHORS- atom: atoms distributed as evenly as possible across seeds- rule combination: no two seeds share the same sorted rule_id tuple"""atoms = product.functional_atomsatom_use: Counter[str] = Counter()seen_combos: set[tuple[str, ...]] = set()plans: list[dict] = []for i in range(self.seed_count_per_run):# --- atom: pick the least-used one; tie-break randommin_use = min(atom_use.get(a.id, 0) for a in atoms)atom_candidates = [a for a in atoms if atom_use.get(a.id, 0) == min_use]atom = self.rng.choice(atom_candidates)atom_use[atom.id] += 1# --- potential: vary across the atom's abstract_potentialspotential = self.rng.choice(atom.abstract_potentials)# --- rules: sample up to 12 times to find an unseen comborules = sample_rules(self.rng.randint(*rules_per_seed), self.rng)for _ in range(12):key = tuple(sorted(r.rule_id for r in rules))if key not in seen_combos:seen_combos.add(key)breakrules = sample_rules(self.rng.randint(*rules_per_seed), self.rng)# --- wow anchor: rotated per-seed from the shuffled poolanchor = pick_anchor(i, self.rng)plans.append({"index": i,"rules": rules,"atom": atom,"potential": potential,"wow_anchor": anchor,})return plansdef _parallel_build_concepts(self,plans: list[dict],8 unmodified linesrules = plan["rules"]atom = plan["atom"]potential = plan["potential"]anchor = plan["wow_anchor"]concept, raw = self._apply_rules(spaces, rules, product, tension, persona_text, atom, potential, anchor)return AdSeed(seed_id=f"{product.product_id}_{tension.id}_{i:03d}",4 unmodified linesconcept=concept,duration=duration,raw_collision=raw,wow_anchor=anchor,)if self.llm is None or len(plans) <= 1:59 unmodified linespersona_text: str,atom,potential: str,wow_anchor: str,) -> tuple[str, str | None]:if self.llm is not None:try:4 unmodified linestension=tension,persona=persona_text,product=product,wow_anchor=wow_anchor,)return concept, rawexcept Exception as e:3 unmodified linesreturn (f"[{atom.name}] '{potential}' → "f"{tension.greimas_square.S1} vs {tension.greimas_square.S2} 충돌 "f"({persona_text}). 앵커: {wow_anchor}. 규칙: {rule_fragments}",None,)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Per-seed wow anchors — short imperative directives that force divergent,non-cliche scene generation. Rotated across seeds to guarantee diversity.
Design note: even with the same product + tension + persona, injecting onedistinct anchor per seed pushes the LLM into a different creative basin oneach call. Empirically this is the single biggest lever against "all seedsfeel the same" convergence."""
from __future__ import annotations
WOW_ANCHORS: list[str] = [ "이 장면에서 물리법칙(중력·시간·인과 중 하나)이 눈에 보이게 깨진다.", "제품이 주인공보다 먼저 행동하는 순간을 만든다 — 제품에게 의지를 부여하라.", "전체 컷이 무음이다. 대사·나레이션·효과음 0초, 침묵만으로 감정을 끌고 간다.", "화자는 인간이 아니다 — 제품 부품 자신이 1인칭으로 서사를 이끈다.", "결말이 시작으로 되감기며 루프를 만든다. 시청자는 '다시 보기'를 하고 싶어진다.", "초반에 '악당'으로 제시된 인물이 마지막에 가장 도덕적임이 드러나는 반전.", "제품이 화면에 한 번도 직접 등장하지 않는다. 그림자·소리·자국·빈자리만.", "시간이 거꾸로 흐르는 구간이 최소 3초 이상 있어야 한다.", "관객이 마지막 장면에서 이 광고의 '장르'를 재해석하게 된다 (로맨스→호러, 코미디→비극 등).", "한 컷의 의미가 마지막 컷에 의해 180도 뒤집힌다 (반전 편집).", "스케일이 극단으로 전복된다 — 지구만 한 제품, 쌀알만 한 주인공, 또는 그 역.", "하나의 감각이 다른 감각으로 번역되어 나타난다 (청각→시각, 촉각→청각 등).", "주인공이 제품에 '사용되는' 구조로 뒤집힌다 (agency swap).", "광고 속에 '광고를 찍고 있는 카메라'가 등장하는 액자식 재귀 구조.", "금기 주제(죽음·가난·질병·고독)를 정면으로 다루되 마지막에 존엄/사랑으로 착지.", "브랜드명·로고를 언어적으로 절대 노출하지 말고 실루엣·빈 공간으로만 각인시킨다.", "마지막 1초가 의도적으로 미완성이다 — 생략된 부분을 시청자가 채운다.", "같은 배우가 3개 이상 다른 역할로 1인 다역 교차 출연한다.", "매 비트마다 배경 색 팔레트가 단 하나의 색으로 붕괴된다 (mono-scene).", "제품의 기능이 현실 세계에 문자 그대로 작동한다 ('방수' → 눈물이 피부를 뚫지 못함).", "특정 세대·계급의 아픔이 제품에 거울처럼 반사된다 (세대 시네마).", "결말에서 주인공이 아닌 배경 인물이 진짜 주인공이었음이 밝혀진다.", "광고가 기존 유명 장르 관습을 명백하게 배반한다 (명절 광고의 모든 클리셰를 뒤집는다).", "대사 한 줄이 3번 반복되며 매번 의미가 달라진다.",]
def pick_anchor(index: int, rng) -> str: """Pick an anchor for the i-th seed. Shuffles per-run to rotate.
Uses the provided rng so that the same rng_seed reproduces the same sequence. """ shuffled = WOW_ANCHORS.copy() rng.shuffle(shuffled) return shuffled[index % len(shuffled)]35 unmodified lines36373839404142434445464729 unmodified lines7778798081828384858664 unmodified lines15115215315415515612 unmodified lines16917017117217317417517635 unmodified lines_REASONING_STARTERS = ("사용자는", "사용자가", "분석:", "역할:", "입력 공간", "제약 조건","핵심 요구사항", "주요 요구사항", "요구사항 분석", "입력 요소","The user is", "The user wants", "The user asked","Let me", "I need to", "I'll ", "I will ", "I should","**역할**", "**입력**", "**제약**", "**출력**","역할 분석", "분석해보", "정리해보", "요청을",)_SCENE_STARTERS = ("어느 ", "밤 ", "낮 ", "새벽 ", "아침 ", "저녁 ", "오후 ","교실 ", "복도 ", "지하철 ", "버스 ", "옥상 ", "병실 ", "골목 ",29 unmodified linesreturn Trueif any(first.startswith(m) for m in _REASONING_STARTERS):return Trueif first.startswith(("| ", "|", "- ", "1. ", "2. ", "3. ", "•")):if block.count("\n") < 2:return Trueif re.match(r"^\*\*[^*]+\*\*\s*:", first):return Truereturn False64 unmodified linestension: "TensionArchetype",persona: str,product: "ProductGenome",) -> tuple[str, str]:"""Return (cleaned_concept, raw_response)."""tpl = _load_prompt("apply_collision.txt")12 unmodified linespayoff=tension.emotional_payoff,persona=persona,rules="\n".join(f"- [{r.rule_id}] {r.name}: {r.llm_prompt_fragment}" for r in rules),)raw = self.complete(prompt, max_tokens=8192, temperature=0.85)cleaned, _ = strip_reasoning(raw)if not cleaned:cleaned = f"[LLM reasoning only — no narrative extracted] ({atom.name} · {potential})"35 unmodified lines363738394041424344454647484950515253545556575829 unmodified lines88899091929394959697989910010110210310410510610710810911011111264 unmodified lines17717817918018118218312 unmodified lines19619719819920020120220320435 unmodified lines_REASONING_STARTERS = ("사용자는", "사용자가", "분석:", "역할:", "입력 공간", "제약 조건","핵심 요구사항", "주요 요구사항", "요구사항 분석", "입력 요소","적용:", "접근:", "전략:", "선택된","The user is", "The user wants", "The user asked","Let me", "Let's", "Thinking", "I need to", "I'll ", "I will ", "I should","Looking at", "Actually", "The cultural", "The culturally","Maybe ", "Or: ", "No, that", "Reverse this", "Analysis","Okay,", "OK,", "Alright,", "First,", "So the","**역할**", "**입력**", "**제약**", "**출력**","**Role**", "**Input**", "**Output**","역할 분석", "분석해보", "정리해보", "요청을",)_ENGLISH_REASONING_TRIGGERS = (" the user ", " let me ", "thinking", "maybe ", " actually ","reverse this", "no, that", " looking at ", " analysis ","okay,", "alright,", "first,", "so the ", "let's ",)_SCENE_STARTERS = ("어느 ", "밤 ", "낮 ", "새벽 ", "아침 ", "저녁 ", "오후 ","교실 ", "복도 ", "지하철 ", "버스 ", "옥상 ", "병실 ", "골목 ",29 unmodified linesreturn Trueif any(first.startswith(m) for m in _REASONING_STARTERS):return True# Collision rule id header: "R05:", "R01.", "R12 -"if re.match(r"^R\d{2}[:.\-\s]", first):return True# Markdown "**Heading**:" patternif re.match(r"^\*\*[^*]+\*\*\s*:", first):return True# Lists without narrative structureif first.startswith(("| ", "|", "- ", "1. ", "2. ", "3. ", "•")):if block.count("\n") < 2:return True# High ASCII ratio in opening chars — likely English reasoningopener = first[:120]if opener:ascii_ratio = sum(1 for c in opener if c.isascii()) / len(opener)if ascii_ratio > 0.85 and len(opener) > 30:return True# English reasoning triggers anywhere in the blocklow = block.lower()if sum(1 for trig in _ENGLISH_REASONING_TRIGGERS if trig in low) >= 2:return Truereturn False64 unmodified linestension: "TensionArchetype",persona: str,product: "ProductGenome",wow_anchor: str = "장면에 예측 불가능한 반전이 반드시 있어야 한다.",) -> tuple[str, str]:"""Return (cleaned_concept, raw_response)."""tpl = _load_prompt("apply_collision.txt")12 unmodified linespayoff=tension.emotional_payoff,persona=persona,rules="\n".join(f"- [{r.rule_id}] {r.name}: {r.llm_prompt_fragment}" for r in rules),wow_anchor=wow_anchor,)raw = self.complete(prompt, max_tokens=8192, temperature=1.0)cleaned, _ = strip_reasoning(raw)if not cleaned:cleaned = f"[LLM reasoning only — no narrative extracted] ({atom.name} · {potential})"
35 unmodified lines36373839404142434445464735 unmodified linesself._client = httpx.Client(timeout=timeout)_SYSTEM_PROMPT = ("You are AETHER-Ad Genesis. Respond in Korean. ""Output ONLY the requested final answer — no internal reasoning, ""no '사용자는…/The user is…' preamble, no meta commentary, ""no constraint summaries. Start directly with the answer. ""Do not fabricate real brands. Keep content safe ""(no self-harm, minority harm, explicit sexual content, hate speech).")def complete(self, prompt: str, max_tokens: int = 4096, temperature: float = 0.6) -> str:35 unmodified lines36373839404142434445464748495035 unmodified linesself._client = httpx.Client(timeout=timeout)_SYSTEM_PROMPT = ("You are AETHER-Ad Genesis. Output ONLY the requested final answer — ""no chain-of-thought, no 'Let me think', no 'R05: Cultural betrayal. ""Maybe...', no 'The user is...', no analysis blocks, no English ""deliberation. Korean responses only, starting directly with the ""narrative/answer. Never prepend rule IDs (R01-R15) as headers. ""Never use markdown bold/headings. Do not fabricate real brands. ""Keep content safe (no self-harm, minority harm, explicit sexual ""content, hate speech). If you catch yourself writing reasoning in ""English or Korean, stop and restart with the Korean final answer.")def complete(self, prompt: str, max_tokens: int = 4096, temperature: float = 0.6) -> str:
123456789101112131415161712 unmodified lines3031323334[역할] 당신은 AETHER-Ad Genesis의 Collision 엔진이다.Fauconnier-Turner Conceptual Blending에 따라 두 입력 공간을 교차 투사하여창발적 구조를 가진 광고 장면 1건을 생성한다.[엄수 규칙]1. 사고 과정·분석·제약 정리·입력 공간 설명 등 메타 주석을 절대 쓰지 말 것.2. "사용자는…", "사용자가…", "제약 조건…", "입력 공간…", "**역할**…" 같은자기 지시·요약 텍스트 일체 금지.3. 첫 글자부터 곧장 "장면 묘사"로 시작. 서사만.4. 출력은 **한국어 한 문단(3-5문장)**. 줄바꿈/리스트/헤더/굵게/백틱 금지.5. 부품 '{atom_name}'이 서사의 전환점으로 반드시 한 번 등장.6. 실존 브랜드 금지. '{brand}' 외 언급 금지.7. 장애·성별·인종 비하, 미성년 성적 묘사, 자해 직접 묘사 금지.8. 광고 카피(한 줄 슬로건) 쓰지 말 것.[입력 공간 I1 — 제품]- 제품: {product_id} · 브랜드: {brand} · 카테고리: {category}12 unmodified lines[적용할 Collision Rule(s)]{rules}[출력]장면 묘사 문단 하나. 첫 글자가 이미 서사의 첫 이미지여야 함. 다른 텍스트 일체 금지.123456789101112131415161718192021222324252627282912 unmodified lines42434445464748495051[역할] 당신은 AETHER-Ad Genesis의 Collision 엔진이다.Fauconnier-Turner Conceptual Blending에 따라 두 입력 공간을 교차 투사하여창발적 구조를 가진 "시청자가 '와!' 하고 숨을 쉬는 광고 장면" 하나를 생성한다.[엄수 규칙 — 형식]1. 사고 과정·분석·제약 정리·입력 공간 설명 등 메타 주석 절대 쓰지 말 것.2. "사용자는…", "사용자가…", "제약 조건…", "**역할**…" 같은 자기 지시 금지.3. 첫 글자부터 곧장 "장면 묘사"로 시작. 서사만.4. 출력은 **한국어 한 문단(3-5문장)**. 줄바꿈/리스트/헤더/굵게/백틱 금지.5. 광고 카피(한 줄 슬로건) 금지.[엄수 규칙 — 와우 포인트]- 장면 안에 물리/인과/도덕 규칙을 "눈에 보이게" 깨는 순간이 반드시 한 번 이상.- 관객이 첫 3초에 예측한 결말이 마지막 3초에 뒤집혀야 한다 (prediction gap).- **아래 '와우 앵커'는 이번 seed 전용 설계 지시다. 반드시 서사에 내재화시킨다.**[와우 앵커 — 이번 seed 전용]{wow_anchor}[엄수 규칙 — 클리셰 금지]다음 진부한 클리셰는 즉시 폐기하고 다르게 쓴다:- "가족 사진을 보며 눈물" / "할머니·할아버지의 죽음으로 감동 마무리"- "졸업식·결혼식 대기실에서의 포옹" / "연인의 뒤돌아보는 미소"- "빗속에서 우산을 씌워주는 장면" / "카페 창밖을 보며 추억"- "아이가 아버지의 구두를 신어보는 장면" / "일기장에 쓰는 편지"- 시계 제품에서 흔한: "초침 소리와 눈물 교차" 단독 사용 금지 — 반드시 위 와우 앵커와 결합.[입력 공간 I1 — 제품]- 제품: {product_id} · 브랜드: {brand} · 카테고리: {category}12 unmodified lines[적용할 Collision Rule(s)]{rules}[제약]- 실존 브랜드 금지. '{brand}' 외 언급 금지.- 장애·성별·인종 비하, 미성년 성적 묘사, 자해 직접 묘사 금지.- 부품 '{atom_name}'이 서사의 전환점으로 반드시 한 번 등장.[출력]장면 묘사 한 문단. 첫 글자가 이미 서사의 첫 이미지여야 함. 다른 텍스트 일체 금지.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758[역할] 당신은 AETHER-Ad Genesis의 Genome Generator이다.사용자의 짧은 제품 설명을 받아 완전한 ProductGenome JSON 하나만 생성한다.
[입력]- 브랜드: {brand}- 카테고리: {category}- 가격대: {price_tier}- product_id (snake_case, 영문 소문자+숫자+언더스코어만): {product_id}- 부품 목록:{parts}
[엄수 규칙 — 형식]1. **출력은 오직 JSON 객체 하나만**. 다른 텍스트 일체 금지 (주석·설명·사고 과정 금지).2. 첫 글자는 `{{` 마지막 글자는 `}}`.3. 응답은 UTF-8 한국어 기반. 실존 브랜드명 사용 금지.
[엄수 규칙 — 내용]- 각 부품을 `functional_atom` 하나로 변환.- 각 atom의 `id`는 `F01_xxx` 형식 (F + 2자리 숫자 + 영문 snake).- 각 atom의 `abstract_potentials` **정확히 3개** — 은유·상징·문화적 함의 (기능 반복 금지).- 각 atom의 `scamper_variants`에 S/C/A/M/P/E/R 각 **정확히 1개**씩 (한국어 짧게).- `narrative_affordance`: "low" | "medium" | "high" 중 하나.- `taboo_proximity`: "none" | "low" | "medium" | "high" 중 하나.- `sensory_signatures`에 visual/auditory/tactile/olfactory/kinesthetic 각 1개.- `cultural_symbols.korean` 2개, `cultural_symbols.global` 1개.- `ludic_potential` 2개.
[출력 스키마]{{ "product_id": "{product_id}", "brand": "{brand}", "category": "{category}", "price_tier": "{price_tier}", "functional_atoms": [ {{ "id": "F01_xxx", "name": "부품명", "literal": "문자 그대로의 기능", "abstract_potentials": ["...", "...", "..."], "scamper_variants": {{ "S": [".."], "C": [".."], "A": [".."], "M": [".."], "P": [".."], "E": [".."], "R": [".."] }}, "narrative_affordance": "high", "taboo_proximity": "none" }} ], "physical_parts": ["...", "..."], "sensory_signatures": {{ "visual": ["..."], "auditory": ["..."], "tactile": ["..."], "olfactory": ["..."], "kinesthetic": ["..."] }}, "cultural_symbols": {{ "korean": ["..", ".."], "global": [".."] }}, "ludic_potential": ["...", "..."], "taboo_proximity": "none"}}
JSON 객체 하나만 출력.1 unmodified line234567891011 unmodified lines2223242526272811 unmodified lines40414243444523 unmodified lines69707172737475767778798081828384858687888990919293949518 unmodified lines1141151161171181191201211221231241251261271281291301 unmodified linefrom __future__ import annotationsimport loggingimport osimport sysfrom pathlib import Pathfrom typing import Any, Literal11 unmodified linesfrom aether_ad.core.collision import ALL_RULES # noqa: E402from aether_ad.core.context import load_context # noqa: E402from aether_ad.core.engine import GenesisEngine # noqa: E402from aether_ad.core.genome import load_genome # noqa: E402from aether_ad.llm.fireworks_kimi import FireworksKimiBackend # noqa: E402from aether_ad.llm.hf_inference import HFInferenceBackend # noqa: E402from aether_ad.version import __version__ # noqa: E40211 unmodified linesCONTEXT = load_context(TENSIONS_PATH)app = FastAPI(title="AETHER-Ad Genesis", version=__version__)app.add_middleware(CORSMiddleware,23 unmodified lines}@app.get("/api/products")async def products() -> list[dict[str, Any]]:items: list[dict[str, Any]] = []for p in sorted(PRODUCTS_DIR.glob("*.json")):try:g = load_genome(p)items.append({"product_id": g.product_id,"brand": g.brand,"category": g.category,"price_tier": g.price_tier,"atom_count": len(g.functional_atoms),"atoms": [{"id": a.id, "name": a.name} for a in g.functional_atoms],})except Exception as e:log.warning("skip product %s: %s", p, e)return items@app.get("/api/tensions")async def tensions() -> list[dict[str, Any]]:return [t.model_dump() for t in CONTEXT.tension_archetypes]18 unmodified lines@app.post("/api/generate")async def generate(req: GenerateRequest) -> dict[str, Any]:product_path: Path | None = Nonefor p in PRODUCTS_DIR.glob("*.json"):try:if load_genome(p).product_id == req.product_id:product_path = pbreakexcept Exception:continueif product_path is None:raise HTTPException(status_code=404, detail=f"Product '{req.product_id}' not found")genome = load_genome(product_path)llm = Nonetry:1 unmodified line23456789101112131411 unmodified lines262728293031323311 unmodified lines454647484950515253545556575859606162636465666768697071727374757623 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125218 unmodified lines2712722732742752762771 unmodified linefrom __future__ import annotationsimport jsonimport loggingimport osimport reimport sysimport threadingimport timefrom pathlib import Pathfrom typing import Any, Literal11 unmodified linesfrom aether_ad.core.collision import ALL_RULES # noqa: E402from aether_ad.core.context import load_context # noqa: E402from aether_ad.core.engine import GenesisEngine # noqa: E402from aether_ad.core.genome import ProductGenome, load_genome # noqa: E402from aether_ad.llm.base import _load_prompt, strip_reasoning # noqa: E402from aether_ad.llm.fireworks_kimi import FireworksKimiBackend # noqa: E402from aether_ad.llm.hf_inference import HFInferenceBackend # noqa: E402from aether_ad.version import __version__ # noqa: E40211 unmodified linesCONTEXT = load_context(TENSIONS_PATH)# In-memory custom products (per Space lifetime). Replace with a persistent store later.CUSTOM_PRODUCTS: dict[str, ProductGenome] = {}_CUSTOM_LOCK = threading.Lock()def _slugify(text: str) -> str:"""Turn an arbitrary Korean/English string into a snake_case ASCII id."""s = re.sub(r"[^A-Za-z0-9]+", "_", (text or "").strip()).strip("_").lower()if not s or not re.match(r"^[a-z]", s):s = "custom_" + (s or str(int(time.time())))return s[:40]def _resolve_product(product_id: str) -> ProductGenome:"""Resolve a product_id to a ProductGenome from disk or in-memory custom store."""if product_id in CUSTOM_PRODUCTS:return CUSTOM_PRODUCTS[product_id]for p in PRODUCTS_DIR.glob("*.json"):try:g = load_genome(p)if g.product_id == product_id:return gexcept Exception:continueraise HTTPException(status_code=404, detail=f"Product '{product_id}' not found")app = FastAPI(title="AETHER-Ad Genesis", version=__version__)app.add_middleware(CORSMiddleware,23 unmodified lines}def _genome_summary(g: ProductGenome, custom: bool = False) -> dict[str, Any]:return {"product_id": g.product_id,"brand": g.brand,"category": g.category,"price_tier": g.price_tier,"atom_count": len(g.functional_atoms),"atoms": [{"id": a.id, "name": a.name} for a in g.functional_atoms],"custom": custom,}@app.get("/api/products")async def products() -> list[dict[str, Any]]:items: list[dict[str, Any]] = []for p in sorted(PRODUCTS_DIR.glob("*.json")):try:items.append(_genome_summary(load_genome(p), custom=False))except Exception as e:log.warning("skip product %s: %s", p, e)with _CUSTOM_LOCK:for g in CUSTOM_PRODUCTS.values():items.append(_genome_summary(g, custom=True))return itemsclass QuickProductPart(BaseModel):name: strdescription: str = ""class QuickProductForm(BaseModel):brand: str = Field(min_length=1, max_length=40)category: str = Field(min_length=1, max_length=60)price_tier: Literal["budget", "mid", "premium", "luxury"] = "premium"parts: list[QuickProductPart] = Field(min_length=2, max_length=8)backend: Literal["fireworks", "hf"] = "fireworks"model: str | None = Nonedef _extract_json_object(text: str) -> dict:"""Pull the first balanced {...} block out of an LLM response."""s = (text or "").strip()# fence-code stripm = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", s)if m:s = m.group(1)start = s.find("{")if start < 0:raise ValueError("no JSON object found in LLM response")depth = 0for i in range(start, len(s)):c = s[i]if c == "{":depth += 1elif c == "}":depth -= 1if depth == 0:return json.loads(s[start : i + 1])raise ValueError("unbalanced JSON braces in LLM response")@app.post("/api/products/expand")async def expand_product(form: QuickProductForm) -> dict[str, Any]:"""Expand a short form into a full ProductGenome via LLM, register in-memory."""if form.backend == "fireworks" and not os.getenv("FIREWORKS_API_KEY"):raise HTTPException(status_code=400, detail="FIREWORKS_API_KEY not set")if form.backend == "hf" and not os.getenv("HF_TOKEN"):raise HTTPException(status_code=400, detail="HF_TOKEN not set")try:llm = (FireworksKimiBackend(model=form.model or None)if form.backend == "fireworks"else HFInferenceBackend(model=form.model or None))except Exception as e:log.exception("backend init failed")raise HTTPException(status_code=500, detail=f"Backend init failed: {e}") from epid = _slugify(form.brand)# ensure uniquenessbase = pidn = 1with _CUSTOM_LOCK:while pid in CUSTOM_PRODUCTS:n += 1pid = f"{base}_{n}"parts_block = "\n".join(f"- {p.name.strip()}: {p.description.strip()}" for p in form.parts)prompt = _load_prompt("generate_product_genome.txt").format(brand=form.brand,category=form.category,price_tier=form.price_tier,product_id=pid,parts=parts_block,)try:raw = await run_in_threadpool(llm.complete, prompt, 16384, 0.55)except Exception as e:log.exception("llm.complete failed for genome expansion")raise HTTPException(status_code=502, detail=f"LLM failed: {e}") from ecleaned, _ = strip_reasoning(raw)text = cleaned or rawtry:data = _extract_json_object(text)except Exception as e:log.warning("genome JSON parse failed: %s\n--raw--\n%s", e, raw[:2000])raise HTTPException(status_code=422,detail=f"LLM did not return valid JSON ({e}). Try again or adjust parts.",) from e# Normalize required defaultsdata["product_id"] = piddata.setdefault("brand", form.brand)data.setdefault("category", form.category)data.setdefault("price_tier", form.price_tier)try:genome = ProductGenome.model_validate(data)except Exception as e:log.warning("genome validation failed: %s\n--data--\n%s", e, json.dumps(data)[:2000])raise HTTPException(status_code=422,detail=f"Expanded genome failed schema validation: {e}",) from ewith _CUSTOM_LOCK:CUSTOM_PRODUCTS[pid] = genomelog.info("registered custom product %s (%d atoms)", pid, len(genome.functional_atoms))return _genome_summary(genome, custom=True)@app.delete("/api/products/custom/{product_id}")async def delete_custom(product_id: str) -> dict[str, bool]:with _CUSTOM_LOCK:removed = CUSTOM_PRODUCTS.pop(product_id, None) is not Nonereturn {"removed": removed}@app.get("/api/tensions")async def tensions() -> list[dict[str, Any]]:return [t.model_dump() for t in CONTEXT.tension_archetypes]18 unmodified lines@app.post("/api/generate")async def generate(req: GenerateRequest) -> dict[str, Any]:genome = _resolve_product(req.product_id)llm = Nonetry:
2 unmodified lines345678910111213141516171819202122232498 unmodified lines123124125126127128131 unmodified lines2602612622632642652 unmodified linesconst $ = (sel, el = document) => el.querySelector(sel);const $$ = (sel, el = document) => Array.from(el.querySelectorAll(sel));const API = {meta: () => fetch('/api/meta').then(r => r.json()),products: () => fetch('/api/products').then(r => r.json()),tensions: () => fetch('/api/tensions').then(r => r.json()),rules: () => fetch('/api/rules').then(r => r.json()),generate: (body) => fetch('/api/generate', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),}).then(async r => {if (!r.ok) {const j = await r.json().catch(() => ({ detail: r.statusText }));throw new Error(j.detail || `HTTP ${r.status}`);}return r.json();}),};let TENSIONS = [];98 unmodified lines$('#topK').addEventListener('input', e => $('#topKVal').textContent = e.target.value);$('#backendSel').addEventListener('change', syncBackendPlaceholder);$('#genBtn').addEventListener('click', runGenerate);}function syncBackendPlaceholder() {131 unmodified lines</div></div><div class="seed-section-title">Concept</div><div class="seed-concept">${escapeHtml(seed.concept)}</div>2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899098 unmodified lines189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312131 unmodified lines4444454464474484494502 unmodified linesconst $ = (sel, el = document) => el.querySelector(sel);const $$ = (sel, el = document) => Array.from(el.querySelectorAll(sel));const _post = (url, body) => fetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),}).then(async r => {if (!r.ok) {const j = await r.json().catch(() => ({ detail: r.statusText }));throw new Error(j.detail || `HTTP ${r.status}`);}return r.json();});const API = {meta: () => fetch('/api/meta').then(r => r.json()),products: () => fetch('/api/products').then(r => r.json()),tensions: () => fetch('/api/tensions').then(r => r.json()),rules: () => fetch('/api/rules').then(r => r.json()),generate: (body) => _post('/api/generate', body),expand: (body) => _post('/api/products/expand', body),};const PRESETS = {coffee: {brand: 'NOVA-Bean', category: '원두 커피', price_tier: 'premium',parts: [{ name: '원두', description: '로스팅된 커피 콩' },{ name: '그라인더', description: '원두를 가는 장치' },{ name: '필터', description: '커피 가루를 걸러내는 종이/천' },{ name: '추출수', description: '92~96℃의 정제수' },{ name: '잔', description: '커피를 담는 세라믹 컵' },],},phone: {brand: 'AETHER-Phone', category: '스마트폰', price_tier: 'premium',parts: [{ name: '디스플레이', description: '6.3인치 OLED 터치 패널' },{ name: '카메라', description: '후면 트리플 카메라' },{ name: '배터리', description: '4500mAh 리튬이온 배터리' },{ name: '프로세서', description: '자체 설계 AI 칩셋' },{ name: '진동모터', description: '햅틱 피드백용 미니 모터' },],},sneaker: {brand: 'PULSE-Run', category: '러닝화', price_tier: 'mid',parts: [{ name: '미드솔', description: '발포폼 완충재' },{ name: '아웃솔', description: '고무 접지면' },{ name: '어퍼', description: '통기성 니트 직물' },{ name: '끈', description: '라운드 레이스' },{ name: '뒤꿈치컵', description: '아킬레스를 감싸는 TPU' },],},beer: {brand: 'HOP-Haru', category: '수제맥주 IPA', price_tier: 'mid',parts: [{ name: '병', description: '갈색 유리 330ml' },{ name: '뚜껑', description: '크라운 캡' },{ name: '거품', description: '상부 하얀 헤드' },{ name: '라벨', description: '가상 브랜드 레터링' },{ name: '홉', description: '쓴맛과 시트러스 향' },],},cosmetic: {brand: 'GLOW-Han', category: '스킨케어 앰플', price_tier: 'luxury',parts: [{ name: '스포이드', description: '유리 드로퍼' },{ name: '병', description: '갈색 자외선 차단 유리' },{ name: '세럼', description: '점성 있는 투명 액체' },{ name: '향', description: '한방 허브 노트' },{ name: '케이스', description: '한지 질감 외곽 박스' },],},car: {brand: 'SPIRA-EV', category: '전기차', price_tier: 'luxury',parts: [{ name: '배터리팩', description: '차체 바닥 일체형' },{ name: '모터', description: '듀얼 퍼머넌트 마그넷' },{ name: '스크린', description: '17인치 중앙 터치' },{ name: '핸들', description: '요크 형 스티어링' },{ name: '충전 포트', description: '800V 급속 충전' },],},};let TENSIONS = [];98 unmodified lines$('#topK').addEventListener('input', e => $('#topKVal').textContent = e.target.value);$('#backendSel').addEventListener('change', syncBackendPlaceholder);$('#genBtn').addEventListener('click', runGenerate);wireModal();}/* ── Custom product modal ─────────────────────────────────── */function wireModal() {$('#newProductBtn').addEventListener('click', openModal);$('#productModal').querySelectorAll('[data-close]').forEach(el => {el.addEventListener('click', closeModal);});document.addEventListener('keydown', e => {if (e.key === 'Escape' && !$('#productModal').hidden) closeModal();});$('#npAddPart').addEventListener('click', () => addPartRow('', ''));$('#npSubmit').addEventListener('click', submitCustomProduct);$$('.preset-chip').forEach(btn => {btn.addEventListener('click', () => applyPreset(btn.dataset.preset));});// Seed with 2 empty rowsaddPartRow('', '');addPartRow('', '');}function openModal() {$('#productModal').hidden = false;$('#npErr').hidden = true;document.body.style.overflow = 'hidden';setTimeout(() => $('#npBrand').focus(), 50);}function closeModal() {$('#productModal').hidden = true;document.body.style.overflow = '';}function addPartRow(name, desc) {const rows = $$('#npParts .part-row');if (rows.length >= 8) return;const row = document.createElement('div');row.className = 'part-row';row.innerHTML = `<input type="text" class="part-name" placeholder="부품 이름" value="${escapeAttr(name)}" maxlength="30" /><input type="text" class="part-desc" placeholder="한 줄 설명 (선택)" value="${escapeAttr(desc)}" maxlength="80" /><button type="button" class="part-del" title="삭제">✕</button>`;row.querySelector('.part-del').addEventListener('click', () => {if ($$('#npParts .part-row').length > 2) row.remove();updatePartCount();});$('#npParts').appendChild(row);updatePartCount();}function updatePartCount() {const n = $$('#npParts .part-row').length;$('#npPartCount').textContent = `(${n}/8)`;}function applyPreset(key) {const p = PRESETS[key];if (!p) return;$('#npBrand').value = p.brand;$('#npCategory').value = p.category;$('#npTier').value = p.price_tier;$('#npParts').innerHTML = '';p.parts.forEach(pt => addPartRow(pt.name, pt.description));$('#npErr').hidden = true;}async function submitCustomProduct() {const brand = $('#npBrand').value.trim();const category = $('#npCategory').value.trim();const tier = $('#npTier').value;const parts = $$('#npParts .part-row').map(row => ({name: row.querySelector('.part-name').value.trim(),description: row.querySelector('.part-desc').value.trim(),})).filter(p => p.name);if (!brand) return showModalErr('브랜드를 입력하세요. (가상 브랜드만)');if (!category) return showModalErr('카테고리를 입력하세요.');if (parts.length < 2) return showModalErr('부품을 2개 이상 입력하세요.');const backend = $('#backendSel').value === 'none' ? 'fireworks' : $('#backendSel').value;$('#npSubmit').disabled = true;$('#npSubmit .btn-spinner').hidden = false;$('#npSubmit .btn-label').textContent = 'LLM 확장 중… (30~60s)';$('#npErr').hidden = true;try {const result = await API.expand({ brand, category, price_tier: tier, parts, backend });PRODUCTS.push(result);const sel = $('#productSel');const opt = document.createElement('option');opt.value = result.product_id;opt.textContent = `${result.brand} · ${result.category} [custom]`;sel.appendChild(opt);sel.value = result.product_id;updateProductMeta();closeModal();} catch (err) {const msg = err && err.message ? err.message : String(err);showModalErr(`❌ 확장 실패: ${msg}`);} finally {$('#npSubmit').disabled = false;$('#npSubmit .btn-spinner').hidden = true;$('#npSubmit .btn-label').textContent = '→ LLM으로 확장';}}function showModalErr(msg) {const box = $('#npErr');box.hidden = false;box.textContent = msg;}function escapeAttr(s) {return String(s || '').replace(/"/g, '"');}function syncBackendPlaceholder() {131 unmodified lines</div></div>${seed.wow_anchor ? `<div class="seed-anchor">${escapeHtml(seed.wow_anchor)}</div>` : ''}<div class="seed-section-title">Concept</div><div class="seed-concept">${escapeHtml(seed.concept)}</div>
35 unmodified lines36373839404142434445136 unmodified lines18218318418518618735 unmodified lines<main class="container main"><aside class="sidebar"><div class="card"><div class="card-header"><h2><span class="step">1</span>Product Genome</h2></div><div class="field"><label for="productSel">Product</label><select id="productSel"></select><div id="productMeta" class="meta"></div></div></div>136 unmodified lines</div></footer><script src="/static/app.js"></script></body></html>35 unmodified lines363738394041424344454647484950136 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525635 unmodified lines<main class="container main"><aside class="sidebar"><div class="card"><div class="card-header"><h2><span class="step">1</span>Product Genome</h2></div><div class="field"><label for="productSel">Product</label><div class="product-row"><select id="productSel"></select><button type="button" id="newProductBtn" class="btn-mini" title="새 제품 추가">+</button></div><div id="productMeta" class="meta"></div></div></div>136 unmodified lines</div></footer><!-- Custom product modal --><div id="productModal" class="modal" hidden><div class="modal-backdrop" data-close></div><div class="modal-panel"><header class="modal-head"><h3>🧬 새 제품 추가 <small>— LLM이 잠재력·SCAMPER 변주까지 확장합니다</small></h3><button type="button" class="modal-x" data-close aria-label="닫기">✕</button></header><div class="modal-body"><div class="form-row"><div class="field"><label for="npBrand">브랜드 (가상 브랜드만, 실존 브랜드 금지)</label><input type="text" id="npBrand" placeholder="예: NOVA-Bean, AETHER-Phone, HAN-Cha" maxlength="40" /></div><div class="field"><label for="npTier">가격대</label><select id="npTier"><option value="budget">budget</option><option value="mid">mid</option><option value="premium" selected>premium</option><option value="luxury">luxury</option></select></div></div><div class="field"><label for="npCategory">카테고리 (한국어)</label><input type="text" id="npCategory" placeholder="예: 원두 커피, 태블릿, 러닝화, 맥주, 화장품" maxlength="60" /></div><div class="field"><label>부품/구성 요소 <span id="npPartCount">(2/8)</span><small>· 2~8개 · 이름 + 한 줄 설명</small></label><div id="npParts" class="parts-list"></div><button type="button" id="npAddPart" class="btn-ghost">+ 부품 추가</button></div><details class="preset-details"><summary>💡 빠른 프리셋 — 한 번에 채우기</summary><div class="preset-grid"><button type="button" class="preset-chip" data-preset="coffee">☕ 원두 커피 NOVA-Bean</button><button type="button" class="preset-chip" data-preset="phone">📱 스마트폰 AETHER-Phone</button><button type="button" class="preset-chip" data-preset="sneaker">👟 러닝화 PULSE-Run</button><button type="button" class="preset-chip" data-preset="beer">🍺 수제맥주 HOP-Haru</button><button type="button" class="preset-chip" data-preset="cosmetic">💄 화장품 GLOW-Han</button><button type="button" class="preset-chip" data-preset="car">🚗 전기차 SPIRA-EV</button></div></details><div id="npErr" class="err" hidden></div></div><footer class="modal-foot"><button type="button" class="btn-ghost" data-close>취소</button><button type="button" id="npSubmit" class="btn-primary"><span class="btn-spinner" hidden></span><span class="btn-label">→ LLM으로 확장</span></button></footer></div></div><script src="/static/app.js"></script></body></html>
537 unmodified lines538539540541542543537 unmodified linesfont-variant-numeric: tabular-nums;}/* Raw model output (collapsible reference) */.raw-details {margin-top: 14px;537 unmodified lines538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732537 unmodified linesfont-variant-numeric: tabular-nums;}/* ── PRODUCT ROW + MINI BTN ─────────────────────────────────── */.product-row {display: grid; grid-template-columns: 1fr 40px; gap: 8px;}.btn-mini {width: 40px; height: 38px;border: 1px solid var(--border);border-radius: var(--radius-sm);background: white; cursor: pointer;font-size: 18px; font-weight: 700;color: var(--primary);transition: all 0.15s;display: grid; place-items: center;font-family: inherit;}.btn-mini:hover {border-color: var(--primary);background: var(--primary-light);}/* ── MODAL ──────────────────────────────────────────────────── */.modal {position: fixed; inset: 0;z-index: 1000;display: grid; place-items: center;padding: 20px;animation: fadeIn 0.15s ease-out;}.modal[hidden] { display: none; }.modal-backdrop {position: absolute; inset: 0;background: rgba(15, 23, 42, 0.45);backdrop-filter: blur(4px);-webkit-backdrop-filter: blur(4px);}.modal-panel {position: relative;width: 100%; max-width: 640px;max-height: 90vh;background: white;border-radius: 18px;box-shadow: 0 28px 80px rgba(15, 23, 42, 0.28);display: flex; flex-direction: column;overflow: hidden;animation: popIn 0.2s cubic-bezier(0.22, 1.2, 0.36, 1);}@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }@keyframes popIn { from { transform: translateY(12px) scale(0.98); opacity: 0; } to { transform: none; opacity: 1; } }.modal-head {padding: 20px 24px 16px;border-bottom: 1px solid var(--border);display: flex; align-items: flex-start; gap: 12px;}.modal-head h3 {flex: 1;font-size: 17px; font-weight: 800;letter-spacing: -0.02em;line-height: 1.3;}.modal-head h3 small {display: block; margin-top: 4px;font-size: 12px; font-weight: 500;color: var(--text-muted);}.modal-x {width: 32px; height: 32px;border: none; background: var(--surface);border-radius: 8px;cursor: pointer;font-size: 14px; color: var(--text-muted);transition: all 0.15s;}.modal-x:hover { background: var(--surface-2); color: var(--danger); }.modal-body {padding: 20px 24px;overflow-y: auto;flex: 1;}.modal-foot {padding: 16px 24px;border-top: 1px solid var(--border);background: var(--surface);display: flex; justify-content: flex-end; gap: 10px;}.modal-foot .btn-primary { width: auto; min-width: 200px; margin-top: 0; }.form-row {display: grid; grid-template-columns: 1fr 140px; gap: 12px;}@media (max-width: 540px) {.form-row { grid-template-columns: 1fr; }}/* parts list inside modal */.parts-list {display: flex; flex-direction: column; gap: 8px;margin-bottom: 8px;}.part-row {display: grid; grid-template-columns: 140px 1fr 32px; gap: 8px;align-items: center;}.part-row input {padding: 8px 10px; font-size: 13px;}.part-row .part-del {width: 32px; height: 34px;border: 1px solid var(--border);border-radius: 6px;background: white;color: var(--text-muted); font-size: 14px;cursor: pointer;font-family: inherit;transition: all 0.15s;}.part-row .part-del:hover {border-color: var(--danger); color: var(--danger);background: #fef2f2;}.btn-ghost {padding: 9px 14px;border: 1px dashed var(--border-strong);border-radius: var(--radius-sm);background: white; color: var(--text-muted);font-size: 13px; font-weight: 600;cursor: pointer;transition: all 0.15s;font-family: inherit;}.btn-ghost:hover {border-color: var(--primary); color: var(--primary);background: var(--primary-light);border-style: solid;}/* presets */.preset-details {margin-top: 14px;border: 1px solid var(--border);border-radius: var(--radius-sm);padding: 10px 14px;background: var(--surface);}.preset-details summary {cursor: pointer; font-weight: 600;color: var(--text); font-size: 13px;}.preset-details[open] summary { margin-bottom: 10px; color: var(--primary); }.preset-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));gap: 8px;}.preset-chip {padding: 9px 10px;border: 1px solid var(--border);border-radius: 8px;background: white; color: var(--text);font-size: 12px; font-weight: 600;cursor: pointer;text-align: left;transition: all 0.15s;font-family: inherit;}.preset-chip:hover {border-color: var(--primary);background: var(--primary-light);color: var(--primary);}/* wow anchor badge on seed cards */.seed-anchor {margin: 8px 0 14px;padding: 8px 12px;background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);border: 1px solid #fbbf24;border-radius: 7px;font-size: 12px; line-height: 1.5;color: #78350f;}.seed-anchor::before {content: "⚡ 와우 앵커: ";font-weight: 700; color: #92400e;}/* Raw model output (collapsible reference) */.raw-details {margin-top: 14px;
.pytest_cache/v/cache/lastfailedAdded+1
aether_ad/core/engine.py+58-9
aether_ad/core/wow_anchors.pyAdded+47
aether_ad/llm/base.py+31-3
aether_ad/llm/fireworks_kimi.py+9-6
aether_ad/llm/prompts/apply_collision.txt+27-10
aether_ad/llm/prompts/generate_product_genome.txtAdded+58
app.py+170-23
static/app.js+196-11
static/index.html+71-2
static/styles.css+189