feat: add ai writing imitation mode
This commit is contained in:
1 parent
9268c73776
commit
bb6b9bd84b
22 files changed
+714
-30
No files matched your search
@@ -13,20 +13,30 @@ GET /api/ai-writing/article-types 列出所有文章类型
|
||||
POST /api/ai-writing/article-types 新增文章类型
|
||||
PATCH /api/ai-writing/article-types/{id} 更新文章类型
|
||||
DELETE /api/ai-writing/article-types/{id} 删除文章类型
|
||||
POST /api/ai-writing/sample/extract 提取样文仿写上传文件文本
|
||||
POST /api/ai-writing/admin/cleanup (admin)手动清理会话
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi import APIRouter, File, HTTPException, Request, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.authz import require_auth
|
||||
from deerflow.utils.file_conversion import CONVERTIBLE_EXTENSIONS, convert_file_to_markdown
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/ai-writing", tags=["ai-writing"])
|
||||
|
||||
_SAMPLE_TEXT_EXTENSIONS = {".txt", ".md", ".markdown"}
|
||||
_MAX_SAMPLE_BYTES = 20 * 1024 * 1024
|
||||
_MAX_SAMPLE_TEXT_CHARS = 120_000
|
||||
|
||||
# ── 请求/响应模型 ─────────────────────────────────────────────────────────────
|
||||
|
||||
class RenameSessionRequest(BaseModel):
|
||||
@@ -67,6 +77,13 @@ class SaveTranscriptRequest(BaseModel):
|
||||
transcript: dict
|
||||
|
||||
|
||||
class SampleExtractResponse(BaseModel):
|
||||
filename: str
|
||||
text: str
|
||||
char_count: int
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class ArticleTypeRequest(BaseModel):
|
||||
key: str
|
||||
label: str
|
||||
@@ -154,6 +171,52 @@ class SessionResponse(BaseModel):
|
||||
updated_at: str
|
||||
|
||||
|
||||
async def _extract_sample_text(file: UploadFile) -> tuple[str, str]:
|
||||
name = file.filename or "sample"
|
||||
ext = Path(name).suffix.lower()
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(status_code=400, detail="文件为空")
|
||||
if len(raw) > _MAX_SAMPLE_BYTES:
|
||||
raise HTTPException(status_code=413, detail=f"文件过大,最大支持 {_MAX_SAMPLE_BYTES // (1024 * 1024)}MB")
|
||||
|
||||
if ext in _SAMPLE_TEXT_EXTENSIONS:
|
||||
text = raw.decode("utf-8", errors="ignore")
|
||||
elif ext in CONVERTIBLE_EXTENSIONS:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp_path = Path(tmp) / f"sample{ext}"
|
||||
tmp_path.write_bytes(raw)
|
||||
md_path = await convert_file_to_markdown(tmp_path)
|
||||
if md_path is None:
|
||||
raise HTTPException(status_code=422, detail=f"无法解析文件:{name}")
|
||||
text = md_path.read_text(encoding="utf-8", errors="ignore")
|
||||
else:
|
||||
raise HTTPException(status_code=415, detail=f"不支持的文件类型:{ext or '未知'}(支持 doc/docx/pdf/md/txt)")
|
||||
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise HTTPException(status_code=422, detail="文件内容为空或无法提取文本")
|
||||
return name, text
|
||||
|
||||
|
||||
@router.post("/sample/extract", response_model=SampleExtractResponse)
|
||||
@require_auth
|
||||
async def extract_sample_article(request: Request, file: UploadFile = File(...)) -> SampleExtractResponse:
|
||||
"""Extract text from a sample article for AI-writing imitation mode."""
|
||||
_ = request
|
||||
name, text = await _extract_sample_text(file)
|
||||
char_count = len(text)
|
||||
truncated = char_count > _MAX_SAMPLE_TEXT_CHARS
|
||||
if truncated:
|
||||
text = text[:_MAX_SAMPLE_TEXT_CHARS]
|
||||
return SampleExtractResponse(
|
||||
filename=name,
|
||||
text=text,
|
||||
char_count=char_count,
|
||||
truncated=truncated,
|
||||
)
|
||||
|
||||
|
||||
# ── 路由 ──────────────────────────────────────────────────────────────────────
|
||||
@router.get("/sessions", response_model=list[SessionResponse])
|
||||
async def list_sessions(request: Request):
|
||||
|
||||
Reference in new issue
Block a user