From e3270bcd9486acc794d514d7579814e7049d03c3 Mon Sep 17 00:00:00 2001 From: xiaoan <419177984@qq.com> Date: Sat, 21 Nov 2026 13:56:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E3=80=8C=E6=8B=BE=E8=AF=AD?= =?UTF-8?q?=E3=80=8D=EF=BC=9A=E9=A6=96=E9=A1=B5=20AI=20=E8=BF=91=E5=86=B5?= =?UTF-8?q?=E6=91=98=E8=A6=81=EF=BC=88=E6=B5=81=E5=BC=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 汇总学习目录、博客分类与最近更新的 10 篇文章 - 调用本地 Ollama qwen3.8:27b 生成技术栈与最近在做 - 每次生成入库,10 天后首次打开首页自动重新生成 - 前端逐字展开缓存摘要,过期时读取 AI 流式响应 - 首页在开场引导结束后显示;拾脉目录页内嵌展示 - 修复摘要面板标题栏命中全局 header 定位的问题 --- blog/templates/base2.html | 6 +- blog/views.py | 10 +- blogsite/settings.py | 5 + blogsite/urls.py | 1 + digest/__init__.py | 0 digest/admin.py | 15 ++ digest/apps.py | 7 + digest/migrations/0001_initial.py | 55 ++++++ digest/migrations/__init__.py | 0 digest/models.py | 20 ++ digest/services.py | 177 +++++++++++++++++ digest/static/digest/digest.css | 165 ++++++++++++++++ digest/static/digest/digest.js | 262 +++++++++++++++++++++++++ digest/templates/digest/_panel.html | 29 +++ digest/urls.py | 9 + digest/views.py | 117 +++++++++++ explore/llm.py | 65 ++++++ mindmaps/templates/mindmaps/index.html | 4 + mindmaps/views.py | 7 + 19 files changed, 951 insertions(+), 3 deletions(-) create mode 100644 digest/__init__.py create mode 100644 digest/admin.py create mode 100644 digest/apps.py create mode 100644 digest/migrations/0001_initial.py create mode 100644 digest/migrations/__init__.py create mode 100644 digest/models.py create mode 100644 digest/services.py create mode 100644 digest/static/digest/digest.css create mode 100644 digest/static/digest/digest.js create mode 100644 digest/templates/digest/_panel.html create mode 100644 digest/urls.py create mode 100644 digest/views.py diff --git a/blog/templates/base2.html b/blog/templates/base2.html index cccc0d3..87b81b5 100644 --- a/blog/templates/base2.html +++ b/blog/templates/base2.html @@ -4,6 +4,7 @@ + 思维导航 · 我的博客 @@ -13,6 +14,7 @@ + {% block extra_css %}{% endblock %} @@ -186,7 +188,8 @@ 写作台 - + +{% include "digest/_panel.html" %} @@ -199,6 +202,7 @@ --> + {% block extra_js %}{% endblock %} diff --git a/blog/views.py b/blog/views.py index 50b46a7..97e26cb 100644 --- a/blog/views.py +++ b/blog/views.py @@ -8,6 +8,7 @@ from django.utils.html import strip_tags from .models import Category, Post, Tag , SiteInfo from explore.models import Idea, Repository from mindmaps.models import MindMap +from digest.services import DIGEST_DAYS, DIGEST_MODEL, digest_is_stale, latest_digest def category_list(request): # """首页:展示所有分类""" @@ -39,12 +40,17 @@ def category_list(request): + digest = latest_digest() + return render(request, 'base2.html', { # 'categories': categories, 'total_posts': total_posts, # 文章总数 'total_categories': total_categories, # 分类总数 - 'mindmap_count' : mindmap_count - + 'mindmap_count' : mindmap_count, + 'digest': digest, + 'digest_stale': digest_is_stale(digest), + 'digest_days': DIGEST_DAYS, + 'digest_model': DIGEST_MODEL, }) diff --git a/blogsite/settings.py b/blogsite/settings.py index 1bae638..be8869a 100644 --- a/blogsite/settings.py +++ b/blogsite/settings.py @@ -46,6 +46,7 @@ INSTALLED_APPS = [ "reflections", "moments", "studio", + "digest", "rest_framework", ] @@ -212,6 +213,10 @@ OLLAMA_TIMEOUT = int(os.environ.get("OLLAMA_TIMEOUT", "90")) # qwen3.5 默认会先输出思考过程;关掉才能稳定拿到 JSON OLLAMA_THINK = os.environ.get("OLLAMA_THINK", "0") == "1" +# ===== 拾语:首页 AI 近况摘要 ===== +DIGEST_MODEL = os.environ.get("DIGEST_MODEL", "qwen3.8:27b") +DIGEST_INTERVAL_DAYS = int(os.environ.get("DIGEST_INTERVAL_DAYS", "10")) + # ===== GitHub 仓库搜索 ===== GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "") GITHUB_TIMEOUT = int(os.environ.get("GITHUB_TIMEOUT", "20")) diff --git a/blogsite/urls.py b/blogsite/urls.py index 37bd9cb..59de230 100644 --- a/blogsite/urls.py +++ b/blogsite/urls.py @@ -37,6 +37,7 @@ urlpatterns = [ path('reflections/', include('reflections.urls')), path('moments/', include('moments.urls')), path('manage/', include('studio.urls')), + path('digest/', include('digest.urls')), path('', include('blog.urls')), path("mindmaps/", include("mindmaps.urls")), path("api/",include("api.urls")), diff --git a/digest/__init__.py b/digest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/digest/admin.py b/digest/admin.py new file mode 100644 index 0000000..f596e97 --- /dev/null +++ b/digest/admin.py @@ -0,0 +1,15 @@ +from django.contrib import admin + +from .models import Digest + + +@admin.register(Digest) +class DigestAdmin(admin.ModelAdmin): + list_display = ("id", "model", "complete", "created_at", "short_content") + list_filter = ("complete", "model", "created_at") + readonly_fields = ("created_at",) + search_fields = ("content",) + + @admin.display(description="摘要") + def short_content(self, obj): + return obj.content[:80] diff --git a/digest/apps.py b/digest/apps.py new file mode 100644 index 0000000..a473cb8 --- /dev/null +++ b/digest/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class DigestConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "digest" + verbose_name = "拾语" diff --git a/digest/migrations/0001_initial.py b/digest/migrations/0001_initial.py new file mode 100644 index 0000000..467be68 --- /dev/null +++ b/digest/migrations/0001_initial.py @@ -0,0 +1,55 @@ +# Generated by Django 5.2.18 on 2026-11-21 05:33 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [] + + operations = [ + migrations.CreateModel( + name="Digest", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("content", models.TextField(verbose_name="摘要")), + ( + "model", + models.CharField( + default="qwen3.8:27b", max_length=100, verbose_name="模型" + ), + ), + ( + "snapshot", + models.JSONField(blank=True, default=dict, verbose_name="数据快照"), + ), + ( + "complete", + models.BooleanField(default=True, verbose_name="完整生成"), + ), + ( + "error", + models.TextField(blank=True, default="", verbose_name="错误"), + ), + ( + "created_at", + models.DateTimeField(auto_now_add=True, verbose_name="生成时间"), + ), + ], + options={ + "verbose_name": "近况摘要", + "verbose_name_plural": "近况摘要", + "ordering": ["-created_at"], + }, + ), + ] diff --git a/digest/migrations/__init__.py b/digest/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/digest/models.py b/digest/models.py new file mode 100644 index 0000000..4774c3b --- /dev/null +++ b/digest/models.py @@ -0,0 +1,20 @@ +from django.db import models + + +class Digest(models.Model): + """一次 AI 近况摘要的生成结果。""" + + content = models.TextField("摘要") + model = models.CharField("模型", max_length=100, default="qwen3.8:27b") + snapshot = models.JSONField("数据快照", default=dict, blank=True) + complete = models.BooleanField("完整生成", default=True) + error = models.TextField("错误", blank=True, default="") + created_at = models.DateTimeField("生成时间", auto_now_add=True) + + class Meta: + ordering = ["-created_at"] + verbose_name = "近况摘要" + verbose_name_plural = "近况摘要" + + def __str__(self): + return self.content[:60] diff --git a/digest/services.py b/digest/services.py new file mode 100644 index 0000000..86b671e --- /dev/null +++ b/digest/services.py @@ -0,0 +1,177 @@ +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) diff --git a/digest/static/digest/digest.css b/digest/static/digest/digest.css new file mode 100644 index 0000000..8cf81f9 --- /dev/null +++ b/digest/static/digest/digest.css @@ -0,0 +1,165 @@ +/* ========================================================= + 拾语 · 首页 AI 近况摘要 + ========================================================= */ + +.dg-panel { + position: fixed; + left: 20px; + bottom: 54px; + z-index: 30; + display: flex; + flex-direction: column; + width: 340px; + max-height: 42vh; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 16px; + background: var(--card); + box-shadow: var(--card-shadow); + font-family: Inter, 'Noto Sans SC', -apple-system, 'PingFang SC', sans-serif; + transition: width .25s ease, box-shadow .25s ease, + opacity .45s ease, visibility .45s ease; +} + +/* 首页:开场引导层结束、脑图展开后才显示 */ +body:not(.intro-done) .dg-panel:not(.dg-panel-inline) { + opacity: 0; + visibility: hidden; + pointer-events: none; +} +body.intro-done .dg-panel:not(.dg-panel-inline) { + opacity: 1; + visibility: visible; +} +.dg-panel:hover { box-shadow: 0 20px 44px -28px rgba(0, 0, 0, .5); } + +.dg-head { + display: flex; + align-items: center; + gap: 7px; + flex: none; + padding: 9px 11px 9px 13px; + cursor: pointer; + user-select: none; + border-bottom: 1px solid var(--line); +} +.dg-spark { color: var(--c2); font-size: 10px; } +.dg-title { + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 12.5px; + font-weight: 700; + letter-spacing: .05em; +} +.dg-badge { + margin-left: auto; + padding: 1px 6px; + border: 1px solid var(--line); + border-radius: 999px; + color: var(--ink-faint); + font-size: 8.5px; + letter-spacing: .04em; + white-space: nowrap; +} +.dg-toggle { + display: grid; + place-items: center; + width: 20px; height: 20px; + padding: 0; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--bg); + color: var(--ink-faint); + font-family: inherit; + font-size: 12px; + line-height: 1; + cursor: pointer; + transition: color .18s ease, border-color .18s ease; +} +.dg-toggle:hover { color: var(--accent); border-color: var(--accent); } + +.dg-body { + min-height: 0; + padding: 10px 14px 12px; + overflow-y: auto; + scrollbar-width: thin; + scrollbar-color: var(--line) transparent; +} +.dg-text { + margin: 0; + color: var(--ink-soft); + font-family: 'Noto Serif SC', serif; + font-size: 12.2px; + line-height: 1.92; + white-space: pre-wrap; + word-break: break-word; + text-wrap: pretty; +} +.dg-text:empty::before { + content: '正在整理最近的目录和文章…'; + color: var(--ink-faint); +} +.dg-meta { + margin: 8px 0 0; + padding-top: 7px; + border-top: 1px dashed var(--line); + color: var(--ink-faint); + font-family: Inter, sans-serif; + font-size: 9.5px; + line-height: 1.7; +} + +.dg-panel.is-streaming .dg-text::after { + content: '▍'; + margin-left: 1px; + color: var(--accent); + animation: dg-blink 1s steps(1) infinite; +} +.dg-panel.is-streaming .dg-badge { + color: var(--accent); + border-color: color-mix(in srgb, var(--accent) 35%, var(--line)); +} + +.dg-panel.is-collapsed { width: 220px; } +.dg-panel.is-collapsed .dg-body { display: none; } + +/* 拾脉目录页:内嵌卡片,不悬浮遮挡目录 */ +.dg-panel.dg-panel-inline { + position: static; + left: auto; + right: auto; + bottom: auto; + width: auto; + max-height: none; + margin: 22px 0 4px; + box-shadow: var(--shadow-sm); +} +.dg-panel.dg-panel-inline.is-collapsed { width: auto; } +.dg-panel.dg-panel-inline .dg-body { max-height: 340px; } +.dg-panel.is-collapsed .dg-head { border-bottom-color: transparent; } +.dg-panel.is-collapsed .dg-badge { display: none; } + +@keyframes dg-blink { + 0%, 49% { opacity: 1; } + 50%, 100% { opacity: 0; } +} + +@media (max-width: 720px) { + .dg-panel { + left: 12px; + right: 12px; + bottom: 72px; + width: auto; + max-height: 34vh; + } + .dg-panel.is-collapsed { + left: 12px; + right: auto; + width: 210px; + } +} + +@media (prefers-reduced-motion: reduce) { + .dg-panel { transition: none; } + .dg-panel.is-streaming .dg-text::after { animation: none; } +} diff --git a/digest/static/digest/digest.js b/digest/static/digest/digest.js new file mode 100644 index 0000000..da08b7e --- /dev/null +++ b/digest/static/digest/digest.js @@ -0,0 +1,262 @@ +/* ========================================================= + 拾语 · 首页 / 拾脉目录页 AI 近况摘要 + - 首页:开场引导层结束后才出现 + - 缓存摘要由前端逐字展开,不是一次性塞入 + - 过期时真正流式生成 + ========================================================= */ +(function () { + 'use strict'; + + var panel = document.getElementById('digestPanel'); + if (!panel) return; + + var textEl = document.getElementById('digestText'); + var metaEl = document.getElementById('digestMeta'); + var head = document.getElementById('digestHead'); + var toggle = document.getElementById('digestToggle'); + var csrfMeta = document.querySelector('meta[name="csrf-token"]'); + var CSRF = csrfMeta ? csrfMeta.getAttribute('content') || '' : ''; + var streamUrl = panel.getAttribute('data-stream-url'); + var stale = panel.getAttribute('data-stale') === 'true'; + var days = panel.getAttribute('data-days') || '10'; + var model = panel.getAttribute('data-model') || 'qwen3.8:27b'; + var isInline = panel.classList.contains('dg-panel-inline'); + var reduced = window.matchMedia + && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + var initialMeta = metaEl ? metaEl.textContent.trim() : ''; + var attempts = 0; + var maxAttempts = 20; + var initialContent = ''; + + var initialScript = document.getElementById('digest-initial'); + if (initialScript) { + try { + initialContent = JSON.parse(initialScript.textContent); + } catch (error) { + initialContent = ''; + } + } + + /* ---------- 折叠 ---------- */ + function setCollapsed(collapsed) { + panel.classList.toggle('is-collapsed', collapsed); + if (toggle) toggle.textContent = collapsed ? '+' : '−'; + if (head) head.setAttribute('aria-expanded', collapsed ? 'false' : 'true'); + try { + localStorage.setItem('digest-collapsed-v2', collapsed ? '1' : '0'); + } catch (error) {} + } + + try { + if (localStorage.getItem('digest-collapsed-v2') === '1') { + panel.classList.add('is-collapsed'); + if (toggle) toggle.textContent = '+'; + if (head) head.setAttribute('aria-expanded', 'false'); + } + } catch (error) {} + + function flip() { + setCollapsed(!panel.classList.contains('is-collapsed')); + } + + if (head) { + head.addEventListener('click', function (event) { + if (event.target.closest('button')) return; + flip(); + }); + head.addEventListener('keydown', function (event) { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + flip(); + } + }); + } + if (toggle) { + toggle.addEventListener('click', function (event) { + event.stopPropagation(); + flip(); + }); + } + + /* ---------- 等首页引导层结束 ---------- */ + function waitForIntro() { + if (isInline) return Promise.resolve(); + + var intro = document.getElementById('intro'); + if (!intro || document.body.classList.contains('intro-done')) { + return Promise.resolve(); + } + + return new Promise(function (resolve) { + var done = false; + var poll = null; + + function finish() { + if (done) return; + done = true; + observer.disconnect(); + if (poll) clearInterval(poll); + resolve(); + } + + var observer = new MutationObserver(function () { + if (document.body.classList.contains('intro-done')) finish(); + }); + observer.observe(document.body, { + attributes: true, + attributeFilter: ['class'] + }); + + poll = setInterval(function () { + if (!document.getElementById('intro') || document.body.classList.contains('intro-done')) { + finish(); + } + }, 350); + }); + } + + waitForIntro().then(function () { + if (stale) { + startStream(); + } else if (initialContent) { + typewrite(initialContent); + } + }); + + /* ---------- 前端逐字展开 ---------- */ + function typewrite(text) { + if (!textEl || !text) return; + + if (reduced) { + textEl.textContent = text; + return; + } + + textEl.textContent = ''; + panel.classList.add('is-streaming'); + if (metaEl) metaEl.textContent = '展开摘要…'; + + var index = 0; + var timer = setInterval(function () { + index += 2; + textEl.textContent = text.slice(0, index); + scrollBody(); + + if (index >= text.length) { + clearInterval(timer); + textEl.textContent = text; + panel.classList.remove('is-streaming'); + if (metaEl) metaEl.textContent = initialMeta; + } + }, 18); + } + + function scrollBody() { + var body = document.getElementById('digestBody'); + if (body) body.scrollTop = body.scrollHeight; + } + + /* ---------- 过期后真正流式生成 ---------- */ + async function startStream() { + if (!streamUrl) return; + + attempts += 1; + panel.classList.add('is-streaming'); + if (attempts === 1 && textEl) textEl.textContent = ''; + if (metaEl) { + metaEl.textContent = attempts === 1 + ? '正在整理最近的目录和文章…' + : '其他窗口正在整理,稍后继续…'; + } + + var response; + try { + response = await fetch(streamUrl, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Accept': 'text/plain', + 'X-CSRFToken': CSRF + } + }); + } catch (error) { + finishError('网络中断,刷新页面重试'); + return; + } + + if (response.status === 409) { + panel.classList.remove('is-streaming'); + if (attempts < maxAttempts) { + if (metaEl) metaEl.textContent = '其他窗口正在整理,稍后继续…'; + setTimeout(startStream, 6000); + } else { + finishError('整理排队超时,刷新页面重试'); + } + return; + } + + if (!response.ok) { + var message = '整理失败,刷新页面重试'; + try { + var data = await response.json(); + if (data && data.error) message = data.error; + } catch (error) {} + finishError(message); + return; + } + + if (!response.body || !response.body.getReader) { + try { + var fullText = await response.text(); + if (textEl) textEl.textContent = fullText.trim(); + if (fullText.indexOf('[整理中断') !== -1) { + finishError('AI 整理中断,刷新页面重试'); + } else { + finishOk(); + } + } catch (error) { + finishError('整理失败,刷新页面重试'); + } + return; + } + + var reader = response.body.getReader(); + var decoder = new TextDecoder(); + var full = ''; + + try { + while (true) { + var result = await reader.read(); + if (result.done) break; + full += decoder.decode(result.value, { stream: true }); + if (textEl) { + textEl.textContent = full; + scrollBody(); + } + } + full += decoder.decode(); + if (textEl) textEl.textContent = full.trim(); + if (full.indexOf('[整理中断') !== -1) { + finishError('AI 整理中断,刷新页面重试'); + } else { + finishOk(); + } + } catch (error) { + finishError('整理中断,刷新页面重试'); + } + } + + function finishOk() { + panel.classList.remove('is-streaming'); + panel.classList.remove('is-stale'); + panel.setAttribute('data-stale', 'false'); + if (metaEl) { + metaEl.textContent = '刚刚更新 · ' + model + ' · 每 ' + days + ' 天更新'; + } + } + + function finishError(message) { + panel.classList.remove('is-streaming'); + if (metaEl) metaEl.textContent = message; + } +})(); diff --git a/digest/templates/digest/_panel.html b/digest/templates/digest/_panel.html new file mode 100644 index 0000000..a41eefa --- /dev/null +++ b/digest/templates/digest/_panel.html @@ -0,0 +1,29 @@ +{% comment %}拾语:AI 近况摘要。homepage 用固定浮层;拾脉目录页用内嵌卡片。{% endcomment %} + diff --git a/digest/urls.py b/digest/urls.py new file mode 100644 index 0000000..89fb9b4 --- /dev/null +++ b/digest/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views + +app_name = "digest" + +urlpatterns = [ + path("stream/", views.stream, name="stream"), +] diff --git a/digest/views.py b/digest/views.py new file mode 100644 index 0000000..7f99a52 --- /dev/null +++ b/digest/views.py @@ -0,0 +1,117 @@ +from django.core.cache import cache +from django.http import HttpResponse, JsonResponse, StreamingHttpResponse +from django.views.decorators.http import require_POST + +from explore.llm import LLMError, chat_stream + +from .models import Digest +from .services import ( + DIGEST_MODEL, + SYSTEM_PROMPT, + build_snapshot, + digest_is_stale, + latest_digest, + snapshot_prompt, +) + +LOCK_KEY = "digest_generating" +LOCK_SECONDS = 600 + + +@require_POST +def stream(request): + latest = latest_digest() + if latest and not digest_is_stale(latest): + return HttpResponse(latest.content, content_type="text/plain; charset=utf-8") + + if not cache.add(LOCK_KEY, "1", LOCK_SECONDS): + return JsonResponse( + {"error": "正在整理,请稍后再试", "code": "busy"}, + status=409, + ) + + latest = latest_digest() + if latest and not digest_is_stale(latest): + cache.delete(LOCK_KEY) + return HttpResponse(latest.content, content_type="text/plain; charset=utf-8") + + try: + snapshot = build_snapshot() + user_prompt = snapshot_prompt(snapshot) + except Exception as exc: + cache.delete(LOCK_KEY) + return JsonResponse( + {"error": "整理数据失败:{}".format(exc), "code": "snapshot_failed"}, + status=500, + ) + + def generate(): + chunks = [] + saved = False + error_text = "" + + try: + for chunk in chat_stream( + SYSTEM_PROMPT, + user_prompt, + model=DIGEST_MODEL, + temperature=0.7, + num_predict=800, + timeout=300, + ): + chunks.append(chunk) + yield chunk + + content = "".join(chunks).strip() + if not content: + raise LLMError("AI 没有返回内容") + + Digest.objects.create( + content=content, + model=DIGEST_MODEL, + snapshot=snapshot, + complete=True, + ) + saved = True + except GeneratorExit: + raise + except Exception as exc: + error_text = str(exc)[:500] + partial = "".join(chunks).strip() + try: + Digest.objects.create( + content=partial, + model=DIGEST_MODEL, + snapshot=snapshot, + complete=False, + error=error_text, + ) + saved = True + except Exception: + pass + try: + yield "\n\n[整理中断:{}]".format(error_text) + except Exception: + pass + finally: + if not saved: + partial = "".join(chunks).strip() + try: + Digest.objects.create( + content=partial, + model=DIGEST_MODEL, + snapshot=snapshot, + complete=False, + error=error_text or "stream closed", + ) + except Exception: + pass + cache.delete(LOCK_KEY) + + response = StreamingHttpResponse( + generate(), + content_type="text/plain; charset=utf-8", + ) + response["Cache-Control"] = "no-cache" + response["X-Accel-Buffering"] = "no" + return response diff --git a/explore/llm.py b/explore/llm.py index eea8309..dc5c8a7 100644 --- a/explore/llm.py +++ b/explore/llm.py @@ -426,6 +426,71 @@ def chat_text(system, user, temperature=0.8, num_predict=200, timeout=30): return (message.get("content") or data.get("response") or "").strip() +def chat_stream(system, user, model=None, temperature=0.7, num_predict=800, timeout=300): + """流式对话:逐段 yield 文本,给「拾语」的首页摘要用。""" + payload = { + "model": model or settings.OLLAMA_MODEL, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "stream": True, + "options": {"temperature": temperature, "num_predict": num_predict}, + } + if not getattr(settings, "OLLAMA_THINK", False): + payload["think"] = False + + url = settings.OLLAMA_BASE_URL + "/api/chat" + request = urllib.request.Request( + url, + data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + + try: + response = urllib.request.urlopen(request, timeout=timeout) + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace")[:300] + logger.warning("Ollama stream HTTP %s: %s", exc.code, detail) + raise LLMUnavailable("模型服务返回了错误") from exc + except (socket.timeout, TimeoutError) as exc: + raise LLMTimeout() from exc + except urllib.error.URLError as exc: + if isinstance(exc.reason, (socket.timeout, TimeoutError)): + raise LLMTimeout() from exc + logger.warning("Ollama stream unreachable: %s", exc.reason) + raise LLMUnavailable("连不上模型服务") from exc + except OSError as exc: + logger.warning("Ollama stream network error: %s", exc) + raise LLMUnavailable("连不上模型服务") from exc + + try: + for raw_line in response: + line = raw_line.decode("utf-8", "replace").strip() + if not line: + continue + try: + data = json.loads(line) + except json.JSONDecodeError: + continue + if data.get("error"): + raise LLMUnavailable(str(data.get("error"))[:200]) + message = data.get("message") or {} + content = message.get("content") or data.get("response") or "" + if content: + yield content + if data.get("done"): + break + except (socket.timeout, TimeoutError) as exc: + raise LLMTimeout() from exc + finally: + try: + response.close() + except Exception: + pass + + def extract_spec(idea): """调模型 -> 结构化条件 -> 拼 GitHub 检索式。""" started = time.monotonic() diff --git a/mindmaps/templates/mindmaps/index.html b/mindmaps/templates/mindmaps/index.html index dc52a82..a9dd6d7 100644 --- a/mindmaps/templates/mindmaps/index.html +++ b/mindmaps/templates/mindmaps/index.html @@ -22,6 +22,8 @@
{{ stats.nodes }}节点
+ {% include "digest/_panel.html" %} +
{% if unlocked %} @@ -115,8 +117,10 @@ {% block extra_css %} + {% endblock %} {% block extra_js %} + {% endblock %} diff --git a/mindmaps/views.py b/mindmaps/views.py index 5ea79e3..8b6cc53 100644 --- a/mindmaps/views.py +++ b/mindmaps/views.py @@ -9,6 +9,7 @@ from django.utils.text import slugify from django.views.decorators.http import require_POST from cabinet.access import is_unlocked, minutes_left, unlock_minutes +from digest.services import DIGEST_DAYS, DIGEST_MODEL, digest_is_stale, latest_digest from .forms import MindFolderForm, MindMapEditForm, MindMapUploadForm, descendant_ids from .models import MindFolder, MindMap, make_slug, unique_slug @@ -57,10 +58,16 @@ def index(request): ) unfiled = MindMap.objects.filter(folder__isnull=True).order_by("created_at", "id") all_maps = MindMap.objects.all() + digest = latest_digest() context = { "folders": folders, "unfiled": unfiled, + "digest": digest, + "digest_stale": digest_is_stale(digest), + "digest_days": DIGEST_DAYS, + "digest_model": DIGEST_MODEL, + "digest_inline": True, "stats": { "folders": MindFolder.objects.count(), "maps": all_maps.count(),