File size: 22,612 Bytes
2367ac6
61159a3
2367ac6
61159a3
 
 
 
2367ac6
61159a3
 
 
 
 
 
 
2367ac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
2367ac6
61159a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2367ac6
 
 
 
61159a3
2367ac6
 
 
 
 
 
61159a3
 
2367ac6
 
 
 
 
 
 
61159a3
 
2367ac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
2367ac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
 
 
2367ac6
 
 
61159a3
2367ac6
61159a3
2367ac6
 
 
 
 
 
 
61159a3
2367ac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
 
 
 
 
 
 
2367ac6
61159a3
2367ac6
 
 
 
 
61159a3
2367ac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
2367ac6
 
61159a3
2367ac6
61159a3
2367ac6
61159a3
2367ac6
61159a3
2367ac6
61159a3
 
2367ac6
61159a3
 
 
 
 
 
 
 
 
2367ac6
 
61159a3
2367ac6
61159a3
2367ac6
 
61159a3
 
2367ac6
61159a3
2367ac6
61159a3
2367ac6
61159a3
 
 
 
 
2367ac6
 
 
aa93841
2367ac6
61159a3
2367ac6
 
aa93841
2367ac6
61159a3
2367ac6
 
 
 
61159a3
2367ac6
61159a3
2367ac6
61159a3
 
 
 
 
 
2367ac6
61159a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2367ac6
 
61159a3
 
 
 
 
 
 
 
 
2367ac6
 
 
 
 
 
 
 
 
 
 
61159a3
2367ac6
61159a3
 
 
2367ac6
 
 
 
 
 
 
 
 
 
61159a3
2367ac6
 
61159a3
 
 
 
 
2367ac6
 
61159a3
 
 
 
 
 
2367ac6
 
 
61159a3
2367ac6
 
 
 
 
 
61159a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2367ac6
 
 
 
 
 
 
61159a3
 
 
 
 
 
 
 
2367ac6
 
61159a3
 
 
2367ac6
61159a3
 
 
 
 
 
 
2367ac6
 
 
 
 
 
61159a3
2367ac6
 
 
61159a3
 
 
 
 
2367ac6
 
61159a3
 
 
 
 
2367ac6
61159a3
 
 
 
 
 
 
 
 
 
 
 
 
2367ac6
61159a3
 
 
 
 
 
 
 
 
 
2367ac6
 
61159a3
 
 
 
 
 
 
2367ac6
61159a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2367ac6
 
61159a3
2367ac6
 
61159a3
2367ac6
 
61159a3
2367ac6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
"""
pipeline_v6.py — Synthesize pipeline (seed → finished article).

Flow (stream_synth):
  pipeline_start
  → synthesize_token * N         (LLM streaming)
  → pipeline_done                (output + annotations + titles + slop_score)

Stages behind pipeline_done (non-streaming, instant or ~2s each):
  cleanup (rules) → post-slop score (rules) → title (LLM, ~2s)

Tools (non-streaming, called directly, not inside stream_synth):
  FetchStep.fetch(url)           Jina Reader → {title, summary}

Cost ≈ ¥0.001/article, 15-25s total.
"""

import os
import re
import json
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Generator, Iterator

from dotenv import load_dotenv
load_dotenv()

from openai import OpenAI
import config as _config


# ======================================================================
# Helpers (quote-aware text processing)
# ======================================================================

_QUOTE_SEGMENT_RE = re.compile(
    r'"[^"]*"|'
    r'\u201c[^\u201d]*\u201d|'
    r"'[^']*'|"
    r'\u2018[^\u2019]*\u2019|'
    r'\u300c[^\u300d]*\u300d|'
    r'\u300e[^\u300f]*\u300f|'
    r'\u300a[^\u300b]*\u300b|'
    r'\uff08[^\uff09]*\uff09|'
    r'\([^\)]*\)'
)

