Files
xiaoan e3270bcd94 加入「拾语」:首页 AI 近况摘要(流式)
- 汇总学习目录、博客分类与最近更新的 10 篇文章
- 调用本地 Ollama qwen3.8:27b 生成技术栈与最近在做
- 每次生成入库,10 天后首次打开首页自动重新生成
- 前端逐字展开缓存摘要,过期时读取 AI 流式响应
- 首页在开场引导结束后显示;拾脉目录页内嵌展示
- 修复摘要面板标题栏命中全局 header 定位的问题
2026-11-21 13:56:53 +08:00

178 lines
5.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from datetime import timedelta
from django.conf import settings
from django.db.models import Count, Q
from django.utils import timezone
from blog.models import Category, Post
from mindmaps.models import MindFolder, MindMap
from .models import Digest
DIGEST_DAYS = max(1, int(getattr(settings, "DIGEST_INTERVAL_DAYS", 10)))
DIGEST_MODEL = getattr(settings, "DIGEST_MODEL", "qwen3.8:27b")
SYSTEM_PROMPT = """你是「拾语」,一个熟悉这个技术博客的整理者。请根据给出的站点数据,用中文写一份近况摘要。
请严格按下面两段输出,不要使用 Markdown 标题、列表符号或代码块:
技术栈:用 3-6 个短语概括主要技术方向,不超过 100 字,不要罗列所有文章标题。
最近在做:写 2-4 句话,像博客主人自己在更新近况,具体提到最近在学、在做的方向;不要编造数据,不要把技术栈逐条重复。
总字数控制在 250-450 字,不要输出 JSON 或额外解释。"""
def latest_digest():
return Digest.objects.filter(complete=True).order_by("-created_at").first()
def digest_is_stale(digest=None):
if digest is None:
return True
return timezone.now() - digest.created_at >= timedelta(days=DIGEST_DAYS)
def _folder_path(folder):
parts = []
seen = set()
node = folder
while node is not None and node.pk not in seen:
seen.add(node.pk)
parts.append(node.name)
node = node.parent
return " / ".join(reversed(parts))
def _map_info(item):
root = ""
data = item.mindmap_data or {}
if isinstance(data, dict):
root = ((data.get("data") or {}).get("text") or "").strip()
return {
"title": (item.title or "").strip()[:200],
"root": root[:100],
"description": (item.description or "").strip()[:200],
}
def build_snapshot():
folders = MindFolder.objects.prefetch_related("maps").order_by("name")
directories = []
for folder in folders:
directories.append({
"path": _folder_path(folder),
"description": (folder.description or "").strip()[:300],
"maps": [_map_info(item) for item in folder.maps.all()],
})
unfiled = [
_map_info(item)
for item in MindMap.objects.filter(folder__isnull=True).order_by("created_at")
]
categories = (
Category.objects.annotate(
published=Count(
"posts", filter=Q(posts__status="published"), distinct=True
)
)
.filter(published__gt=0)
.order_by("-published", "name")
)
latest_posts = (
Post.objects.filter(status="published")
.prefetch_related("categories")
.order_by("-updated_at", "-published_at")[:10]
)
return {
"generated_at": timezone.now().isoformat(),
"stats": {
"published_posts": Post.objects.filter(status="published").count(),
"categories": Category.objects.count(),
"folders": MindFolder.objects.count(),
"maps": MindMap.objects.count(),
},
"directories": directories,
"unfiled_maps": unfiled,
"blog_categories": [
{"name": category.name, "published": category.published}
for category in categories
],
"latest_posts": [
{
"title": post.title,
"categories": [category.name for category in post.categories.all()],
"published_at": post.published_at.isoformat() if post.published_at else "",
"updated_at": post.updated_at.isoformat() if post.updated_at else "",
}
for post in latest_posts
],
}
def snapshot_prompt(snapshot):
stats = snapshot.get("stats") or {}
lines = [
"站点概况:已发布文章 {} 篇,分类 {} 个,拾脉目录 {} 个,脑图 {} 份。".format(
stats.get("published_posts", 0),
stats.get("categories", 0),
stats.get("folders", 0),
stats.get("maps", 0),
),
"",
"## 学习目录(拾脉)",
]
directories = snapshot.get("directories") or []
if directories:
for directory in directories:
description = directory.get("description") or ""
maps = ";".join(
item.get("root") or item.get("title") or ""
for item in directory.get("maps") or []
)
line = "- {}".format(directory.get("path") or "未命名目录")
if description:
line += ":{}".format(description)
if maps:
line += ";脑图:{}".format(maps)
lines.append(line)
else:
lines.append("- 暂无目录")
unfiled = snapshot.get("unfiled_maps") or []
if unfiled:
lines.append(
"未归档脑图:{}".format(
";".join(item.get("root") or item.get("title") or "" for item in unfiled)
)
)
lines.extend(["", "## 博客分类(已发布数量)"])
categories = snapshot.get("blog_categories") or []
if categories:
for category in categories:
lines.append("- {}:{} 篇".format(category["name"], category["published"]))
else:
lines.append("- 暂无分类")
lines.extend(["", "## 最近更新的 10 篇文章"])
posts = snapshot.get("latest_posts") or []
if posts:
for index, post in enumerate(posts, 1):
category_names = "、".join(post.get("categories") or []) or "未分类"
updated = (post.get("updated_at") or "")[:10]
lines.append(
"{}. 《{}》({},更新于 {})".format(
index, post.get("title") or "", category_names, updated
)
)
else:
lines.append("- 暂无文章")
lines.extend([
"",
"请据此写出:技术栈,以及最近在做什么。",
])
return "\n".join(lines)