Curious1008 commited on
Commit
61159a3
·
verified ·
1 Parent(s): aa93841

sync: v6 synthesize pipeline + slim deps (remove chroma)

Browse files
Files changed (4) hide show
  1. Dockerfile +0 -1
  2. pipeline_v6.py +368 -232
  3. requirements.txt +0 -2
  4. server.py +74 -207
Dockerfile CHANGED
@@ -9,7 +9,6 @@ RUN pip install --no-cache-dir -r requirements.txt
9
  # 复制应用代码
10
  COPY server.py pipeline_v6.py config.py ./
11
  COPY patterns_cn_ref.json writing_intuition_guides.json ./
12
- COPY chroma_db_intuition/ ./chroma_db_intuition/
13
  COPY static/ ./static/
14
 
15
  # HF Spaces 要求端口 7860
 
9
  # 复制应用代码
10
  COPY server.py pipeline_v6.py config.py ./
11
  COPY patterns_cn_ref.json writing_intuition_guides.json ./
 
12
  COPY static/ ./static/
13
 
14
  # HF Spaces 要求端口 7860
pipeline_v6.py CHANGED
@@ -1,15 +1,18 @@
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
@@ -26,20 +29,51 @@ load_dotenv()
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", ""),
@@ -47,6 +81,8 @@ REWRITE_MODEL = _config.ModelConfig(
47
  temperature=0.7,
48
  max_tokens=4096,
49
  )
 
 
50
 
51
 