_QUOTE_TRANS = str.maketrans({
    '\u201c': '"', '\u201d': '"',
    '\u2018': "'", '\u2019': "'",
    '\u300c': '"', '\u300d': '"',
    '\u300e': "'", '\u300f': "'",
})


def _normalize_quotes(s: str) -> str:
    """Collapse Chinese quote variants. Length-preserving."""
    return s.translate(_QUOTE_TRANS)


# ======================================================================
# Model clients
# ======================================================================

_client_cache: Dict[Tuple[str, str], OpenAI] = {}


def _get_client(api_key: str, base_url: str) -> OpenAI:
    key = (api_key or "", base_url or "")
    if key not in _client_cache:
        _client_cache[key] = OpenAI(api_key=api_key, base_url=base_url)
    return _client_cache[key]


SYNTHESIZE_MODEL = _config.ModelConfig(
    provider="openai",
    model="deepseek/deepseek-v3.2",
    api_key=os.getenv("OPENROUTER_API_KEY", ""),
    base_url="https://openrouter.ai/api/v1",
    temperature=0.7,
    max_tokens=4096,
)
TITLE_MODEL = SYNTHESIZE_MODEL
FETCH_MODEL = SYNTHESIZE_MODEL


def call_model(model_config, prompt: str, max_tokens: int = 4096,
               temperature: Optional[float] = None, max_retries: int = 3) -> str:
    temp = temperature if temperature is not None else model_config.temperature
    for attempt in range(max_retries):
        try:
            client = _get_client(model_config.api_key, model_config.base_url)
            resp = client.chat.completions.create(
                model=model_config.model,
                messages=[{"role": "user", "content": prompt}],
                temperature=temp,
                max_tokens=max_tokens,
            )
            content = resp.choices[0].message.content
            if content and content.strip():
                return content
            raise ValueError("empty response")
        except Exception:
            if attempt < max_retries - 1:
                time.sleep(2 * (attempt + 1))
            else:
                raise


def call_model_stream(model_config, prompt: str, max_tokens: int = 4096,
                      temperature: Optional[float] = None) -> Iterator[str]:
    temp = temperature if temperature is not None else model_config.temperature
    client = _get_client(model_config.api_key, model_config.base_url)
    response = client.chat.completions.create(
        model=model_config.model,
        messages=[{"role": "user", "content": prompt}],
        temperature=temp,
        max_tokens=max_tokens,
        stream=True,
    )
    for chunk in response:
        if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
            yield chunk.choices[0].delta.content


# ======================================================================
# Context
# ======================================================================

@dataclass
class PipelineContext:
    platform: str = "xiaohongshu"
    seed: Dict = field(default_factory=dict)
    voice_profile: str = ""
    length: str = "medium"

    output: str = ""
    annotations: List[Dict] = field(default_factory=list)
    titles: List[str] = field(default_factory=list)

    slop_score: int = 0
    slop_cleanup: Dict = field(default_factory=dict)

    errors: List[str] = field(default_factory=list)
    step_timings: Dict[str, float] = field(default_factory=dict)


# ======================================================================
# SlopDetect — post-score only (rule-based, instant)
# ======================================================================

