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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pipeline_v6.py — 重构版: 极简 Pipeline
3
+
4
+ 架构:
5
+ SlopDetect (规则, 0.1s)
6
+ → IntuitionRetrieval (写作直觉向量库, 0.5s)
7
+ → Rewrite + Annotations (DeepSeek V3.2, 一次调用, 4s)
8
+ → SlopCleanup (规则, 0.01s)
9
+ → Post-SlopDetect (规则, 0.01s)
10
+
11
+ 砍掉: InputAnalyze LLM, 旧向量库, 单独 Reasoning 步骤
12
+ 成本: ~¥0.001/篇, ~5s 总耗时
13
+ """
14
+
15
+ import os
16
+ import re
17
+ import json
18
+ import time
19
+ import uuid
20
+ from dataclasses import dataclass, field
21
+ from typing import Any, Dict, List, Optional, Tuple, Generator, Iterator
22
+
23
+ from dotenv import load_dotenv
24
+ load_dotenv()
25
+
26
+ from openai import OpenAI
27
+ import config as _config
28
+
29
+ # ======================================================================
30
+ # Model client
31
+ # ======================================================================
32
+
33
+ _client_cache: Dict[Tuple[str, str], OpenAI] = {}
34
+
35
+ def _get_client(api_key: str, base_url: str) -> OpenAI:
36
+ key = (api_key or "", base_url or "")
37
+ if key not in _client_cache:
38
+ _client_cache[key] = OpenAI(api_key=api_key, base_url=base_url)
39
+ return _client_cache[key]
40
+
41
+ # DeepSeek V3.2 — non-thinking, fast, cheap, good at Chinese
42
+ REWRITE_MODEL = _config.ModelConfig(
43
+ provider="openai",
44
+ model="deepseek/deepseek-v3.2",
45
+ api_key=os.getenv("OPENROUTER_API_KEY", ""),
46
+ base_url="https://openrouter.ai/api/v1",
47
+ temperature=0.7,
48
+ max_tokens=4096,
49
+ )
50
+
51
+
52
+ def call_model(model_config, prompt: str, max_tokens: int = 4096,
53
+ temperature: Optional[float] = None, max_retries: int = 3) -> str:
54
+ temp = temperature if temperature is not None else model_config.temperature
55
+ for attempt in range(max_retries):
56
+ try:
57
+ client = _get_client(model_config.api_key, model_config.base_url)
58
+ resp = client.chat.completions.create(
59
+ model=model_config.model,
60
+ messages=[{"role": "user", "content": prompt}],
61
+ temperature=temp,
62
+ max_tokens=max_tokens,
63
+ )
64
+ content = resp.choices[0].message.content
65
+ if content and content.strip():
66
+ return content
67
+ raise ValueError("empty response")
68
+ except Exception as e:
69
+ if attempt < max_retries - 1:
70
+ time.sleep(2 * (attempt + 1))
71
+ else:
72
+ raise
73
+
74
+
75
+ def call_model_stream(model_config, prompt: str, max_tokens: int = 4096,
76
+ temperature: Optional[float] = None) -> Iterator[str]:
77
+ temp = temperature if temperature is not None else model_config.temperature
78
+ client = _get_client(model_config.api_key, model_config.base_url)
79
+ response = client.chat.completions.create(
80
+ model=model_config.model,
81
+ messages=[{"role": "user", "content": prompt}],
82
+ temperature=temp,
83
+ max_tokens=max_tokens,
84
+ stream=True,
85
+ )
86
+ for chunk in response:
87
+ if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
88
+ yield chunk.choices[0].delta.content
89
+
90
+
91
+ # ======================================================================
92
+ # Context
93
+ # ======================================================================
94
+
95
+ @dataclass
96
+ class PipelineContext:
97
+ original: str
98
+ platform: str = "xiaohongshu"
99
+ industry: str = ""
100
+
101
+ # SlopDetect
102
+ slop_score_before: int = 0
103
+ slop_hits: List[Dict] = field(default_factory=list)
104
+
105
+ # Intuition retrieval
106
+ intuition_refs: List[Dict] = field(default_factory=list)
107
+
108
+ # Rewrite output
109
+ output: str = ""
110
+ annotations: List[Dict] = field(default_factory=list)
111
+
112
+ # Post-rewrite
113
+ slop_score_after: int = 0
114
+ slop_cleanup: Dict = field(default_factory=dict)
115
+
116
+ # Meta
117
+ errors: List[str] = field(default_factory=list)
118
+ step_timings: Dict[str, float] = field(default_factory=dict)
119
+
120
+
121
+ # ======================================================================
122
+ # Step 1: SlopDetect (规则, 197 phrases + 34 regex + 4 structural)
123
+ # ======================================================================
124
+
125
+ class SlopDetectStep:
126
+ def __init__(self):
127
+ self._phrases = []
128
+ self._regex = []
129
+ patterns = _config.AI_PATTERNS_CN
130
+ if not patterns:
131
+ return
132
+ for cat_name, cat in patterns.items():
133
+ if not isinstance(cat, dict):
134
+ continue
135
+ for sub_name, sub in cat.items():
136
+ if not isinstance(sub, dict):
137
+ continue
138
+ w = sub.get("weight", 1)
139
+ tag = f"{cat_name}.{sub_name}"
140
+ for p in sub.get("phrases", []):
141
+ self._phrases.append((p, w, tag))
142
+ for r in sub.get("regex", []):
143
+ try:
144
+ self._regex.append((re.compile(r), w, tag))
145
+ except re.error:
146
+ pass
147
+
148
+ def detect(self, text: str) -> Tuple[int, List[Dict]]:
149
+ hits = []
150
+ total_score = 0
151
+
152
+ for phrase, weight, tag in self._phrases:
153
+ count = text.count(phrase)
154
+ if count > 0:
155
+ total_score += weight * count
156
+ hits.append({"pattern": phrase, "weight": weight, "count": count, "category": tag})
157
+
158
+ for compiled, weight, tag in self._regex:
159
+ matches = compiled.findall(text)
160
+ if matches:
161
+ total_score += weight * len(matches)
162
+ hits.append({"pattern": compiled.pattern[:40], "weight": weight, "count": len(matches), "category": tag})
163
+
164
+ # Structural checks
165
+ if len(text) > 100:
166
+ sentences = [s.strip() for s in re.split(r'[。!?]', text) if s.strip()]
167
+ paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
168
+
169
+ if len(paragraphs) <= 1 and len(text) > 200:
170
+ total_score += 8
171
+ hits.append({"pattern": "全文无分段", "weight": 8, "count": 1, "category": "structure"})
172
+
173
+ if sentences:
174
+ avg_len = sum(len(s) for s in sentences) / len(sentences)
175
+ if avg_len > 35:
176
+ total_score += 6
177
+ hits.append({"pattern": f"平均句长{avg_len:.0f}字", "weight": 6, "count": 1, "category": "structure"})
178
+
179
+ if text.count('?') == 0 and text.count('!') == 0 and len(text) > 200:
180
+ total_score += 4
181
+ hits.append({"pattern": "标点单调", "weight": 4, "count": 1, "category": "structure"})
182
+
183
+ if len(sentences) >= 5:
184
+ import statistics
185
+ lens = [len(s) for s in sentences]
186
+ if statistics.stdev(lens) < 5:
187
+ total_score += 6
188
+ hits.append({"pattern": "句长均匀", "weight": 6, "count": 1, "category": "structure"})
189
+
190
+ hits.sort(key=lambda h: h["weight"] * h["count"], reverse=True)
191
+ return total_score, hits[:15]
192
+
193
+
194
+ # ======================================================================
195
+ # Step 2: IntuitionRetrieval (写作直觉向量库)
196
+ # ======================================================================
197
+
198
+ class IntuitionRetrievalStep:
199
+ def __init__(self, n_results: int = 5):
200
+ self.n_results = n_results
201
+ self._coll = None
202
+
203
+ @property
204
+ def collection(self):
205
+ if self._coll is None:
206
+ import chromadb
207
+ from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
208
+ db_path = os.path.join(os.path.dirname(__file__), "chroma_db_intuition")
209
+ client = chromadb.PersistentClient(path=db_path)
210
+ embed_fn = SentenceTransformerEmbeddingFunction(model_name="BAAI/bge-small-zh-v1.5")
211
+ self._coll = client.get_collection("writing_intuition", embedding_function=embed_fn)
212
+ return self._coll
213
+
214
+ def retrieve(self, text: str) -> List[Dict]:
215
+ try:
216
+ results = self.collection.query(
217
+ query_texts=[text[:500]],
218
+ n_results=self.n_results,
219
+ )
220
+ refs = []
221
+ for id, meta in zip(results["ids"][0], results["metadatas"][0]):
222
+ refs.append({
223
+ "id": id,
224
+ "industry": meta.get("industry", ""),
225
+ "templates": meta.get("templates", "[]"),
226
+ "blind_spots": meta.get("blind_spots", "[]"),
227
+ "blind_spot_patterns": meta.get("blind_spot_patterns", "[]"),
228
+ "trust_arc": meta.get("trust_arc", ""),
229
+ "unsaid": meta.get("unsaid", ""),
230
+ "rhythm": meta.get("rhythm", "[]"),
231
+ })
232
+ return refs
233
+ except Exception as e:
234
+ return []
235
+
236
+
237
+ # ======================================================================
238
+ # Step 3: Rewrite + Annotations (一次 LLM 调用)
239
+ # ======================================================================
240
+
241
+ REWRITE_PROMPT = """改写这篇文章让它读起来像真人写的。保持原文主题和所有事实不变。
242
+
243
+ 【用户原文】
244
+ {original}
245
+
246
+ **硬约束**:
247
+ - 保持原文主题不变,不要写成另一篇文章
248
+ - 所有数字/品牌/时间/地点/价格必须保留
249
+ - 不要 emoji,不要 markdown 格式
250
+ - 段落之间用空行分隔
251
+ - 标点有节奏感,不要全是句号
252
+
253
+ **平台 ({platform})**:
254
+ {platform_guide}
255
+
256
+ **写作直觉 (从与你文章最相似的真人好文章中提取):**
257
+ {intuition_block}
258
+
259
+ **关于编造细节**:
260
+ 你可以编造让文章更有感觉的细节。编造的内容用这个格式: {{{{需要补充|提示语|编造的内容}}}}
261
+ 每篇 1-3 处,放在文章开头或关键转折处。原文已有的事实不要标记。
262
+
263
+ 改写完成后,在末尾加上 <<<ANNOTATIONS>>> 标记,然后输出JSON数组,列出3-5个最显著的改动:
264
+ [{{"what": "改了什么", "why": "为什么", "span": "改写后文本中的10-20字片段"}}]
265
+
266
+ **直接输出改写后的文本,第一个字就是正文。最后附上annotations。**"""
267
+
268
+ PLATFORM_GUIDES = {
269
+ "xiaohongshu": (
270
+ "小红书风格: 短段落(2-4句), 200-500字\n"
271
+ "语气亲切随意, 像跟朋友聊天\n"
272
+ "重点突出个人真实感受"
273
+ ),
274
+ "longform": (
275
+ "长文风格: 段落可以长, 500-2000字\n"
276
+ "语气理性有条理, 但不要学术腔\n"
277
+ "重点突出逻辑和信息量"
278
+ ),
279
+ }
280
+
281
+
282
+ class RewriteStep:
283
+ def __init__(self, model_config=None):
284
+ self.model_config = model_config or REWRITE_MODEL
285
+
286
+ def _build_intuition_block(self, refs: List[Dict]) -> str:
287
+ if not refs:
288
+ return "(无参考)"
289
+ lines = []
290
+ for i, r in enumerate(refs[:3]):
291
+ try:
292
+ templates = json.loads(r.get("templates", "[]"))
293
+ blind_spots = json.loads(r.get("blind_spot_patterns", "[]"))
294
+ except:
295
+ templates = []
296
+ blind_spots = []
297
+
298
+ parts = []
299
+ if templates:
300
+ parts.append(f"句式: {'; '.join(t[:40] for t in templates[:2])}")
301
+ if blind_spots:
302
+ parts.append(f"盲区: {'; '.join(b[:30] for b in blind_spots[:2])}")
303
+ if r.get("trust_arc"):
304
+ parts.append(f"信任: {r['trust_arc'][:60]}")
305
+ if r.get("unsaid"):
306
+ parts.append(f"留白: {r['unsaid'][:60]}")
307
+
308
+ if parts:
309
+ lines.append(f"参考{i+1} [{r.get('industry','')}]: " + " | ".join(parts))
310
+
311
+ return "\n".join(lines) if lines else "(无参考)"
312
+
313
+ def build_prompt(self, ctx: PipelineContext) -> str:
314
+ return REWRITE_PROMPT.format(
315
+ original=ctx.original[:2000],
316
+ platform=ctx.platform,
317
+ platform_guide=PLATFORM_GUIDES.get(ctx.platform, PLATFORM_GUIDES["xiaohongshu"]),
318
+ intuition_block=self._build_intuition_block(ctx.intuition_refs),
319
+ )
320
+
321
+ def process_stream(self, ctx: PipelineContext) -> Generator[Tuple[str, dict], None, None]:
322
+ prompt = self.build_prompt(ctx)
323
+ full_text = ""
324
+ try:
325
+ for token in call_model_stream(self.model_config, prompt, max_tokens=4096):
326
+ full_text += token
327
+ # Don't yield annotation JSON as tokens
328
+ if "<<<ANNOTATIONS>>>" not in full_text:
329
+ yield ("rewrite_token", {"token": token})
330
+ except Exception as e:
331
+ ctx.errors.append(f"Rewrite failed: {str(e)[:100]}")
332
+ full_text = ctx.original
333
+
334
+ # Parse annotations from end of output
335
+ if "<<<ANNOTATIONS>>>" in full_text:
336
+ parts = full_text.split("<<<ANNOTATIONS>>>")
337
+ ctx.output = parts[0].strip()
338
+ ann_text = parts[1].strip()
339
+ try:
340
+ if "[" in ann_text:
341
+ ctx.annotations = json.loads(
342
+ ann_text[ann_text.index("["):ann_text.rindex("]")+1]
343
+ )
344
+ # Match spans to output
345
+ for ann in ctx.annotations:
346
+ span = ann.get("span", "")
347
+ if span and span in ctx.output:
348
+ ann["match_start"] = ctx.output.index(span)
349
+ ann["match_end"] = ann["match_start"] + len(span)
350
+ else:
351
+ ann["match_start"] = -1
352
+ ann["match_end"] = -1
353
+ except:
354
+ ctx.annotations = []
355
+ else:
356
+ ctx.output = full_text.strip()
357
+
358
+
359
+ # ======================================================================
360
+ # Step 4: SlopCleanup (规则替换 AI 残留词)
361
+ # ======================================================================
362
+
363
+ class SlopCleanupStep:
364
+ def __init__(self):
365
+ self.replacements = _config.RULE_CLEANER.word_replacements
366
+
367
+ def clean(self, text: str) -> Tuple[str, Dict]:
368
+ replaced = []
369
+ for ai_word, human_word in self.replacements.items():
370
+ if ai_word in text:
371
+ count = text.count(ai_word)
372
+ text = text.replace(ai_word, human_word)
373
+ replaced.append({"from": ai_word, "to": human_word, "count": count})
374
+ return text, {
375
+ "replaced_words": replaced,
376
+ "replaced_total": sum(r["count"] for r in replaced),
377
+ }
378
+
379
+
380
+ # ======================================================================
381
+ # Pipeline 主类
382
+ # ======================================================================
383
+
384
+ class PipelineV6:
385
+ def __init__(self, rewrite_model=None):
386
+ self.slop_detect = SlopDetectStep()
387
+ self.intuition_retrieval = IntuitionRetrievalStep(n_results=5)
388
+ self.rewrite = RewriteStep(model_config=rewrite_model)
389
+ self.slop_cleanup = SlopCleanupStep()
390
+
391
+ def _make_event(self, event_type: str, step: str = "", data: dict = None) -> dict:
392
+ evt = {"type": event_type, "ts": round(time.time(), 3)}
393
+ if step:
394
+ evt["step"] = step
395
+ if data:
396
+ evt["data"] = data
397
+ return evt
398
+
399
+ def stream_run(self, text: str, platform: str = "xiaohongshu",
400
+ industry: str = "") -> Generator[dict, None, None]:
401
+ """
402
+ Streaming pipeline. Events:
403
+ pipeline_start → slop_detect → intuition_retrieved →
404
+ rewrite_token* → rewrite_done → slop_cleanup →
405
+ slop_detect_post → pipeline_done
406
+ """
407
+ pipeline_id = str(uuid.uuid4())[:12]
408
+ ctx = PipelineContext(original=text, platform=platform, industry=industry)
409
+
410
+ yield self._make_event("pipeline_start", data={
411
+ "pipeline_id": pipeline_id,
412
+ "input_length": len(text),
413
+ })
414
+
415
+ # Step 1: SlopDetect (instant)
416
+ t0 = time.time()
417
+ score, hits = self.slop_detect.detect(text)
418
+ ctx.slop_score_before = score
419
+ ctx.slop_hits = hits
420
+ ctx.step_timings["slop_detect"] = time.time() - t0
421
+
422
+ yield self._make_event("step_done", step="slop_detect", data={
423
+ "score": score,
424
+ "hits": hits,
425
+ "total_hits": len(hits),
426
+ })
427
+
428
+ # Step 2: Intuition Retrieval (0.5s)
429
+ t0 = time.time()
430
+ ctx.intuition_refs = self.intuition_retrieval.retrieve(text)
431
+ ctx.step_timings["retrieval"] = time.time() - t0
432
+
433
+ # Auto-detect industry from retrieval results
434
+ if ctx.intuition_refs:
435
+ industries = [r.get("industry", "") for r in ctx.intuition_refs]
436
+ ctx.industry = max(set(industries), key=industries.count) if industries else ""
437
+
438
+ yield self._make_event("step_done", step="retrieval", data={
439
+ "refs_count": len(ctx.intuition_refs),
440
+ "industry": ctx.industry,
441
+ })
442
+
443
+ # Step 3: Rewrite + Annotations (streaming)
444
+ t0 = time.time()
445
+ yield self._make_event("step_start", step="rewrite")
446
+
447
+ for evt_type, evt_data in self.rewrite.process_stream(ctx):
448
+ yield self._make_event(evt_type, step="rewrite", data=evt_data)
449
+
450
+ ctx.step_timings["rewrite"] = time.time() - t0
451
+
452
+ yield self._make_event("step_done", step="rewrite", data={
453
+ "output": ctx.output,
454
+ "output_length": len(ctx.output),
455
+ "annotations": ctx.annotations,
456
+ })
457
+
458
+ # Step 4: SlopCleanup (instant)
459
+ if ctx.output:
460
+ ctx.output, ctx.slop_cleanup = self.slop_cleanup.clean(ctx.output)
461
+ yield self._make_event("step_done", step="slop_cleanup", data={
462
+ "output": ctx.output,
463
+ **ctx.slop_cleanup,
464
+ })
465
+
466
+ # Step 5: Post-rewrite SlopDetect
467
+ if ctx.output:
468
+ ctx.slop_score_after, _ = self.slop_detect.detect(ctx.output)
469
+ yield self._make_event("step_done", step="slop_detect_post", data={
470
+ "score_before": ctx.slop_score_before,
471
+ "score_after": ctx.slop_score_after,
472
+ })
473
+
474
+ # Done
475
+ yield self._make_event("pipeline_done", data={
476
+ "pipeline_id": pipeline_id,
477
+ "output": ctx.output,
478
+ "annotations": ctx.annotations,
479
+ "slop_before": ctx.slop_score_before,
480
+ "slop_after": ctx.slop_score_after,
481
+ "industry": ctx.industry,
482
+ "errors": ctx.errors,
483
+ "step_timings": {k: round(v, 2) for k, v in ctx.step_timings.items()},
484
+ })
485
+
486
+
487
+ # Singleton
488
+ _pipeline = None
489
+
490
+ def get_pipeline(rewrite_model=None) -> PipelineV6:
491
+ global _pipeline
492
+ if _pipeline is None:
493
+ _pipeline = PipelineV6(rewrite_model=rewrite_model)
494
+ return _pipeline