Files
OpenMaopaoya/app/services/novel_pipeline.py
T

80 lines
3.2 KiB
Python

"""动态小说核心管线:实体抽取 → 角色建档 → 世界书注册。
不做 prompt 节省:抽取时给全量上下文,输出严格 JSON。
"""
import json
import re
from ..db.repos import enc, dec
from ..services.llm import LLMClient
EXTRACT_SYSTEM = """你是小说叙事的结构化信息抽取器。给定一段剧情文本,抽取其中出现的【新角色】。
规则:
1. 只抽取具名的、有独立人格的角色(路人甲除外)。
2. 对每个新角色输出完整档案,宁全勿缺。
3. 只输出 JSON 数组,无新角色输出 []。格式:
[{"name":"角色名","identity":"身份/职业","appearance":"外貌描述(用于生图,详细)",
"personality":"性格","speaking_style":"说话风格","relation":"与主角的关系",
"voice":"从这些音色中选一个最合适的: tongtong/xiaoyu/xiaochen/laowang/xiaolin",
"first_impression":"该角色登场时的场景一句话"}]
4. 不要臆造原文没有的角色。"""
ADD_PROMPT = """你是小说世界的管理员。剧情中新角色「{name}」已建档,请为世界书写一条该角色的设定条目,"
"包含身份、性格、与主角关系,200字以内,直接输出条目正文,不要解释。"""
async def extract_new_characters(client: LLMClient, model: str,
recent_story: str) -> list[dict]:
text = await client.chat(model, [
{"role": "system", "content": EXTRACT_SYSTEM},
{"role": "user", "content": recent_story},
], temperature=0.1, max_tokens=4096)
m = re.search(r"\[.*\]", text, re.S)
if not m:
return []
try:
data = json.loads(m.group(0))
return [d for d in data if isinstance(d, dict) and d.get("name")]
except json.JSONDecodeError:
return []
def build_character(user_id: int, novel_id: int, d: dict) -> dict:
"""抽取结果 -> Character 行数据(不含加密字段)"""
return {
"user_id": user_id,
"name": d["name"][:64],
"persona": (f"身份:{d.get('identity','未知')}\n性格:{d.get('personality','')}\n"
f"说话风格:{d.get('speaking_style','')}\n与主角关系:{d.get('relation','')}\n"
f"登场:{d.get('first_impression','')}"),
"voice": d.get("voice") or "tongtong",
"source": "novel_auto",
"novel_id": novel_id,
}
async def gen_avatar(client: LLMClient, model: str, appearance: str) -> str:
if not model:
return ""
prompt = (f"动漫风格角色立绘,半身像,干净背景。角色外貌:{appearance}。"
f"高质量,细节丰富,柔和光影。")
try:
return await client.image(model, prompt)
except Exception:
return ""
def match_worldbook(entries: list, text: str, key: bytes | None) -> list[str]:
"""世界书命中:常驻 or 关键词命中"""
hits = []
for e in entries:
if not e.enabled:
continue
if e.constant:
hits.append(dec(key, e.content_enc))
continue
kws = [k.strip() for k in (e.keywords or "").split(",") if k.strip()]
if any(k in text for k in kws):
hits.append(dec(key, e.content_enc))
return hits