class SlopDetectStep:
    def __init__(self):
        self._phrases = []
        self._regex = []
        patterns = _config.AI_PATTERNS_CN
        if not patterns:
            return
        for cat_name, cat in patterns.items():
            if not isinstance(cat, dict):
                continue
            for sub_name, sub in cat.items():
                if not isinstance(sub, dict):
                    continue
                w = sub.get("weight", 1)
                tag = f"{cat_name}.{sub_name}"
                for p in sub.get("phrases", []):
                    self._phrases.append((p, w, tag))
                for r in sub.get("regex", []):
                    try:
                        self._regex.append((re.compile(r), w, tag))
                    except re.error:
                        pass

    def detect(self, text: str) -> Tuple[int, List[Dict]]:
        hits = []
        total_score = 0

        def _blank_short_quote(m):
            seg = m.group(0)
            inner_len = len(seg) - 2
            return " " * len(seg) if 0 < inner_len <= 15 else seg

        scan_text = _QUOTE_SEGMENT_RE.sub(_blank_short_quote, text)

        for phrase, weight, tag in self._phrases:
            count = scan_text.count(phrase)
            if count > 0:
                total_score += weight * count
                hits.append({"pattern": phrase, "weight": weight, "count": count, "category": tag})

        for compiled, weight, tag in self._regex:
            matches = compiled.findall(scan_text)
            if matches:
                total_score += weight * len(matches)
                hits.append({"pattern": compiled.pattern[:40], "weight": weight, "count": len(matches), "category": tag})

        if len(text) > 100:
            sentences = [s.strip() for s in re.split(r'[。!?]', text) if s.strip()]
            paragraphs = [p.strip() for p in text.split('\n') if p.strip()]

            if len(paragraphs) <= 1 and len(text) > 200:
                total_score += 8
                hits.append({"pattern": "全文无分段", "weight": 8, "count": 1, "category": "structure"})

            if sentences:
                avg_len = sum(len(s) for s in sentences) / len(sentences)
                if avg_len > 35:
                    total_score += 6
                    hits.append({"pattern": f"平均句长{avg_len:.0f}字", "weight": 6, "count": 1, "category": "structure"})

            if text.count('?') == 0 and text.count('!') == 0 and len(text) > 200:
                total_score += 4
                hits.append({"pattern": "标点单调", "weight": 4, "count": 1, "category": "structure"})

            if len(sentences) >= 5:
                import statistics
                lens = [len(s) for s in sentences]
                if statistics.stdev(lens) < 5:
                    total_score += 6
                    hits.append({"pattern": "句长均匀", "weight": 6, "count": 1, "category": "structure"})

        hits.sort(key=lambda h: h["weight"] * h["count"], reverse=True)
        return total_score, hits[:15]


# ======================================================================
# Synthesize (seed + voice → article + annotations)
# ======================================================================

SYNTHESIZE_PROMPT = """根据以下种子,写一篇完整的文章。

【主题】{topic}

【视角/切入点】{angle}

【核心观点】{core_point}

【事实/素材】
{facts_block}

{references_block}

【用户写作风格】
{voice_block}

【硬约束】
- 紧扣核心观点,不要跑题
- 使用种子里的事实/素材,不编造与之矛盾的内容
- 字数范围:{length_spec}
- 不要 emoji,不要 markdown 格式
- 段落之间用空行分隔
- 标点有节奏感,长短句交替

【平台 ({platform})】
{platform_guide}

写完后,末尾加 <<<ANNOTATIONS>>> 标记,然后输出 JSON 数组,列出 3-5 个你在文章中做出的关键写作选择:
[{{"what": "做了什么选择", "why": "为什么(基于哪条 voice/seed 信号)", "span": "文章中对应的10-20字片段"}}]

**span 必须是文章里一段连续的、可以直接复制出来的原文子串,不要拼接、不要改写、不要省略号代替。**

**直接输出正文,第一个字就是正文。最后附上 annotations。**"""

LENGTH_SPECS = {
    "short":  "150-300 字",
    "medium": "300-600 字",
    "long":   "600-1200 字",
}

PLATFORM_GUIDES = {
    "xiaohongshu": (
        "小红书风格: 短段落(2-4句)\n"
        "语气亲切随意, 像跟朋友聊天\n"
        "重点突出个人真实感受"
    ),
    "longform": (
        "长文风格: 段落可以长\n"
        "语气理性有条理, 但不要学术腔\n"
        "重点突出逻辑和信息量"
    ),
}


