Curious1008 commited on
Commit
7717bf5
·
verified ·
1 Parent(s): bc93cfb

Upload server.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. server.py +328 -0
server.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=["*"],
42
+ allow_credentials=False,
43
+ allow_methods=["GET", "POST", "OPTIONS"],
44
+ allow_headers=["*"],
45
+ )
46
+
47
+
48
+ # ======================================================================
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
+ }
84
+
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",
190
+ "data": json.dumps({"type": "error", "code": 400, "message": str(e)}, ensure_ascii=False),
191
+ }
192
+ except Exception as e:
193
+ yield {
194
+ "event": "error",
195
+ "data": json.dumps({"type": "error", "code": 500, "message": f"internal: {e}"}, ensure_ascii=False),
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")