aversion-api / server.py
Curious1008's picture
sync: v6 synthesize pipeline + slim deps (remove chroma)
61159a3 verified
Raw History Blame Contribute Delete
5.84 kB
"""
server.py β€” Aversion FastAPI server (Synthesize pipeline).
Endpoints:
POST /api/v1/synthesize/stream β€” seed β†’ finished article (SSE streaming)
POST /api/v1/fetch/url β€” Jina Reader URL β†’ {title, summary} (JSON)
GET /health β€” health check
GET / β€” project info
Start:
uvicorn server:app --host 0.0.0.0 --port 8000
# or: python server.py
"""
import os
import json
import asyncio
from typing import List, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from pipeline_v6 import get_pipeline
app = FastAPI(
title="Aversion API",
description="Chinese AI writing engine β€” seed to finished article",
version="0.2.0",
)
# MVP: open CORS. Tighten before production.
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
# ======================================================================
# Request schemas
# ======================================================================
class SeedReference(BaseModel):
url: str
title: str = ""
summary: str = ""
class Seed(BaseModel):
topic: str = Field(..., min_length=1, max_length=200)
angle: str = Field("", max_length=300)
core_point: str = Field(..., min_length=1, max_length=500)
facts: List[str] = Field(default_factory=list)
references: List[SeedReference] = Field(default_factory=list)
class SynthesizeRequest(BaseModel):
seed: Seed
voice_profile: str = Field("", max_length=3000)
platform: str = Field("xiaohongshu", pattern="^(xiaohongshu|longform)$")
length: str = Field("medium", pattern="^(short|medium|long)$")
class FetchRequest(BaseModel):
url: str = Field(..., min_length=8, max_length=2000)
# ======================================================================
# Root / health
# ======================================================================
@app.get("/")
async def root():
return {
"name": "Aversion",
"version": "0.2.0",
"description": "Seed β†’ finished Chinese article",
"endpoints": {
"synthesize_stream": "POST /api/v1/synthesize/stream",
"fetch_url": "POST /api/v1/fetch/url",
"health": "GET /health",
},
"docs": "/docs",
}
@app.get("/health")
async def health():
try:
_ = get_pipeline()
return {"status": "ok", "pipeline": "v6-synthesize"}
except Exception as e:
raise HTTPException(status_code=503, detail=f"pipeline not ready: {e}")
# ======================================================================
# Synthesize (SSE streaming)
# ======================================================================
def _next_or_none(gen):
"""run_in_executor-safe iterator pull. Returns None on StopIteration."""
try:
return next(gen)
except StopIteration:
return None
async def _sse_synthesize(req: SynthesizeRequest):
try:
pipeline = get_pipeline()
gen = pipeline.stream_synth(
seed=req.seed.model_dump(),
voice_profile=req.voice_profile,
platform=req.platform,
length=req.length,
)
loop = asyncio.get_event_loop()
while True:
event = await loop.run_in_executor(None, _next_or_none, gen)
if event is None:
break
yield {
"event": event["type"],
"data": json.dumps(event, ensure_ascii=False),
}
except ValueError as e:
yield {
"event": "error",
"data": json.dumps({"type": "error", "code": 400, "message": str(e)}, ensure_ascii=False),
}
except Exception as e:
yield {
"event": "error",
"data": json.dumps({"type": "error", "code": 500, "message": f"internal: {e}"}, ensure_ascii=False),
}
@app.post("/api/v1/synthesize/stream")
async def synthesize_stream(req: SynthesizeRequest):
"""
Seed β†’ finished article (SSE).
Events:
pipeline_start β†’ synthesize_token * N β†’ pipeline_done
(error on failure)
"""
return EventSourceResponse(_sse_synthesize(req))
# ======================================================================
# Fetch URL (standalone JSON)
# ======================================================================
@app.post("/api/v1/fetch/url")
async def fetch_url(req: FetchRequest):
"""
Jina Reader β†’ {title, summary, url}. ~3-5s.
Returns {success: bool, url, title?, summary?, error?}.
"""
loop = asyncio.get_event_loop()
pipeline = get_pipeline()
result = await loop.run_in_executor(None, pipeline.fetcher.fetch, req.url)
return result
# ======================================================================
# Static test page
# ======================================================================
if os.path.isdir("static"):
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/test")
async def test_page():
return FileResponse("static/index.html")
# ======================================================================
# Dev entry
# ======================================================================
if __name__ == "__main__":
import uvicorn
print("ι’„ηƒ­ pipeline...")
_ = get_pipeline()
print("pipeline ε°±η»ͺ")
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")