class SynthesizeStep:
    def __init__(self, model_config=None):
        self.model_config = model_config or SYNTHESIZE_MODEL

    def _build_facts_block(self, facts: List[str]) -> str:
        if not facts:
            return "(无)"
        return "\n".join(f"- {f}" for f in facts if f)

    def _build_references_block(self, refs: List[Dict]) -> str:
        if not refs:
            return ""
        lines = ["【引用资料】"]
        for i, r in enumerate(refs[:5]):
            summary = (r.get("summary") or r.get("text") or "")[:300].strip()
            url = (r.get("url") or "").strip()
            if summary:
                src = f" (来源: {url})" if url else ""
                lines.append(f"- 引用{i+1}: {summary}{src}")
        if len(lines) == 1:
            return ""
        lines.append("可以借鉴引用里的观点或事实,若直接使用请在行文中提及来源。")
        return "\n".join(lines) + "\n"

    def _build_voice_block(self, voice_profile: str) -> str:
        vp = (voice_profile or "").strip()
        if not vp:
            return "(用户未提供声音档案,使用自然口语化中文,避免 AI 腔。)"
        return vp[:1500]

    def build_prompt(self, ctx: PipelineContext) -> str:
        seed = ctx.seed or {}
        return SYNTHESIZE_PROMPT.format(
            topic=(seed.get("topic") or "").strip() or "(未指定)",
            angle=(seed.get("angle") or "").strip() or "(未指定)",
            core_point=(seed.get("core_point") or "").strip() or "(未指定)",
            facts_block=self._build_facts_block(seed.get("facts") or []),
            references_block=self._build_references_block(seed.get("references") or []),
            voice_block=self._build_voice_block(ctx.voice_profile),
            length_spec=LENGTH_SPECS.get(ctx.length, LENGTH_SPECS["medium"]),
            platform=ctx.platform,
            platform_guide=PLATFORM_GUIDES.get(ctx.platform, PLATFORM_GUIDES["xiaohongshu"]),
        )

    def process_stream(self, ctx: PipelineContext) -> Generator[Tuple[str, dict], None, None]:
        prompt = self.build_prompt(ctx)
        full_text = ""
        try:
            for token in call_model_stream(self.model_config, prompt, max_tokens=4096):
                full_text += token
                if "<<<ANNOTATIONS>>>" not in full_text:
                    yield ("synthesize_token", {"token": token})
        except Exception as e:
            ctx.errors.append(f"Synthesize failed: {str(e)[:100]}")
            ctx.output = ""
            return

        if "<<<ANNOTATIONS>>>" in full_text:
            parts = full_text.split("<<<ANNOTATIONS>>>")
            ctx.output = parts[0].strip()
            ann_text = parts[1].strip()
            try:
                if "[" in ann_text:
                    ctx.annotations = json.loads(
                        ann_text[ann_text.index("["):ann_text.rindex("]")+1]
                    )
                    output_norm = _normalize_quotes(ctx.output)
                    for ann in ctx.annotations:
                        span = ann.get("span", "")
                        if not span:
                            ann["match_start"] = -1
                            ann["match_end"] = -1
                            continue
                        if span in ctx.output:
                            ann["match_start"] = ctx.output.index(span)
                            ann["match_end"] = ann["match_start"] + len(span)
                            continue
                        span_norm = _normalize_quotes(span)
                        if span_norm in output_norm:
                            idx = output_norm.index(span_norm)
                            ann["match_start"] = idx
                            ann["match_end"] = idx + len(span_norm)
                        else:
                            ann["match_start"] = -1
                            ann["match_end"] = -1
            except Exception:
                ctx.annotations = []
        else:
            ctx.output = full_text.strip()


# ======================================================================
# Title (3 candidates, non-streaming LLM call)
# ======================================================================

