""" 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} 写完后,末尾加 <<>> 标记,然后输出 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 "<<>>" 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 "<<>>" in full_text: parts = full_text.split("<<>>") 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