File size: 5,840 Bytes
7717bf5
61159a3
7717bf5
61159a3
 
 
 
 
7717bf5
61159a3
7717bf5
61159a3
7717bf5
 
 
 
 
61159a3
7717bf5
61159a3
7717bf5
 
61159a3
7717bf5
 
 
61159a3
7717bf5
 
 
 
61159a3
 
7717bf5
 
61159a3
7717bf5
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
 
 
 
 
 
 
 
 
 
 
 
7717bf5
 
61159a3
 
 
 
 
 
7717bf5
61159a3
 
7717bf5
 
 
61159a3
7717bf5
 
 
 
 
 
61159a3
 
7717bf5
61159a3
 
 
7717bf5
 
 
 
 
 
 
 
61159a3
 
7717bf5
 
 
 
61159a3
 
 
7717bf5
 
61159a3
7717bf5
 
 
 
 
 
61159a3
7717bf5
 
61159a3
 
 
7717bf5
61159a3
7717bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61159a3
 
7717bf5
61159a3
7717bf5
61159a3
 
 
7717bf5
61159a3
7717bf5
 
 
61159a3
7717bf5
 
61159a3
 
7717bf5
61159a3
 
7717bf5
 
61159a3
 
 
7717bf5
 
 
61159a3
7717bf5
 
61159a3
 
7717bf5
61159a3
 
 
7717bf5
 
 
61159a3
7717bf5
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""
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")