TITLE_PROMPT = """给下面这篇文章起 3 个候选标题。

【文章】
{article}

【平台 ({platform})】
{platform_hint}

【规则】
- 每个标题 8-22 字
- 3 个候选给出不同切入方式:具体场景、反差/悬念、观点陈述
- 不要 emoji、不要 #tag、不要书名号
- 不要用「值得一提的是」「不难发现」这类套话
- 围绕文章核心观点,不要跑题或夸大

直接输出 JSON 数组,每个元素一个标题字符串:
["标题1", "标题2", "标题3"]

除了 JSON 不要输出任何其他内容。"""

TITLE_PLATFORM_HINTS = {
    "xiaohongshu": (
        "小红书:标题要有钩子,能让用户愿意点进来。"
        "可以用反差、具体数字、第一人称、提问。"
        "避免标题党,要和正文内容匹配。"
    ),
    "longform": (
        "公众号/长文:标题要让读者一眼知道讲什么。"
        "克制、准确、有观点。不要夸张和噱头。"
    ),
}


class TitleStep:
    def __init__(self, model_config=None):
        self.model_config = model_config or TITLE_MODEL

    def build_prompt(self, article: str, platform: str) -> str:
        return TITLE_PROMPT.format(
            article=article[:2000],
            platform=platform,
            platform_hint=TITLE_PLATFORM_HINTS.get(platform, TITLE_PLATFORM_HINTS["xiaohongshu"]),
        )

    def generate(self, article: str, platform: str = "xiaohongshu") -> List[str]:
        if not article or len(article) < 30:
            return []
        prompt = self.build_prompt(article, platform)
        try:
            raw = call_model(self.model_config, prompt, max_tokens=400, temperature=0.8)
        except Exception:
            return []
        if "[" not in raw or "]" not in raw:
            return []
        try:
            arr = json.loads(raw[raw.index("["):raw.rindex("]")+1])
            titles = [str(t).strip() for t in arr if isinstance(t, str) and t.strip()]
            return titles[:3]
        except Exception:
            return []


# ======================================================================
# Fetch (URL → seed reference, standalone tool)
# ======================================================================

FETCH_SUMMARY_PROMPT = """下面是一篇网页文章的内容。请输出一段 200 字以内的中文摘要,保留主要观点和关键事实。

【文章】
{content}

【输出要求】
- 只输出摘要正文,不要标题、标签、markdown
- 200 字以内
- 保留文章核心论点和 2-3 条具体事实/数据
- 如果是外语,翻译为中文摘要"""


class FetchStep:
    JINA_BASE = "https://r.jina.ai/"
    FETCH_TIMEOUT = 20.0
    MAX_CONTENT_CHARS = 6000

    def __init__(self, model_config=None):
        self.model_config = model_config or FETCH_MODEL

    def _fetch_raw(self, url: str) -> Tuple[str, str]:
        import httpx
        if not url.startswith(("http://", "https://")):
            raise ValueError("URL 必须以 http:// 或 https:// 开头")
        reader_url = self.JINA_BASE + url
        with httpx.Client(timeout=self.FETCH_TIMEOUT, follow_redirects=True) as client:
            resp = client.get(reader_url, headers={"Accept": "text/plain"})
            resp.raise_for_status()
            body = resp.text

        title = ""
        content = body
        lines = body.split("\n", 20)
        for line in lines:
            if line.startswith("Title:"):
                title = line[6:].strip()
                break
        marker = "Markdown Content:"
        if marker in body:
            content = body.split(marker, 1)[1].strip()
        content = content[: self.MAX_CONTENT_CHARS]
        return title, content

    def _summarize(self, content: str) -> str:
        if not content or len(content) < 50:
            return content.strip()
        prompt = FETCH_SUMMARY_PROMPT.format(content=content)
        try:
            raw = call_model(self.model_config, prompt, max_tokens=500, temperature=0.3)
            return raw.strip()[:500]
        except Exception:
            return content[:300].strip()

    def fetch(self, url: str) -> Dict:
        try:
            title, content = self._fetch_raw(url)
        except Exception as e:
            return {"success": False, "url": url, "error": f"抓取失败: {str(e)[:200]}"}
        if not content.strip():
            return {"success": False, "url": url, "error": "内容为空或 Jina Reader 未返回正文"}
        summary = self._summarize(content)
        return {
            "success": True,
            "url": url,
            "title": title,
            "summary": summary,
        }