52
  def call_model(model_config, prompt: str, max_tokens: int = 4096,
@@ -65,7 +101,7 @@ def call_model(model_config, prompt: str, max_tokens: int = 4096,
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:
@@ -94,32 +130,24 @@ def call_model_stream(model_config, prompt: str, max_tokens: int = 4096,
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:
@@ -149,19 +177,25 @@ class SlopDetectStep:
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()]
@@ -192,133 +226,105 @@ class SlopDetectStep:
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
- - 改写后字数与原文相近(±20%以内),不要大幅删减或压缩
249
- - 所有数字/品牌/时间/地点/价格必须保留
 
 
 
 
 
250
  - 不要 emoji,不要 markdown 格式
251
  - 段落之间用空行分隔
252
- - 标点有节奏感,不要全是句号
253
 
254
- **平台 ({platform})**:
255
  {platform_guide}
256
 
257
- **写作直觉 (从与你文章最相似的真人好文章中提取):**
258
- {intuition_block}
259
 
260
- **关于编造细节**:
261
- 你可以编造让文章更有感觉的细节。编造的内容用这个格式: {{{{需要补充|提示语|编造的内容}}}}
262
- 每篇 1-3 处,放在文章开头或关键转折处。原文已有的事实不要标记。
263
 
264
- 改写完成后,在末尾加上 <<<ANNOTATIONS>>> 标记,然后输出JSON数组,列出3-5个最显著的改动:
265
- [{{"what": "改了什么", "why": "为什么", "span": "改写后文本中的10-20字片段"}}]
266
 
267
- **直接输出改写后的文本,第一个字就是正文。最后附上annotations。**"""
 
 
 
 
268
 
269
  PLATFORM_GUIDES = {
270
  "xiaohongshu": (
271
  "小红书风格: 短段落(2-4句)\n"
272
  "语气亲切随意, 像跟朋友���天\n"
273
- "重点突出个人真实感受\n"
274
- "改写后字数与原文相近,不要大幅删减内容"
275
  ),
276
  "longform": (
277
  "长文风格: 段落可以长\n"
278
  "语气理性有条理, 但不要学术腔\n"
279
- "重点突出逻辑和信息量\n"
280
- "改写后字数与原文相近,不要大幅删减内容"
281
  ),
282
  }
283
 
284
 
285
- class RewriteStep:
286
  def __init__(self, model_config=None):
287
- self.model_config = model_config or REWRITE_MODEL
288
 
289
- def _build_intuition_block(self, refs: List[Dict]) -> str:
 
 
 
 
 
290
  if not refs:
291
- return "(无参考)"
292
- lines = []
293
- for i, r in enumerate(refs[:3]):
294
- try:
295
- templates = json.loads(r.get("templates", "[]"))
296
- blind_spots = json.loads(r.get("blind_spot_patterns", "[]"))
297
- except:
298
- templates = []
299
- blind_spots = []
300
-
301
- parts = []
302
- if templates:
303
- parts.append(f"句式: {'; '.join(t[:40] for t in templates[:2])}")
304
- if blind_spots:
305
- parts.append(f"盲区: {'; '.join(b[:30] for b in blind_spots[:2])}")
306
- if r.get("trust_arc"):
307
- parts.append(f"信任: {r['trust_arc'][:60]}")
308
- if r.get("unsaid"):
309
- parts.append(f"留白: {r['unsaid'][:60]}")
310
-
311
- if parts:
312
- lines.append(f"参考{i+1} [{r.get('industry','')}]: " + " | ".join(parts))
313
-
314
- return "\n".join(lines) if lines else "(无参考)"
315
 
316
  def build_prompt(self, ctx: PipelineContext) -> str:
317
- return REWRITE_PROMPT.format(
318
- original=ctx.original[:2000],
 
 
 
 
 
 
 
319
  platform=ctx.platform,
320
  platform_guide=PLATFORM_GUIDES.get(ctx.platform, PLATFORM_GUIDES["xiaohongshu"]),
321
- intuition_block=self._build_intuition_block(ctx.intuition_refs),
322
  )
323
 
324
  def process_stream(self, ctx: PipelineContext) -> Generator[Tuple[str, dict], None, None]:
@@ -327,14 +333,13 @@ class RewriteStep:
327
  try:
328
  for token in call_model_stream(self.model_config, prompt, max_tokens=4096):
329
  full_text += token
330
- # Don't yield annotation JSON as tokens
331
  if "<<<ANNOTATIONS>>>" not in full_text:
332
- yield ("rewrite_token", {"token": token})
333
  except Exception as e:
334
- ctx.errors.append(f"Rewrite failed: {str(e)[:100]}")
335
- full_text = ctx.original
 
336
 
337
- # Parse annotations from end of output
338
  if "<<<ANNOTATIONS>>>" in full_text:
339
  parts = full_text.split("<<<ANNOTATIONS>>>")
340
  ctx.output = parts[0].strip()
@@ -344,23 +349,172 @@ class RewriteStep:
344
  ctx.annotations = json.loads(
345
  ann_text[ann_text.index("["):ann_text.rindex("]")+1]
346
  )
347
- # Match spans to output
348
  for ann in ctx.annotations:
349
  span = ann.get("span", "")
350
- if span and span in ctx.output:
 
 
 
 
351
  ann["match_start"] = ctx.output.index(span)
352
  ann["match_end"] = ann["match_start"] + len(span)
 
 
 
 
 
 
353
  else:
354
  ann["match_start"] = -1
355
  ann["match_end"] = -1
356
- except:
357
  ctx.annotations = []
358
  else:
359
  ctx.output = full_text.strip()
360
 
361
 
362
  # ======================================================================
363
- # Step 4: SlopCleanup (规则替换 AI 残留词)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  # ======================================================================
365
 
366
  class SlopCleanupStep:
@@ -368,130 +522,112 @@ class SlopCleanupStep:
368
  self.replacements = _config.RULE_CLEANER.word_replacements
369
 
370
  def clean(self, text: str) -> Tuple[str, Dict]:
 
 
 
 
 
 
 
 
371
  replaced = []
372
  for ai_word, human_word in self.replacements.items():
373
- if ai_word in text:
374
- count = text.count(ai_word)
375
- text = text.replace(ai_word, human_word)
376
  replaced.append({"from": ai_word, "to": human_word, "count": count})
377
- return text, {
 
 
 
 
 
 
378
  "replaced_words": replaced,
379
  "replaced_total": sum(r["count"] for r in replaced),
380
  }
381
 
382
 
383
  # ======================================================================
384
- # Pipeline 主类
385
  # ======================================================================
386
 
387
  class PipelineV6:
388
- def __init__(self, rewrite_model=None):
 
 
 
 
389
  self.slop_detect = SlopDetectStep()
390
- self.intuition_retrieval = IntuitionRetrievalStep(n_results=5)
391
- self.rewrite = RewriteStep(model_config=rewrite_model)
392
- self.slop_cleanup = SlopCleanupStep()
393
-
394
- def _make_event(self, event_type: str, step: str = "", data: dict = None) -> dict:
395
- evt = {"type": event_type, "ts": round(time.time(), 3)}
396
- if step:
397
- evt["step"] = step
398
- if data:
399
- evt["data"] = data
400
- return evt
401
-
402
- def stream_run(self, text: str, platform: str = "xiaohongshu",
403
- industry: str = "") -> Generator[dict, None, None]:
404
- """
405
- Streaming pipeline. Events:
406
- pipeline_start → slop_detect → intuition_retrieved →
407
- rewrite_token* → rewrite_done → slop_cleanup →
408
- slop_detect_post → pipeline_done
409
- """
410
- pipeline_id = str(uuid.uuid4())[:12]
411
- ctx = PipelineContext(original=text, platform=platform, industry=industry)
412
-
413
- yield self._make_event("pipeline_start", data={
414
- "pipeline_id": pipeline_id,
415
- "input_length": len(text),
416
- })
417
 
418
- # Step 1: SlopDetect (instant)
419
- t0 = time.time()
420
- score, hits = self.slop_detect.detect(text)
421
- ctx.slop_score_before = score
422
- ctx.slop_hits = hits
423
- ctx.step_timings["slop_detect"] = time.time() - t0
424
-
425
- yield self._make_event("step_done", step="slop_detect", data={
426
- "score": score,
427
- "hits": hits,
428
- "total_hits": len(hits),
429
- })
430
-
431
- # Step 2: Intuition Retrieval (0.5s)
432
- t0 = time.time()
433
- ctx.intuition_refs = self.intuition_retrieval.retrieve(text)
434
- ctx.step_timings["retrieval"] = time.time() - t0
435
 
436
- # Auto-detect industry from retrieval results
437
- if ctx.intuition_refs:
438
- industries = [r.get("industry", "") for r in ctx.intuition_refs]
439
- ctx.industry = max(set(industries), key=industries.count) if industries else ""
 
 
 
 
 
 
 
 
 
440
 
441
- yield self._make_event("step_done", step="retrieval", data={
442
- "refs_count": len(ctx.intuition_refs),
443
- "industry": ctx.industry,
444
- })
 
 
 
 
 
 
445
 
446
- # Step 3: Rewrite + Annotations (streaming)
447
  t0 = time.time()
448
- yield self._make_event("step_start", step="rewrite")
 
 
 
 
 
 
449
 
450
- for evt_type, evt_data in self.rewrite.process_stream(ctx):
451
- yield self._make_event(evt_type, step="rewrite", data=evt_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
 
453
- ctx.step_timings["rewrite"] = time.time() - t0
454
 
455
- yield self._make_event("step_done", step="rewrite", data={
456
- "output": ctx.output,
457
- "output_length": len(ctx.output),
458
- "annotations": ctx.annotations,
459
- })
460
 
461
- # Step 4: SlopCleanup (instant)
462
- if ctx.output:
463
- ctx.output, ctx.slop_cleanup = self.slop_cleanup.clean(ctx.output)
464
- yield self._make_event("step_done", step="slop_cleanup", data={
465
- "output": ctx.output,
466
- **ctx.slop_cleanup,
467
- })
468
 
469
- # Step 5: Post-rewrite SlopDetect
470
- if ctx.output:
471
- ctx.slop_score_after, _ = self.slop_detect.detect(ctx.output)
472
- yield self._make_event("step_done", step="slop_detect_post", data={
473
- "score_before": ctx.slop_score_before,
474
- "score_after": ctx.slop_score_after,
475
- })
476
-
477
- # Done
478
- yield self._make_event("pipeline_done", data={
479
- "pipeline_id": pipeline_id,
480
- "output": ctx.output,
481
- "annotations": ctx.annotations,
482
- "slop_before": ctx.slop_score_before,
483
- "slop_after": ctx.slop_score_after,
484
- "industry": ctx.industry,
485
- "errors": ctx.errors,
486
- "step_timings": {k: round(v, 2) for k, v in ctx.step_timings.items()},
487
- })
488
-
489
-
490
- # Singleton
491
- _pipeline = None
492
-
493
- def get_pipeline(rewrite_model=None) -> PipelineV6:
494
  global _pipeline
495
  if _pipeline is None:
496
- _pipeline = PipelineV6(rewrite_model=rewrite_model)
497
  return _pipeline
 
1
  """
2
+ pipeline_v6.py — Synthesize pipeline (seed → finished article).
3
 
4
+ Flow (stream_synth):
5
+ pipeline_start
6
+ → synthesize_token * N (LLM streaming)
7
+ → pipeline_done (output + annotations + titles + slop_score)
 
 
8
 
9
+ Stages behind pipeline_done (non-streaming, instant or ~2s each):
10
+ cleanup (rules) → post-slop score (rules) → title (LLM, ~2s)
11
+
12
+ Tools (non-streaming, called directly, not inside stream_synth):
13
+ FetchStep.fetch(url) Jina Reader → {title, summary}
14
+
15
+ Cost ≈ ¥0.001/article, 15-25s total.
16
  """
17
 
18
  import os
 
29
  from openai import OpenAI
30
  import config as _config
31
 
32
+
33
  # ======================================================================
34
+ # Helpers (quote-aware text processing)
35
+ # ======================================================================
36
+
37
+ _QUOTE_SEGMENT_RE = re.compile(
38
+ r'"[^"]*"|'
39
+ r'\u201c[^\u201d]*\u201d|'
40
+ r"'[^']*'|"
41
+ r'\u2018[^\u2019]*\u2019|'
42
+ r'\u300c[^\u300d]*\u300d|'
43
+ r'\u300e[^\u300f]*\u300f|'
44
+ r'\u300a[^\u300b]*\u300b|'
45
+ r'\uff08[^\uff09]*\uff09|'
46
+ r'\([^\)]*\)'
47
+ )
48
+
49
+ _QUOTE_TRANS = str.maketrans({
50
+ '\u201c': '"', '\u201d': '"',
51
+ '\u2018': "'", '\u2019': "'",
52
+ '\u300c': '"', '\u300d': '"',
53
+ '\u300e': "'", '\u300f': "'",
54
+ })
55
+
56
+
57
+ def _normalize_quotes(s: str) -> str:
58
+ """Collapse Chinese quote variants. Length-preserving."""
59
+ return s.translate(_QUOTE_TRANS)
60
+
61
+
62
+ # ======================================================================
63
+ # Model clients
64
  # ======================================================================
65
 
66
  _client_cache: Dict[Tuple[str, str], OpenAI] = {}
67
 
68
+
69
  def _get_client(api_key: str, base_url: str) -> OpenAI:
70
  key = (api_key or "", base_url or "")
71
  if key not in _client_cache:
72
  _client_cache[key] = OpenAI(api_key=api_key, base_url=base_url)
73
  return _client_cache[key]
74
 
75
+
76
+ SYNTHESIZE_MODEL = _config.ModelConfig(
77
  provider="openai",
78
  model="deepseek/deepseek-v3.2",
79
  api_key=os.getenv("OPENROUTER_API_KEY", ""),
 
81
  temperature=0.7,
82
  max_tokens=4096,
83
  )
84
+ TITLE_MODEL = SYNTHESIZE_MODEL
85
+ FETCH_MODEL = SYNTHESIZE_MODEL
86
 
87
 
88
  def call_model(model_config, prompt: str, max_tokens: int = 4096,
 
101
  if content and content.strip():
102
  return content
103
  raise ValueError("empty response")
104
+ except Exception:
105
  if attempt < max_retries - 1:
106
  time.sleep(2 * (attempt + 1))
107
  else:
 
130
 
131
  @dataclass
132
  class PipelineContext:
 
133
  platform: str = "xiaohongshu"
134
+ seed: Dict = field(default_factory=dict)
135
+ voice_profile: str = ""
136
+ length: str = "medium"
 
 
137
 
 
 
 
 
138
  output: str = ""
139
  annotations: List[Dict] = field(default_factory=list)
140
+ titles: List[str] = field(default_factory=list)
141
 
142
+ slop_score: int = 0
 
143
  slop_cleanup: Dict = field(default_factory=dict)
144
 
 
145
  errors: List[str] = field(default_factory=list)
146
  step_timings: Dict[str, float] = field(default_factory=dict)
147
 
148
 
149
  # ======================================================================
150
+ # SlopDetect — post-score only (rule-based, instant)
151
  # ======================================================================
152
 
153
  class SlopDetectStep:
 
177
  hits = []
178
  total_score = 0
179
 
180
+ def _blank_short_quote(m):
181
+ seg = m.group(0)
182
+ inner_len = len(seg) - 2
183
+ return " " * len(seg) if 0 < inner_len <= 15 else seg
184
+
185
+ scan_text = _QUOTE_SEGMENT_RE.sub(_blank_short_quote, text)
186
+
187
  for phrase, weight, tag in self._phrases:
188
+ count = scan_text.count(phrase)
189
  if count > 0:
190
  total_score += weight * count
191
  hits.append({"pattern": phrase, "weight": weight, "count": count, "category": tag})
192
 
193
  for compiled, weight, tag in self._regex:
194
+ matches = compiled.findall(scan_text)
195
  if matches:
196
  total_score += weight * len(matches)
197
  hits.append({"pattern": compiled.pattern[:40], "weight": weight, "count": len(matches), "category": tag})
198
 
 
199
  if len(text) > 100:
200
  sentences = [s.strip() for s in re.split(r'[。!?]', text) if s.strip()]
201
  paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
 
226
 
227
 
228
  # ======================================================================
229
+ # Synthesize (seed + voice → article + annotations)
230
  # ======================================================================
231
 
232
+ SYNTHESIZE_PROMPT = """根据以下种子,写一篇完整的文章。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
+ 【主题】{topic}
235
 
236
+ 【视角/切入点】{angle}
 
 
237
 
238
+ 【核心观点】{core_point}
239
 
240
+ 【事实/素材】
241
+ {facts_block}
242
 
243
+ {references_block}
244
+
245
+ 【用户写作风格】
246
+ {voice_block}
247
+
248
+ 【硬约束】
249
+ - 紧扣核心观点,不要跑题
250
+ - 使用种子里的事实/素材,不编造与之矛盾的内容
251
+ - 字数范围:{length_spec}
252
  - 不要 emoji,不要 markdown 格式
253
  - 段落之间用空行分隔
254
+ - 标点有节奏感,长短句交替
255
 
256
+ 【平台 ({platform})】
257
  {platform_guide}
258
 
259
+ 写完后,末尾加 <<<ANNOTATIONS>>> 标记,然后输出 JSON 数组,列出 3-5 个你在文章中做出的关键写作选择:
260
+ [{{"what": "做了什么选择", "why": "为什么(基于哪条 voice/seed 信号)", "span": "文章中对应的10-20字片段"}}]
261
 
262
+ **span 必须是文章里一段连续的、可以直接复制出来的原文子串,不要拼接、不要改写、不要省略号代替。**
 
 
263
 
264
+ **直接输出正文,第一个字就是正文。最后附上 annotations。**"""
 
265
 
266
+ LENGTH_SPECS = {
267
+ "short": "150-300 字",
268
+ "medium": "300-600 字",
269
+ "long": "600-1200 字",
270
+ }
271
 
272
  PLATFORM_GUIDES = {
273
  "xiaohongshu": (
274
  "小红书风格: 短段落(2-4句)\n"
275
  "语气亲切随意, 像跟朋友���天\n"
276
+ "重点突出个人真实感受"
 
277
  ),
278
  "longform": (
279
  "长文风格: 段落可以长\n"
280
  "语气理性有条理, 但不要学术腔\n"
281
+ "重点突出逻辑和信息量"
 
282
  ),
283
  }
284
 
285
 
286
+ class SynthesizeStep:
287
  def __init__(self, model_config=None):
288
+ self.model_config = model_config or SYNTHESIZE_MODEL
289
 
290
+ def _build_facts_block(self, facts: List[str]) -> str:
291
+ if not facts:
292
+ return "(无)"
293
+ return "\n".join(f"- {f}" for f in facts if f)
294
+
295
+ def _build_references_block(self, refs: List[Dict]) -> str:
296
  if not refs:
297
+ return ""
298
+ lines = ["【引用资料】"]
299
+ for i, r in enumerate(refs[:5]):
300
+ summary = (r.get("summary") or r.get("text") or "")[:300].strip()
301
+ url = (r.get("url") or "").strip()
302
+ if summary:
303
+ src = f" (来源: {url})" if url else ""
304
+ lines.append(f"- 引用{i+1}: {summary}{src}")
305
+ if len(lines) == 1:
306
+ return ""
307
+ lines.append("可以借鉴引用里的观点或事实,若直接使用请在行文中提及来源。")
308
+ return "\n".join(lines) + "\n"
309
+
310
+ def _build_voice_block(self, voice_profile: str) -> str:
311
+ vp = (voice_profile or "").strip()
312
+ if not vp:
313
+ return "(用户未提供声音档案,使用自然口语化中文,避免 AI 腔。)"
314
+ return vp[:1500]
 
 
 
 
 
 
315
 
316
  def build_prompt(self, ctx: PipelineContext) -> str:
317
+ seed = ctx.seed or {}
318
+ return SYNTHESIZE_PROMPT.format(
319
+ topic=(seed.get("topic") or "").strip() or "(未指定)",
320
+ angle=(seed.get("angle") or "").strip() or "(未指定)",
321
+ core_point=(seed.get("core_point") or "").strip() or "(未指定)",
322
+ facts_block=self._build_facts_block(seed.get("facts") or []),
323
+ references_block=self._build_references_block(seed.get("references") or []),
324
+ voice_block=self._build_voice_block(ctx.voice_profile),
325
+ length_spec=LENGTH_SPECS.get(ctx.length, LENGTH_SPECS["medium"]),
326
  platform=ctx.platform,
327
  platform_guide=PLATFORM_GUIDES.get(ctx.platform, PLATFORM_GUIDES["xiaohongshu"]),
 
328
  )
329
 
330
  def process_stream(self, ctx: PipelineContext) -> Generator[Tuple[str, dict], None, None]:
 
333
  try:
334
  for token in call_model_stream(self.model_config, prompt, max_tokens=4096):
335
  full_text += token
 
336
  if "<<<ANNOTATIONS>>>" not in full_text:
337
+ yield ("synthesize_token", {"token": token})
338
  except Exception as e:
339
+ ctx.errors.append(f"Synthesize failed: {str(e)[:100]}")
340
+ ctx.output = ""
341
+ return
342
 
 
343
  if "<<<ANNOTATIONS>>>" in full_text:
344
  parts = full_text.split("<<<ANNOTATIONS>>>")
345
  ctx.output = parts[0].strip()
 
349
  ctx.annotations = json.loads(
350
  ann_text[ann_text.index("["):ann_text.rindex("]")+1]
351
  )
352
+ output_norm = _normalize_quotes(ctx.output)
353
  for ann in ctx.annotations:
354
  span = ann.get("span", "")
355
+ if not span:
356
+ ann["match_start"] = -1
357
+ ann["match_end"] = -1
358
+ continue
359
+ if span in ctx.output:
360
  ann["match_start"] = ctx.output.index(span)
361
  ann["match_end"] = ann["match_start"] + len(span)
362
+ continue
363
+ span_norm = _normalize_quotes(span)
364
+ if span_norm in output_norm:
365
+ idx = output_norm.index(span_norm)
366
+ ann["match_start"] = idx
367
+ ann["match_end"] = idx + len(span_norm)
368
  else:
369
  ann["match_start"] = -1
370
  ann["match_end"] = -1
371
+ except Exception:
372
  ctx.annotations = []
373
  else:
374
  ctx.output = full_text.strip()
375
 
376
 
377
  # ======================================================================
378
+ # Title (3 candidates, non-streaming LLM call)
379
+ # ======================================================================
380
+
381
+ TITLE_PROMPT = """给下面这篇文章起 3 个候选标题。
382
+
383
+ 【文章】
384
+ {article}
385
+
386
+ 【平台 ({platform})】
387
+ {platform_hint}
388
+
389
+ 【规则】
390
+ - 每个标题 8-22 字
391
+ - 3 个候选给出不同切入方式:具体场景、反差/悬念、观点陈述
392
+ - 不要 emoji、不要 #tag、不要书名号
393
+ - 不要用「值得一提的是」「不难发现」这类套话
394
+ - 围绕文章核心观点,不要跑题或夸大
395
+
396
+ 直接输出 JSON 数组,每个元素一个标题字符串:
397
+ ["标题1", "标题2", "标题3"]
398
+
399
+ 除了 JSON 不要输出任何其他内容。"""
400
+
401
+ TITLE_PLATFORM_HINTS = {
402
+ "xiaohongshu": (
403
+ "小红书:标题要有钩子,能让用户愿意点进来。"
404
+ "可以用反差、具体数字、第一人称、提问。"
405
+ "避免标题党,要和正文内容匹配。"
406
+ ),
407
+ "longform": (
408
+ "公众号/长文:标题要让读者一眼知道讲什么。"
409
+ "克制、准确、有观点。不要夸张和噱头。"
410
+ ),
411
+ }
412
+
413
+
414
+ class TitleStep:
415
+ def __init__(self, model_config=None):
416
+ self.model_config = model_config or TITLE_MODEL
417
+
418
+ def build_prompt(self, article: str, platform: str) -> str:
419
+ return TITLE_PROMPT.format(
420
+ article=article[:2000],
421
+ platform=platform,
422
+ platform_hint=TITLE_PLATFORM_HINTS.get(platform, TITLE_PLATFORM_HINTS["xiaohongshu"]),
423
+ )
424
+
425
+ def generate(self, article: str, platform: str = "xiaohongshu") -> List[str]:
426
+ if not article or len(article) < 30:
427
+ return []
428
+ prompt = self.build_prompt(article, platform)
429
+ try:
430
+ raw = call_model(self.model_config, prompt, max_tokens=400, temperature=0.8)
431
+ except Exception:
432
+ return []
433
+ if "[" not in raw or "]" not in raw:
434
+ return []
435
+ try:
436
+ arr = json.loads(raw[raw.index("["):raw.rindex("]")+1])
437
+ titles = [str(t).strip() for t in arr if isinstance(t, str) and t.strip()]
438
+ return titles[:3]
439
+ except Exception:
440
+ return []
441
+
442
+
443
+ # ======================================================================
444
+ # Fetch (URL → seed reference, standalone tool)
445
+ # ======================================================================
446
+
447
+ FETCH_SUMMARY_PROMPT = """下面是一篇网页文章的内容。请输出一段 200 字以内的中文摘要,保留主要观点和关键事实。
448
+
449
+ 【文章】
450
+ {content}
451
+
452
+ 【输出要求】
453
+ - 只输出摘要正文,不要标题、标签、markdown
454
+ - 200 字以内
455
+ - 保留文章核心论点和 2-3 条具体事实/数据
456
+ - 如果是外语,翻译为中文摘要"""
457
+
458
+
459
+ class FetchStep:
460
+ JINA_BASE = "https://r.jina.ai/"
461
+ FETCH_TIMEOUT = 20.0
462
+ MAX_CONTENT_CHARS = 6000
463
+
464
+ def __init__(self, model_config=None):
465
+ self.model_config = model_config or FETCH_MODEL
466
+
467
+ def _fetch_raw(self, url: str) -> Tuple[str, str]:
468
+ import httpx
469
+ if not url.startswith(("http://", "https://")):
470
+ raise ValueError("URL 必须以 http:// 或 https:// 开头")
471
+ reader_url = self.JINA_BASE + url
472
+ with httpx.Client(timeout=self.FETCH_TIMEOUT, follow_redirects=True) as client:
473
+ resp = client.get(reader_url, headers={"Accept": "text/plain"})
474
+ resp.raise_for_status()
475
+ body = resp.text
476
+
477
+ title = ""
478
+ content = body
479
+ lines = body.split("\n", 20)
480
+ for line in lines:
481
+ if line.startswith("Title:"):
482
+ title = line[6:].strip()
483
+ break
484
+ marker = "Markdown Content:"
485
+ if marker in body:
486
+ content = body.split(marker, 1)[1].strip()
487
+ content = content[: self.MAX_CONTENT_CHARS]
488
+ return title, content
489
+
490
+ def _summarize(self, content: str) -> str:
491
+ if not content or len(content) < 50:
492
+ return content.strip()
493
+ prompt = FETCH_SUMMARY_PROMPT.format(content=content)
494
+ try:
495
+ raw = call_model(self.model_config, prompt, max_tokens=500, temperature=0.3)
496
+ return raw.strip()[:500]
497
+ except Exception:
498
+ return content[:300].strip()
499
+
500
+ def fetch(self, url: str) -> Dict:
501
+ try:
502
+ title, content = self._fetch_raw(url)
503
+ except Exception as e:
504
+ return {"success": False, "url": url, "error": f"抓取失败: {str(e)[:200]}"}
505
+ if not content.strip():
506
+ return {"success": False, "url": url, "error": "内容为空或 Jina Reader 未返回正文"}
507
+ summary = self._summarize(content)
508
+ return {
509
+ "success": True,
510
+ "url": url,
511
+ "title": title,
512
+ "summary": summary,
513
+ }
514
+
515
+
516
+ # ======================================================================
517
+ # SlopCleanup (rule replacements, quote-aware)
518
  # ======================================================================
519
 
520
  class SlopCleanupStep:
 
522
  self.replacements = _config.RULE_CLEANER.word_replacements
523
 
524
  def clean(self, text: str) -> Tuple[str, Dict]:
525
+ preserved = []
526
+
527
+ def stash(m):
528
+ preserved.append(m.group(0))
529
+ return f"\x00{len(preserved)-1}\x00"
530
+
531
+ stashed = _QUOTE_SEGMENT_RE.sub(stash, text)
532
+
533
  replaced = []
534
  for ai_word, human_word in self.replacements.items():
535
+ if ai_word in stashed:
536
+ count = stashed.count(ai_word)
537
+ stashed = stashed.replace(ai_word, human_word)
538
  replaced.append({"from": ai_word, "to": human_word, "count": count})
539
+
540
+ def restore(m):
541
+ return preserved[int(m.group(1))]
542
+
543
+ final = re.sub(r'\x00(\d+)\x00', restore, stashed)
544
+
545
+ return final, {
546
  "replaced_words": replaced,
547
  "replaced_total": sum(r["count"] for r in replaced),
548
  }
549
 
550
 
551
  # ======================================================================
552
+ # Pipeline
553
  # ======================================================================
554
 
555
  class PipelineV6:
556
+ def __init__(self, synthesize_model=None, title_model=None, fetch_model=None):
557
+ self.synthesize = SynthesizeStep(model_config=synthesize_model)
558
+ self.title = TitleStep(model_config=title_model)
559
+ self.fetcher = FetchStep(model_config=fetch_model)
560
+ self.cleanup = SlopCleanupStep()
561
  self.slop_detect = SlopDetectStep()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
562
 
563
+ def stream_synth(self, seed: Dict, voice_profile: str = "",
564
+ platform: str = "xiaohongshu",
565
+ length: str = "medium") -> Generator[dict, None, None]:
566
+ """
567
+ Seed → finished article, streaming.
 
 
 
 
 
 
 
 
 
 
 
 
568
 
569
+ Events:
570
+ pipeline_start handshake, metadata
571
+ synthesize_token * every LLM token for UI streaming
572
+ pipeline_done final payload: output + annotations + titles +
573
+ slop_score + cleanup + errors + timings
574
+ """
575
+ pid = str(uuid.uuid4())[:12]
576
+ ctx = PipelineContext(
577
+ platform=platform,
578
+ seed=seed or {},
579
+ voice_profile=voice_profile or "",
580
+ length=length,
581
+ )
582
 
583
+ yield {
584
+ "type": "pipeline_start",
585
+ "ts": round(time.time(), 3),
586
+ "data": {
587
+ "pipeline_id": pid,
588
+ "has_voice_profile": bool(voice_profile),
589
+ "seed_keys": list((seed or {}).keys()),
590
+ "length": length,
591
+ },
592
+ }
593
 
 
594
  t0 = time.time()
595
+ for evt_type, evt_data in self.synthesize.process_stream(ctx):
596
+ yield {
597
+ "type": evt_type,
598
+ "ts": round(time.time(), 3),
599
+ "data": evt_data,
600
+ }
601
+ ctx.step_timings["synthesize"] = round(time.time() - t0, 2)
602
 
603
+ if ctx.output:
604
+ ctx.output, ctx.slop_cleanup = self.cleanup.clean(ctx.output)
605
+ ctx.slop_score, _ = self.slop_detect.detect(ctx.output)
606
+ t0 = time.time()
607
+ ctx.titles = self.title.generate(ctx.output, ctx.platform)
608
+ ctx.step_timings["title"] = round(time.time() - t0, 2)
609
+
610
+ yield {
611
+ "type": "pipeline_done",
612
+ "ts": round(time.time(), 3),
613
+ "data": {
614
+ "pipeline_id": pid,
615
+ "output": ctx.output,
616
+ "annotations": ctx.annotations,
617
+ "titles": ctx.titles,
618
+ "slop_score": ctx.slop_score,
619
+ "cleanup": ctx.slop_cleanup,
620
+ "errors": ctx.errors,
621
+ "step_timings": ctx.step_timings,
622
+ },
623
+ }
624
 
 
625
 
626
+ _pipeline: Optional[PipelineV6] = None
 
 
 
 
627
 
 
 
 
 
 
 
 
628
 
629
+ def get_pipeline() -> PipelineV6:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  global _pipeline
631
  if _pipeline is None:
632
+ _pipeline = PipelineV6()
633
  return _pipeline
requirements.txt CHANGED
@@ -4,6 +4,4 @@ sse-starlette==3.3.4
4
  pydantic==2.12.5
5
  python-dotenv==1.2.2
6
  openai==2.30.0
7
- chromadb==1.5.6
8
- sentence-transformers==5.3.0
9
  httpx==0.28.1
 
4
  pydantic==2.12.5
5
  python-dotenv==1.2.2
6
  openai==2.30.0
 
 
7
  httpx==0.28.1
server.py CHANGED
@@ -1,41 +1,39 @@
1
  """
2
- server.py — Aversion FastAPI MVP Server
3
 
4
- 端点:
5
- POST /api/v1/rewrite/stream — 全文改写 (SSE 流式)
6
- POST /api/v1/rewrite-span/stream — 局部改写 (SSE 流式)
7
- POST /api/v1/detect — AI slop 检测 (仅检测, 不改写)
8
- GET /health — 健康检查
9
- GET / — 项目信息
10
 
11
- 启动:
12
  uvicorn server:app --host 0.0.0.0 --port 8000
13
-
14
- 或:
15
- python server.py
16
  """
17
 
18
  import os
19
  import json
20
  import asyncio
21
- from typing import Optional
22
 
23
- from fastapi import FastAPI, HTTPException, Request
24
  from fastapi.middleware.cors import CORSMiddleware
25
  from fastapi.staticfiles import StaticFiles
 
26
  from pydantic import BaseModel, Field
27
  from sse_starlette.sse import EventSourceResponse
28
 
29
- from pipeline_v6 import PipelineV6, PipelineContext, SlopDetectStep, get_pipeline
30
 
31
 
32
  app = FastAPI(
33
  title="Aversion API",
34
- description="Chinese AI Content Quality Engine — MVP",
35
- version="0.1.0",
36
  )
37
 
38
- # CORS — MVP 允许所有来源, 上线前收紧
39
  app.add_middleware(
40
  CORSMiddleware,
41
  allow_origins=["*"],
@@ -49,35 +47,45 @@ app.add_middleware(
49
  # Request schemas
50
  # ======================================================================
51
 
52
- class RewriteRequest(BaseModel):
53
- text: str = Field(..., min_length=50, max_length=10000)
54
- platform: str = Field("xiaohongshu", pattern="^(xiaohongshu|longform)$")
55
- industry: Optional[str] = Field(None, description="行业(可选,自动检测)")
 
 
 
 
 
 
 
 
56
 
57
 
 
 
 
 
 
 
58
 
59
- class DetectRequest(BaseModel):
60
- text: str = Field(..., min_length=1, max_length=10000,
61
- description="待检测的文本")
62
 
63
 
64
  # ======================================================================
65
- # Endpoints
66
  # ======================================================================
67
 
68
  @app.get("/")
69
  async def root():
70
  return {
71
  "name": "Aversion",
72
- "version": "0.1.0",
73
- "description": "Chinese AI Content Quality Engine",
74
- "methodology": "Fact-Reconstruct (事实 × 声音 × 手法)",
75
  "endpoints": {
76
- "analyze": "POST /api/v1/analyze",
77
- "rewrite_stream": "POST /api/v1/rewrite/stream",
78
- "rewrite_span_stream": "POST /api/v1/rewrite-span/stream",
79
- "detect": "POST /api/v1/detect",
80
- "health": "GET /health",
81
  },
82
  "docs": "/docs",
83
  }
@@ -85,105 +93,43 @@ async def root():
85
 
86
  @app.get("/health")
87
  async def health():
88
- """健康检查: 验证 pipeline 和 KB 都可用"""
89
  try:
90
- pipeline = get_pipeline()
91
- count = pipeline.intuition_retrieval.collection.count()
92
- return {
93
- "status": "ok",
94
- "pipeline": "v6",
95
- "intuition_db_count": count,
96
- }
97
  except Exception as e:
98
  raise HTTPException(status_code=503, detail=f"pipeline not ready: {e}")
99
 
100
 
101
- @app.post("/api/v1/detect")
102
- async def detect(req: DetectRequest):
103
- """
104
- AI slop 检测 (仅检测, 不改写).
105
-
106
- 纯规则扫描, 0 LLM 调用, 毫秒级.
107
- 返回 score, hits (top 15), total_hits.
108
- """
109
- try:
110
- detector = SlopDetectStep()
111
- score, hits = detector.detect(req.text)
112
- result = {"score": score, "hits": hits, "total_hits": len(hits)}
113
- return {
114
- "score": result.get("score", 0),
115
- "hits": result.get("hits", []),
116
- "total_hits": result.get("total_hits", 0),
117
- }
118
- except Exception as e:
119
- raise HTTPException(status_code=500, detail=f"detect failed: {e}")
120
-
121
-
122
- class AnalyzeRequest(BaseModel):
123
- text: str = Field(..., min_length=50, max_length=10000)
124
- platform: str = Field("xiaohongshu", pattern="^(xiaohongshu|longform)$")
125
-
126
-
127
- @app.post("/api/v1/analyze")
128
- async def analyze(req: AnalyzeRequest):
129
- """
130
- 分析文章: SlopDetect (instant) + InputAnalyze (LLM).
131
- 返回 slop hits + facts + industry + voice_hint.
132
- 用户可以修正后再调 /rewrite/stream.
133
- """
134
- from pipeline_v6 import SlopDetectStep, IntuitionRetrievalStep
135
-
136
- # SlopDetect (instant)
137
- detector = SlopDetectStep()
138
- score, hits = detector.detect(req.text)
139
-
140
- # Intuition Retrieval (0.5s) — auto-detect industry
141
- retrieval = IntuitionRetrievalStep(n_results=3)
142
- refs = retrieval.retrieve(req.text)
143
- industries = [r.get("industry", "") for r in refs]
144
- industry = max(set(industries), key=industries.count) if industries else "其他"
145
-
146
- return {
147
- "slop": {"score": score, "hits": hits, "total_hits": len(hits)},
148
- "industry": industry,
149
- "platform": req.platform,
150
- }
151
-
152
 
153
  def _next_or_none(gen):
154
- """线程安全的 next() — 返回 None 代替 StopIteration (避免 executor 传播问题)"""
155
  try:
156
  return next(gen)
157
  except StopIteration:
158
  return None
159
 
160
 
161
- async def sse_stream_rewrite(req: RewriteRequest):
162
- """
163
- 生成 SSE 事件流 (/rewrite/stream).
164
- 关键: pipeline 是同步代码 (blocking LLM 调用), 必须用 run_in_executor
165
- 把每次 next(generator) 放到线程池, 否则会阻塞 asyncio event loop 导致 SSE 无法 flush.
166
- """
167
  try:
168
  pipeline = get_pipeline()
169
- gen = pipeline.stream_run(
170
- req.text,
 
171
  platform=req.platform,
172
- industry=req.industry or "",
173
  )
174
  loop = asyncio.get_event_loop()
175
-
176
  while True:
177
  event = await loop.run_in_executor(None, _next_or_none, gen)
178
  if event is None:
179
  break
180
-
181
  yield {
182
  "event": event["type"],
183
  "data": json.dumps(event, ensure_ascii=False),
184
  }
185
-
186
-
187
  except ValueError as e:
188
  yield {
189
  "event": "error",
@@ -196,133 +142,54 @@ async def sse_stream_rewrite(req: RewriteRequest):
196
  }
197
 
198
 
199
- @app.post("/api/v1/rewrite/stream")
200
- async def rewrite_stream(req: RewriteRequest):
201
  """
202
- 全文改写 (SSE 流式).
203
-
204
- Response: text/event-stream. 事件序列:
205
- pipeline_start → step_start/done × 5 → pipeline_done
206
 
207
- Error:
208
- 400 (PipelineInputError): 输入校验失败
209
- 500: 内部异常
210
  """
211
- return EventSourceResponse(sse_stream_rewrite(req))
212
-
213
 
214
 
215
  # ======================================================================
216
- # 轻量 Span Rewrite (不走 pipeline, 直接调 LLM, 带已有 context)
217
  # ======================================================================
218
 
219
- class SpanQuickRequest(BaseModel):
220
- full_text: str
221
- start: int
222
- end: int
223
- feedback: str = ""
224
-
225
-
226
- @app.post("/api/v1/span-quick")
227
- async def span_quick(req: SpanQuickRequest):
228
  """
229
- 轻量局部改写 — 不走 pipeline, 直接调 LLM.
230
- full_text 本身就是最好的 context, LLM 读前后文即可理解声音/事实.
231
  """
232
- import asyncio
233
- from pipeline_v6 import call_model, REWRITE_MODEL, IntuitionRetrievalStep
234
-
235
- if req.start >= req.end or req.start < 0 or req.end > len(req.full_text):
236
- raise HTTPException(400, "span 越界")
237
-
238
- locked_before = req.full_text[:req.start]
239
- target_span = req.full_text[req.start:req.end]
240
- locked_after = req.full_text[req.end:]
241
-
242
- # Retrieve relevant writing intuition for this span
243
- intuition_hint = ""
244
- try:
245
- retrieval = IntuitionRetrievalStep(n_results=2)
246
- refs = retrieval.retrieve(target_span)
247
- if refs:
248
- hints = []
249
- for r in refs[:1]:
250
- import json as _json
251
- templates = _json.loads(r.get("templates", "[]"))
252
- if templates:
253
- hints.append(f"句式参考: {templates[0][:40]}")
254
- if r.get("trust_arc"):
255
- hints.append(f"信任弧线: {r['trust_arc'][:40]}")
256
- intuition_hint = "\n".join(hints)
257
- except:
258
- pass
259
-
260
- prompt = f"""重写文章的中间部分, 前后文锁定不变。
261
-
262
- 【前文】{locked_before[-300:] if len(locked_before) > 300 else locked_before}
263
-
264
- 【需要重写】{target_span}
265
-
266
- 【后文】{locked_after[:300] if len(locked_after) > 300 else locked_after}
267
-
268
- 【要求】{req.feedback or '让这段更自然, 更像真人写的'}
269
-
270
- {f'【写作参考】{chr(10)}{intuition_hint}' if intuition_hint else ''}
271
-
272
- 约束: 只改中间 | 无缝衔接 | 保留事实 | 字数±30% | 不要emoji/markdown | 直接输出"""
273
-
274
  loop = asyncio.get_event_loop()
275
- try:
276
- result = await loop.run_in_executor(
277
- None,
278
- lambda: call_model(REWRITE_MODEL, prompt, max_tokens=1024, temperature=0.7)
279
- )
280
- new_span = result.strip()
281
- new_text = locked_before + new_span + locked_after
282
-
283
- return {
284
- "new_text": new_text,
285
- "new_span": new_span,
286
- "explanation": f"已根据要求「{req.feedback or '更自然'}」重写了选中部分",
287
- }
288
- except Exception as e:
289
- return {"error": str(e)[:200]}
290
 
291
 
292
  # ======================================================================
293
- # Static files (本地测试页)
294
  # ======================================================================
295
 
296
- app.mount("/static", StaticFiles(directory="static"), name="static")
297
-
298
-
299
- @app.get("/test")
300
- async def test_page():
301
- """重定向到本地测试页"""
302
- from fastapi.responses import FileResponse
303
- return FileResponse("static/index.html")
304
-
305
 
306
- @app.get("/api/test-sse")
307
- async def test_sse():
308
- """最简 SSE 端点 — 验证浏览器能不能收事件"""
309
- async def gen():
310
- for i in range(3):
311
- yield {"event": "test", "data": json.dumps({"count": i, "msg": f"event {i}"})}
312
- await asyncio.sleep(1)
313
- return EventSourceResponse(gen())
314
 
315
 
316
  # ======================================================================
317
- # 开发启动
318
  # ======================================================================
319
 
320
  if __name__ == "__main__":
321
  import uvicorn
322
- # 预热 pipeline (第一次会加载 KB, 约 3-5s)
323
  print("预热 pipeline...")
324
  _ = get_pipeline()
325
  print("pipeline 就绪")
326
- print("测试页: http://localhost:8000/test")
327
  port = int(os.environ.get("PORT", 8000))
328
  uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
 
1
  """
2
+ server.py — Aversion FastAPI server (Synthesize pipeline).
3
 
4
+ Endpoints:
5
+ POST /api/v1/synthesize/stream — seed → finished article (SSE streaming)
6
+ POST /api/v1/fetch/url — Jina Reader URL → {title, summary} (JSON)
7
+ GET /health — health check
8
+ GET / — project info
 
9
 
10
+ Start:
11
  uvicorn server:app --host 0.0.0.0 --port 8000
12
+ # or: python server.py
 
 
13
  """
14
 
15
  import os
16
  import json
17
  import asyncio
18
+ from typing import List, Optional
19
 
20
+ from fastapi import FastAPI, HTTPException
21
  from fastapi.middleware.cors import CORSMiddleware
22
  from fastapi.staticfiles import StaticFiles
23
+ from fastapi.responses import FileResponse
24
  from pydantic import BaseModel, Field
25
  from sse_starlette.sse import EventSourceResponse
26
 
27
+ from pipeline_v6 import get_pipeline
28
 
29
 
30
  app = FastAPI(
31
  title="Aversion API",
32
+ description="Chinese AI writing engine — seed to finished article",
33
+ version="0.2.0",
34
  )
35
 
36
+ # MVP: open CORS. Tighten before production.
37
  app.add_middleware(
38
  CORSMiddleware,
39
  allow_origins=["*"],
 
47
  # Request schemas
48
  # ======================================================================
49
 
50
+ class SeedReference(BaseModel):
51
+ url: str
52
+ title: str = ""
53
+ summary: str = ""
54
+
55
+
56
+ class Seed(BaseModel):
57
+ topic: str = Field(..., min_length=1, max_length=200)
58
+ angle: str = Field("", max_length=300)
59
+ core_point: str = Field(..., min_length=1, max_length=500)
60
+ facts: List[str] = Field(default_factory=list)
61
+ references: List[SeedReference] = Field(default_factory=list)
62
 
63
 
64
+ class SynthesizeRequest(BaseModel):
65
+ seed: Seed
66
+ voice_profile: str = Field("", max_length=3000)
67
+ platform: str = Field("xiaohongshu", pattern="^(xiaohongshu|longform)$")
68
+ length: str = Field("medium", pattern="^(short|medium|long)$")
69
+
70
 
71
+ class FetchRequest(BaseModel):
72
+ url: str = Field(..., min_length=8, max_length=2000)
 
73
 
74
 
75
  # ======================================================================
76
+ # Root / health
77
  # ======================================================================
78
 
79
  @app.get("/")
80
  async def root():
81
  return {
82
  "name": "Aversion",
83
+ "version": "0.2.0",
84
+ "description": "Seed → finished Chinese article",
 
85
  "endpoints": {
86
+ "synthesize_stream": "POST /api/v1/synthesize/stream",
87
+ "fetch_url": "POST /api/v1/fetch/url",
88
+ "health": "GET /health",
 
 
89
  },
90
  "docs": "/docs",
91
  }
 
93
 
94
  @app.get("/health")
95
  async def health():
 
96
  try:
97
+ _ = get_pipeline()
98
+ return {"status": "ok", "pipeline": "v6-synthesize"}
 
 
 
 
 
99
  except Exception as e:
100
  raise HTTPException(status_code=503, detail=f"pipeline not ready: {e}")
101
 
102
 
103
+ # ======================================================================
104
+ # Synthesize (SSE streaming)
105
+ # ======================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  def _next_or_none(gen):
108
+ """run_in_executor-safe iterator pull. Returns None on StopIteration."""
109
  try:
110
  return next(gen)
111
  except StopIteration:
112
  return None
113
 
114
 
115
+ async def _sse_synthesize(req: SynthesizeRequest):
 
 
 
 
 
116
  try:
117
  pipeline = get_pipeline()
118
+ gen = pipeline.stream_synth(
119
+ seed=req.seed.model_dump(),
120
+ voice_profile=req.voice_profile,
121
  platform=req.platform,
122
+ length=req.length,
123
  )
124
  loop = asyncio.get_event_loop()
 
125
  while True:
126
  event = await loop.run_in_executor(None, _next_or_none, gen)
127
  if event is None:
128
  break
 
129
  yield {
130
  "event": event["type"],
131
  "data": json.dumps(event, ensure_ascii=False),
132
  }
 
 
133
  except ValueError as e:
134
  yield {
135
  "event": "error",
 
142
  }
143
 
144
 
145
+ @app.post("/api/v1/synthesize/stream")
146
+ async def synthesize_stream(req: SynthesizeRequest):
147
  """
148
+ Seed → finished article (SSE).
 
 
 
149
 
150
+ Events:
151
+ pipeline_start → synthesize_token * N → pipeline_done
152
+ (error on failure)
153
  """
154
+ return EventSourceResponse(_sse_synthesize(req))
 
155
 
156
 
157
  # ======================================================================
158
+ # Fetch URL (standalone JSON)
159
  # ======================================================================
160
 
161
+ @app.post("/api/v1/fetch/url")
162
+ async def fetch_url(req: FetchRequest):
 
 
 
 
 
 
 
163
  """
164
+ Jina Reader → {title, summary, url}. ~3-5s.
165
+ Returns {success: bool, url, title?, summary?, error?}.
166
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  loop = asyncio.get_event_loop()
168
+ pipeline = get_pipeline()
169
+ result = await loop.run_in_executor(None, pipeline.fetcher.fetch, req.url)
170
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
 
173
  # ======================================================================
174
+ # Static test page
175
  # ======================================================================
176
 
177
+ if os.path.isdir("static"):
178
+ app.mount("/static", StaticFiles(directory="static"), name="static")
 
 
 
 
 
 
 
179
 
180
+ @app.get("/test")
181
+ async def test_page():
182
+ return FileResponse("static/index.html")
 
 
 
 
 
183
 
184
 
185
  # ======================================================================
186
+ # Dev entry
187
  # ======================================================================
188
 
189
  if __name__ == "__main__":
190
  import uvicorn
 
191
  print("预热 pipeline...")
192
  _ = get_pipeline()
193
  print("pipeline 就绪")
 
194
  port = int(os.environ.get("PORT", 8000))
195
  uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")