# ======================================================================
# SlopCleanup (rule replacements, quote-aware)
# ======================================================================

class SlopCleanupStep:
    def __init__(self):
        self.replacements = _config.RULE_CLEANER.word_replacements

    def clean(self, text: str) -> Tuple[str, Dict]:
        preserved = []

        def stash(m):
            preserved.append(m.group(0))
            return f"\x00{len(preserved)-1}\x00"

        stashed = _QUOTE_SEGMENT_RE.sub(stash, text)

        replaced = []
        for ai_word, human_word in self.replacements.items():
            if ai_word in stashed:
                count = stashed.count(ai_word)
                stashed = stashed.replace(ai_word, human_word)
                replaced.append({"from": ai_word, "to": human_word, "count": count})

        def restore(m):
            return preserved[int(m.group(1))]

        final = re.sub(r'\x00(\d+)\x00', restore, stashed)

        return final, {
            "replaced_words": replaced,
            "replaced_total": sum(r["count"] for r in replaced),
        }


# ======================================================================
# Pipeline
# ======================================================================

class PipelineV6:
    def __init__(self, synthesize_model=None, title_model=None, fetch_model=None):
        self.synthesize = SynthesizeStep(model_config=synthesize_model)
        self.title = TitleStep(model_config=title_model)
        self.fetcher = FetchStep(model_config=fetch_model)
        self.cleanup = SlopCleanupStep()
        self.slop_detect = SlopDetectStep()

    def stream_synth(self, seed: Dict, voice_profile: str = "",
                     platform: str = "xiaohongshu",
                     length: str = "medium") -> Generator[dict, None, None]:
        """
        Seed → finished article, streaming.

        Events:
          pipeline_start      handshake, metadata
          synthesize_token *  every LLM token for UI streaming
          pipeline_done       final payload: output + annotations + titles +
                              slop_score + cleanup + errors + timings
        """
        pid = str(uuid.uuid4())[:12]
        ctx = PipelineContext(
            platform=platform,
            seed=seed or {},
            voice_profile=voice_profile or "",
            length=length,
        )

        yield {
            "type": "pipeline_start",
            "ts": round(time.time(), 3),
            "data": {
                "pipeline_id": pid,
                "has_voice_profile": bool(voice_profile),
                "seed_keys": list((seed or {}).keys()),
                "length": length,
            },
        }

        t0 = time.time()
        for evt_type, evt_data in self.synthesize.process_stream(ctx):
            yield {
                "type": evt_type,
                "ts": round(time.time(), 3),
                "data": evt_data,
            }
        ctx.step_timings["synthesize"] = round(time.time() - t0, 2)

        if ctx.output:
            ctx.output, ctx.slop_cleanup = self.cleanup.clean(ctx.output)
            ctx.slop_score, _ = self.slop_detect.detect(ctx.output)
            t0 = time.time()
            ctx.titles = self.title.generate(ctx.output, ctx.platform)
            ctx.step_timings["title"] = round(time.time() - t0, 2)

        yield {
            "type": "pipeline_done",
            "ts": round(time.time(), 3),
            "data": {
                "pipeline_id": pid,
                "output": ctx.output,
                "annotations": ctx.annotations,
                "titles": ctx.titles,
                "slop_score": ctx.slop_score,
                "cleanup": ctx.slop_cleanup,
                "errors": ctx.errors,
                "step_timings": ctx.step_timings,
            },
        }


_pipeline: Optional[PipelineV6] = None


def get_pipeline() -> PipelineV6:
    global _pipeline
    if _pipeline is None:
        _pipeline = PipelineV6()
    return _pipeline