1 Commits
v1.1 ... v2.0

Author SHA1 Message Date
87286986ea v2.0: 添加分类系统和标签系统,支持多类别多标签 2026-05-23 00:51:42 +08:00
4 changed files with 770 additions and 85 deletions

View File

@@ -1,19 +1,21 @@
# Article Writer - 文章编写系统
基于 Flask + LLM 的智能文章编写系统,支持主题管理、素材收集和大模型生成文章。
基于 Flask + LLM 的智能文章编写系统,支持主题管理、素材收集、分类标签和大模型生成文章。
## 功能
- 主题管理:创建、编辑、删除文章主题
- 素材收集:支持文本素材和图片素材
- Prompt编辑每个主题可自定义生成提示词
- 分类系统:多级分类,每个主题可归属多个分类
- 标签系统:灵活标签,每个主题支持多个标签,支持新建标签
- 素材收集支持文本素材和图片素材含Ctrl+V粘贴截图
- Prompt编辑每个主题可自定义生成提示词支持历史记录
- 大模型生成:调用 LLM 根据素材自动生成文章
- 文章管理:查看、编辑、删除生成的文章
- 文章管理:查看、编辑、删除、复制、下载生成的文章
## 技术栈
- 后端Python 3 + Flask + SQLite
- 前端HTML/CSS/JS原生
- 前端HTML/CSS/JSBootstrap 5 暗色主题
- LLM兼容 OpenAI API 格式的大模型接口
## 快速开始
@@ -24,7 +26,7 @@ pip install flask requests
# 配置环境变量
export LLM_URL="https://your-llm-api/v1/chat/completions"
export LLM_API_KEY="your-api-key"
export LLM_API_KEY="***"
export LLM_MODEL="qwen3.6-plus"
# 启动服务
@@ -35,7 +37,7 @@ python app.py
## 配置
通过环境变量配置 LLM 接口:
通过环境变量或页面配置 LLM 接口:
| 环境变量 | 说明 | 默认值 |
|---------|------|--------|
@@ -43,21 +45,49 @@ python app.py
| LLM_API_KEY | API 密钥 | - |
| LLM_MODEL | 模型名称 | qwen3.6-plus |
## 数据结构
- **topics** - 文章主题
- **categories** - 分类(支持多对多关联)
- **tags** - 标签(支持多对多关联,自动清理孤立标签)
- **topic_categories** - 主题-分类关联表
- **topic_tags** - 主题-标签关联表
- **materials** - 素材(文本/图片)
- **articles** - 生成的文章
- **llm_config** - LLM接口配置
- **prompt_history** - Prompt历史记录
## 项目结构
```
article-writer/
├── app.py # 主应用Flask后端
├── templates/
│ ├── index.html # 首页(主题列表)
│ └── topic.html # 主题详情页
│ ├── index.html # 首页(主题列表 + 分类/标签筛选
│ └── topic.html # 主题详情页(素材 + 文章生成 + 分类标签编辑)
├── static/
│ ├── css/
│ ├── js/
│ └── uploads/ # 图片上传目录
├── .env.example # 环境变量示例
└── .gitignore
```
## API
### 分类
- `GET /api/categories` - 分类列表(含主题计数)
- `POST /api/categories` - 创建分类
- `PUT /api/categories/<id>` - 更新分类
- `DELETE /api/categories/<id>` - 删除分类
### 标签
- `GET /api/tags` - 标签列表(含主题计数)
- `POST /api/tags` - 创建标签
- `DELETE /api/tags/<id>` - 删除标签
### 主题
- `POST /api/topics` - 创建主题(支持 category_ids, tag_ids, new_tags
- `PUT /api/topics/<id>` - 更新主题(支持更新分类和标签关联)
## License
MIT

218
app.py
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""
文章编写系统 - Article Writer System
功能主题管理、素材收集、Prompt编辑、大模型生成文章
功能主题管理、素材收集、Prompt编辑、大模型生成文章、分类与标签
"""
import os
@@ -82,6 +82,31 @@ def init_db():
created_at TEXT DEFAULT (datetime('now','localtime')),
FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS categories (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
sort_order INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS tags (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
created_at TEXT DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS topic_categories (
topic_id TEXT NOT NULL,
category_id TEXT NOT NULL,
PRIMARY KEY (topic_id, category_id),
FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE CASCADE,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS topic_tags (
topic_id TEXT NOT NULL,
tag_id TEXT NOT NULL,
PRIMARY KEY (topic_id, tag_id),
FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
);
''')
# 初始化默认配置
conn.execute('INSERT OR IGNORE INTO llm_config (id, url, api_key, model) VALUES (1, ?, ?, ?)',
@@ -104,6 +129,22 @@ def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def _topic_with_tags(conn, topic_row):
"""给 topic row 附上分类和标签信息"""
t = dict(topic_row)
cats = conn.execute(
'SELECT c.* FROM categories c JOIN topic_categories tc ON c.id=tc.category_id WHERE tc.topic_id=? ORDER BY c.sort_order',
(t['id'],)
).fetchall()
t['categories'] = [dict(c) for c in cats]
tags = conn.execute(
'SELECT tg.* FROM tags tg JOIN topic_tags tt ON tg.id=tt.tag_id WHERE tt.topic_id=? ORDER BY tg.name',
(t['id'],)
).fetchall()
t['tags'] = [dict(tg) for tg in tags]
return t
# ==================== 页面路由 ====================
@app.route('/')
@@ -113,8 +154,14 @@ def index():
'SELECT t.*, (SELECT COUNT(*) FROM materials WHERE topic_id=t.id) as mat_count '
'FROM topics t ORDER BY updated_at DESC'
).fetchall()
categories = conn.execute('SELECT * FROM categories ORDER BY sort_order, name').fetchall()
tags = conn.execute('SELECT * FROM tags ORDER BY name').fetchall()
# 附上分类和标签
topic_list = []
for t in topics:
topic_list.append(_topic_with_tags(conn, t))
conn.close()
return render_template('index.html', topics=topics)
return render_template('index.html', topics=topic_list, categories=categories, tags=tags)
@app.route('/topic/<topic_id>')
@@ -124,6 +171,7 @@ def topic_detail(topic_id):
if not topic:
conn.close()
return redirect(url_for('index'))
topic = _topic_with_tags(conn, topic)
materials = conn.execute(
'SELECT * FROM materials WHERE topic_id=? ORDER BY sort_order, created_at',
(topic_id,)
@@ -132,8 +180,11 @@ def topic_detail(topic_id):
'SELECT * FROM articles WHERE topic_id=? ORDER BY created_at DESC',
(topic_id,)
).fetchall()
categories = conn.execute('SELECT * FROM categories ORDER BY sort_order, name').fetchall()
tags = conn.execute('SELECT * FROM tags ORDER BY name').fetchall()
conn.close()
return render_template('topic.html', topic=topic, materials=materials, articles=articles)
return render_template('topic.html', topic=topic, materials=materials, articles=articles,
categories=categories, tags=tags)
# ==================== 主题API ====================
@@ -151,10 +202,29 @@ def create_topic():
'INSERT INTO topics (id, name, description, prompt, created_at, updated_at) VALUES (?,?,?,?,?,?)',
(tid, name, data.get('description', ''), data.get('prompt', ''), now, now)
)
# 关联分类
for cat_id in data.get('category_ids', []):
conn.execute('INSERT OR IGNORE INTO topic_categories (topic_id, category_id) VALUES (?,?)', (tid, cat_id))
# 关联标签如果传了已有tag id
for tag_id in data.get('tag_ids', []):
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (tid, tag_id))
# 处理新标签(按名称创建)
for tag_name in data.get('new_tags', []):
tag_name = tag_name.strip()
if not tag_name:
continue
existing = conn.execute('SELECT id FROM tags WHERE name=?', (tag_name,)).fetchone()
if existing:
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (tid, existing['id']))
else:
tag_id = str(uuid.uuid4())[:8]
conn.execute('INSERT INTO tags (id, name, created_at) VALUES (?,?,?)', (tag_id, tag_name, now))
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (tid, tag_id))
conn.commit()
topic = conn.execute('SELECT * FROM topics WHERE id=?', (tid,)).fetchone()
result = _topic_with_tags(conn, topic)
conn.close()
return jsonify(dict(topic))
return jsonify(result)
@app.route('/api/topics/<topic_id>', methods=['PUT'])
@@ -174,9 +244,37 @@ def update_topic(topic_id):
values.append(topic_id)
conn.execute(f'UPDATE topics SET {",".join(fields)} WHERE id=?', values)
conn.commit()
# 更新分类关联
if 'category_ids' in data:
conn.execute('DELETE FROM topic_categories WHERE topic_id=?', (topic_id,))
for cat_id in data['category_ids']:
conn.execute('INSERT OR IGNORE INTO topic_categories (topic_id, category_id) VALUES (?,?)', (topic_id, cat_id))
# 更新标签关联
if 'tag_ids' in data or 'new_tags' in data:
conn.execute('DELETE FROM topic_tags WHERE topic_id=?', (topic_id,))
for tag_id in data.get('tag_ids', []):
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (topic_id, tag_id))
for tag_name in data.get('new_tags', []):
tag_name = tag_name.strip()
if not tag_name:
continue
existing = conn.execute('SELECT id FROM tags WHERE name=?', (tag_name,)).fetchone()
if existing:
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (topic_id, existing['id']))
else:
tag_id = str(uuid.uuid4())[:8]
conn.execute('INSERT INTO tags (id, name, created_at) VALUES (?,?,?)', (tag_id, tag_name, now))
conn.execute('INSERT OR IGNORE INTO topic_tags (topic_id, tag_id) VALUES (?,?)', (topic_id, tag_id))
# 清理无引用的孤立标签
conn.execute('DELETE FROM tags WHERE id NOT IN (SELECT tag_id FROM topic_tags)')
conn.commit()
topic = conn.execute('SELECT * FROM topics WHERE id=?', (topic_id,)).fetchone()
result = _topic_with_tags(conn, topic)
conn.close()
return jsonify(dict(topic))
return jsonify(result)
@app.route('/api/topics/<topic_id>', methods=['DELETE'])
@@ -190,6 +288,112 @@ def delete_topic(topic_id):
if os.path.exists(fp):
os.remove(fp)
conn.execute('DELETE FROM topics WHERE id=?', (topic_id,))
# 清理孤立标签
conn.execute('DELETE FROM tags WHERE id NOT IN (SELECT tag_id FROM topic_tags)')
conn.commit()
conn.close()
return jsonify({'ok': True})
# ==================== 分类API ====================
@app.route('/api/categories', methods=['GET'])
def list_categories():
conn = get_db()
rows = conn.execute(
'SELECT c.*, (SELECT COUNT(*) FROM topic_categories WHERE category_id=c.id) as topic_count '
'FROM categories c ORDER BY c.sort_order, c.name'
).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route('/api/categories', methods=['POST'])
def create_category():
data = request.get_json(force=True)
name = data.get('name', '').strip()
if not name:
return jsonify({'error': '分类名不能为空'}), 400
conn = get_db()
existing = conn.execute('SELECT * FROM categories WHERE name=?', (name,)).fetchone()
if existing:
conn.close()
return jsonify({'error': '分类已存在'}), 400
cid = str(uuid.uuid4())[:8]
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn.execute('INSERT INTO categories (id, name, sort_order, created_at) VALUES (?,?,?,?)',
(cid, name, data.get('sort_order', 0), now))
conn.commit()
cat = conn.execute('SELECT * FROM categories WHERE id=?', (cid,)).fetchone()
conn.close()
return jsonify(dict(cat))
@app.route('/api/categories/<category_id>', methods=['PUT'])
def update_category(category_id):
data = request.get_json(force=True)
conn = get_db()
fields = []
values = []
for key in ['name', 'sort_order']:
if key in data:
fields.append(f'{key}=?')
values.append(data[key])
if fields:
values.append(category_id)
conn.execute(f'UPDATE categories SET {",".join(fields)} WHERE id=?', values)
conn.commit()
cat = conn.execute('SELECT * FROM categories WHERE id=?', (category_id,)).fetchone()
conn.close()
return jsonify(dict(cat)) if cat else jsonify({'error': '未找到'}), 404
@app.route('/api/categories/<category_id>', methods=['DELETE'])
def delete_category(category_id):
conn = get_db()
conn.execute('DELETE FROM categories WHERE id=?', (category_id,))
conn.commit()
conn.close()
return jsonify({'ok': True})
# ==================== 标签API ====================
@app.route('/api/tags', methods=['GET'])
def list_tags():
conn = get_db()
rows = conn.execute(
'SELECT tg.*, (SELECT COUNT(*) FROM topic_tags WHERE tag_id=tg.id) as topic_count '
'FROM tags tg ORDER BY tg.name'
).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route('/api/tags', methods=['POST'])
def create_tag():
data = request.get_json(force=True)
name = data.get('name', '').strip()
if not name:
return jsonify({'error': '标签名不能为空'}), 400
conn = get_db()
existing = conn.execute('SELECT * FROM tags WHERE name=?', (name,)).fetchone()
if existing:
conn.close()
return jsonify(dict(existing)) # 已存在直接返回
tid = str(uuid.uuid4())[:8]
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn.execute('INSERT INTO tags (id, name, created_at) VALUES (?,?,?)', (tid, name, now))
conn.commit()
tag = conn.execute('SELECT * FROM tags WHERE id=?', (tid,)).fetchone()
conn.close()
return jsonify(dict(tag))
@app.route('/api/tags/<tag_id>', methods=['DELETE'])
def delete_tag(tag_id):
conn = get_db()
conn.execute('DELETE FROM tags WHERE id=?', (tag_id,))
conn.commit()
conn.close()
return jsonify({'ok': True})
@@ -304,8 +508,8 @@ def update_llm_config():
conn.execute('''
INSERT INTO llm_config (id, url, api_key, model, updated_at) VALUES (1, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET url=?, api_key=?, model=?, updated_at=?
''', (1, url, api_key, model, now, url, api_key, model, now))
ON CONFLICT(id) DO UPDATE SET url=excluded.url, api_key=excluded.api_key, model=excluded.model, updated_at=excluded.updated_at
''', (url, api_key, model, now))
conn.commit()
conn.close()
return jsonify({'ok': True})

View File

@@ -7,7 +7,7 @@
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
<style>
:root { --bg-dark: #0d1117; --bg-card: #161b22; --bg-hover: #1c2333; --border: #30363d; --text: #c9d1d9; --text-muted: #9eaab8; --accent: #58a6ff; --accent-hover: #79c0ff; --danger: #f85149; --success: #3fb950; }
:root { --bg-dark: #0d1117; --bg-card: #161b22; --bg-hover: #1c2333; --border: #30363d; --text: #c9d1d9; --text-muted: #9eaab8; --accent: #58a6ff; --accent-hover: #79c0ff; --danger: #f85149; --success: #3fb950; --warning: #d29922; }
* { box-sizing: border-box; }
body { background: var(--bg-dark); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; min-height: 100vh; }
.text-muted { color: var(--text-muted) !important; }
@@ -36,8 +36,33 @@
.empty-state { text-align: center; padding: 80px 20px; color: var(--text-muted); }
.empty-state i { font-size: 4rem; margin-bottom: 16px; display: block; }
.badge-mat { background: rgba(88,166,255,0.15); color: var(--accent); }
.badge-cat { background: rgba(210,153,34,0.15); color: var(--warning); font-size: 0.75rem; }
.badge-tag { background: rgba(63,185,80,0.15); color: var(--success); font-size: 0.75rem; cursor: pointer; }
.badge-tag:hover { background: rgba(63,185,80,0.3); }
.config-indicator { font-size: 0.8rem; }
.alert-info { background: rgba(88,166,255,0.12); border-color: rgba(88,166,255,0.25); color: var(--text); }
/* 分类筛选侧栏 */
.filter-sidebar { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
.filter-sidebar h6 { color: var(--accent); font-size: 0.9rem; margin-bottom: 10px; }
.filter-item { display: flex; align-items: center; gap: 6px; padding: 5px 8px; border-radius: 6px; cursor: pointer; transition: all 0.15s; font-size: 0.88rem; color: var(--text-muted); }
.filter-item:hover { background: var(--bg-hover); color: var(--text); }
.filter-item.active { background: rgba(88,166,255,0.12); color: var(--accent); }
.filter-item .count { margin-left: auto; font-size: 0.75rem; opacity: 0.6; }
.tag-cloud { display: flex; flex-wrap: wrap; gap: 6px; }
.tag-cloud .badge-tag { font-size: 0.78rem; padding: 3px 8px; }
.tag-cloud .badge-tag.active { background: rgba(63,185,80,0.35); border: 1px solid var(--success); }
.clear-filter { font-size: 0.78rem; color: var(--danger); cursor: pointer; opacity: 0.7; }
.clear-filter:hover { opacity: 1; }
/* 新建主题弹窗中的分类/标签选择 */
.select-pills { display: flex; flex-wrap: wrap; gap: 6px; }
.pill-option { padding: 4px 12px; border-radius: 16px; border: 1px solid var(--border); cursor: pointer; font-size: 0.85rem; transition: all 0.15s; color: var(--text-muted); }
.pill-option:hover { border-color: var(--accent); color: var(--accent); }
.pill-option.selected { background: rgba(88,166,255,0.15); border-color: var(--accent); color: var(--accent); }
.pill-option.selected-tag { background: rgba(63,185,80,0.15); border-color: var(--success); color: var(--success); }
.tag-input-group { display: flex; gap: 6px; }
.tag-input-group input { flex: 1; }
</style>
</head>
<body>
@@ -51,6 +76,9 @@
<button class="btn btn-outline-accent btn-sm" onclick="showConfigModal()">
<i class="bi bi-gear me-1"></i>模型配置
</button>
<button class="btn btn-outline-accent btn-sm" onclick="showCategoryModal()">
<i class="bi bi-folder me-1"></i>分类管理
</button>
<button class="btn btn-accent" onclick="showCreateModal()">
<i class="bi bi-plus-lg me-1"></i>新建主题
</button>
@@ -59,33 +87,90 @@
</nav>
<div class="container py-4">
{% if topics %}
<div class="row g-3">
{% for t in topics %}
<div class="col-md-6 col-lg-4">
<div class="topic-card" onclick="location.href='/topic/{{t.id}}'">
<div class="d-flex justify-content-between align-items-start">
<h5 class="mb-0"><i class="bi bi-folder2-open me-2 text-warning"></i>{{t.name}}</h5>
<button class="btn btn-sm btn-link text-danger p-0" onclick="event.stopPropagation();deleteTopic('{{t.id}}','{{t.name}}')" title="删除">
<i class="bi bi-trash3"></i>
</button>
<!-- 左侧:筛选栏 -->
<div class="col-md-3 col-lg-2">
<div class="filter-sidebar mb-3">
<div class="d-flex justify-content-between align-items-center mb-2">
<h6 class="mb-0"><i class="bi bi-folder2 me-1"></i>分类</h6>
<span class="clear-filter" id="clearCatFilter" style="display:none;" onclick="clearCategoryFilter()">清除</span>
</div>
{% if t.description %}<div class="desc">{{t.description}}</div>{% endif %}
<div class="meta mt-2">
<span class="badge badge-mat me-1"><i class="bi bi-file-earmark-text me-1"></i>{{t.mat_count}} 素材</span>
<span class="ms-2"><i class="bi bi-clock me-1"></i>{{t.updated_at}}</span>
<div class="filter-item {% if not request.args.get('cat') %}active{% endif %}" onclick="filterByCategory('')">
<i class="bi bi-grid"></i> 全部
</div>
{% for c in categories %}
<div class="filter-item" data-cat-id="{{c.id}}" onclick="filterByCategory('{{c.id}}')">
<i class="bi bi-folder2"></i> {{c.name}}
<span class="count" id="cat-count-{{c.id}}"></span>
</div>
{% endfor %}
</div>
<div class="filter-sidebar">
<div class="d-flex justify-content-between align-items-center mb-2">
<h6 class="mb-0"><i class="bi bi-tags me-1"></i>标签</h6>
<span class="clear-filter" id="clearTagFilter" style="display:none;" onclick="clearTagFilter()">清除</span>
</div>
<div class="tag-cloud">
{% for t in tags %}
<span class="badge-tag" data-tag-id="{{t.id}}" data-tag-name="{{t.name}}" onclick="filterByTag('{{t.id}}')">{{t.name}}</span>
{% endfor %}
{% if not tags %}
<span class="text-muted small">暂无标签</span>
{% endif %}
</div>
</div>
</div>
{% endfor %}
<!-- 右侧:主题卡片 -->
<div class="col-md-9 col-lg-10">
{% if topics %}
<div class="row g-3" id="topicGrid">
{% for t in topics %}
<div class="col-md-6 col-lg-4 topic-item"
data-categories="{{t.categories | map(attribute='id') | join(',')}}"
data-tags="{{t.tags | map(attribute='id') | join(',')}}">
<div class="topic-card" onclick="location.href='/topic/{{t.id}}'">
<div class="d-flex justify-content-between align-items-start">
<h5 class="mb-0"><i class="bi bi-folder2-open me-2 text-warning"></i>{{t.name}}</h5>
<button class="btn btn-sm btn-link text-danger p-0" onclick="event.stopPropagation();deleteTopic('{{t.id}}','{{t.name}}')" title="删除">
<i class="bi bi-trash3"></i>
</button>
</div>
{% if t.description %}<div class="desc">{{t.description}}</div>{% endif %}
<!-- 分类标签 -->
{% if t.categories %}
<div class="mt-2">
{% for c in t.categories %}
<span class="badge badge-cat me-1"><i class="bi bi-folder2 me-1"></i>{{c.name}}</span>
{% endfor %}
</div>
{% endif %}
<!-- 标签 -->
{% if t.tags %}
<div class="mt-1">
{% for tg in t.tags %}
<span class="badge badge-tag me-1"><i class="bi bi-tag me-1"></i>{{tg.name}}</span>
{% endfor %}
</div>
{% endif %}
<div class="meta mt-2">
<span class="badge badge-mat me-1"><i class="bi bi-file-earmark-text me-1"></i>{{t.mat_count}} 素材</span>
<span class="ms-2"><i class="bi bi-clock me-1"></i>{{t.updated_at}}</span>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="empty-state">
<i class="bi bi-journal-text"></i>
<h5>还没有主题</h5>
<p>点击右上角「新建主题」开始吧</p>
</div>
{% endif %}
</div>
</div>
{% else %}
<div class="empty-state">
<i class="bi bi-journal-text"></i>
<h5>还没有主题</h5>
<p>点击右上角「新建主题」开始吧</p>
</div>
{% endif %}
</div>
<!-- 新建主题模态框 -->
@@ -105,6 +190,26 @@
<label class="form-label">主题说明</label>
<textarea class="form-control" id="topicDesc" rows="2" placeholder="简要描述这个主题的方向"></textarea>
</div>
<div class="mb-3">
<label class="form-label">分类(可多选)</label>
<div class="select-pills" id="categoryPills">
<!-- 动态填充 -->
</div>
<div class="form-text">点击选择所属分类</div>
</div>
<div class="mb-3">
<label class="form-label">标签</label>
<div class="select-pills mb-2" id="tagPills">
<!-- 动态填充已有标签 -->
</div>
<div class="tag-input-group">
<input type="text" class="form-control form-control-sm" id="newTagInput" placeholder="输入新标签,回车添加">
<button class="btn btn-sm btn-outline-accent" onclick="addNewTagToForm()">添加</button>
</div>
<div class="select-pills mt-1" id="newTagPills">
<!-- 动态填充新标签 -->
</div>
</div>
<div class="mb-3">
<label class="form-label">默认Prompt</label>
<textarea class="form-control" id="topicPrompt" rows="4" placeholder="请根据以下素材撰写一篇结构清晰、内容丰富的文章:"></textarea>
@@ -118,6 +223,27 @@
</div>
</div>
<!-- 分类管理模态框 -->
<div class="modal fade" id="categoryModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="bi bi-folder me-2"></i>分类管理</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="d-flex gap-2 mb-3">
<input type="text" class="form-control form-control-sm" id="newCatName" placeholder="新分类名称">
<button class="btn btn-sm btn-accent" onclick="createCategory()">添加</button>
</div>
<div id="categoryList">
<!-- 动态填充 -->
</div>
</div>
</div>
</div>
</div>
<!-- LLM配置模态框 -->
<div class="modal fade" id="configModal" tabindex="-1">
<div class="modal-dialog">
@@ -164,6 +290,11 @@
<script>
const createModalInstance = new bootstrap.Modal(document.getElementById('createModal'));
const configModalInstance = new bootstrap.Modal(document.getElementById('configModal'));
const categoryModalInstance = new bootstrap.Modal(document.getElementById('categoryModal'));
// 筛选状态
let activeCategoryId = '';
let activeTagId = '';
// 页面加载时获取配置状态
(async function() {
@@ -179,8 +310,207 @@
} catch(e) {}
})();
function showCreateModal() { createModalInstance.show(); }
// ===== 分类筛选 =====
function filterByCategory(catId) {
activeCategoryId = catId;
// 更新侧栏激活状态
document.querySelectorAll('.filter-sidebar .filter-item').forEach(el => {
el.classList.toggle('active', el.dataset.catId === catId || (!catId && !el.dataset.catId));
});
document.getElementById('clearCatFilter').style.display = catId ? 'inline' : 'none';
applyFilters();
}
function clearCategoryFilter() { filterByCategory(''); }
function filterByTag(tagId) {
if (activeTagId === tagId) {
activeTagId = ''; // 再次点击取消
} else {
activeTagId = tagId;
}
// 更新标签云激活状态
document.querySelectorAll('.tag-cloud .badge-tag').forEach(el => {
el.classList.toggle('active', el.dataset.tagId === activeTagId);
});
document.getElementById('clearTagFilter').style.display = activeTagId ? 'inline' : 'none';
applyFilters();
}
function clearTagFilter() { activeTagId = ''; document.querySelectorAll('.tag-cloud .badge-tag').forEach(el => el.classList.remove('active')); document.getElementById('clearTagFilter').style.display = 'none'; applyFilters(); }
function applyFilters() {
const items = document.querySelectorAll('.topic-item');
items.forEach(el => {
const cats = el.dataset.categories ? el.dataset.categories.split(',') : [];
const tags = el.dataset.tags ? el.dataset.tags.split(',') : [];
let show = true;
if (activeCategoryId && !cats.includes(activeCategoryId)) show = false;
if (activeTagId && !tags.includes(activeTagId)) show = false;
el.style.display = show ? '' : 'none';
});
}
// ===== 新建主题 =====
let selectedCategoryIds = [];
let selectedTagIds = [];
let newTagNames = [];
function showCreateModal() {
selectedCategoryIds = [];
selectedTagIds = [];
newTagNames = [];
document.getElementById('topicName').value = '';
document.getElementById('topicDesc').value = '';
document.getElementById('topicPrompt').value = '';
document.getElementById('newTagInput').value = '';
document.getElementById('newTagPills').innerHTML = '';
loadCategoryPills();
loadTagPills();
createModalInstance.show();
}
async function loadCategoryPills() {
try {
const res = await fetch('/api/categories');
const cats = await res.json();
const container = document.getElementById('categoryPills');
container.innerHTML = cats.map(c =>
`<span class="pill-option" data-id="${c.id}" onclick="toggleCategoryPill(this,'${c.id}')">${c.name}</span>`
).join('');
} catch(e) {}
}
async function loadTagPills() {
try {
const res = await fetch('/api/tags');
const tags = await res.json();
const container = document.getElementById('tagPills');
container.innerHTML = tags.map(t =>
`<span class="pill-option" data-id="${t.id}" onclick="toggleTagPill(this,'${t.id}')">${t.name}</span>`
).join('');
} catch(e) {}
}
function toggleCategoryPill(el, id) {
const idx = selectedCategoryIds.indexOf(id);
if (idx >= 0) {
selectedCategoryIds.splice(idx, 1);
el.classList.remove('selected');
} else {
selectedCategoryIds.push(id);
el.classList.add('selected');
}
}
function toggleTagPill(el, id) {
const idx = selectedTagIds.indexOf(id);
if (idx >= 0) {
selectedTagIds.splice(idx, 1);
el.classList.remove('selected-tag');
} else {
selectedTagIds.push(id);
el.classList.add('selected-tag');
}
}
function addNewTagToForm() {
const input = document.getElementById('newTagInput');
const name = input.value.trim();
if (!name || newTagNames.includes(name)) return;
newTagNames.push(name);
input.value = '';
renderNewTagPills();
}
document.getElementById('newTagInput').addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); addNewTagToForm(); }
});
function renderNewTagPills() {
const container = document.getElementById('newTagPills');
container.innerHTML = newTagNames.map((n, i) =>
`<span class="pill-option selected-tag" onclick="removeNewTag(${i})">${n} <i class="bi bi-x"></i></span>`
).join('');
}
function removeNewTag(idx) {
newTagNames.splice(idx, 1);
renderNewTagPills();
}
async function createTopic() {
const name = document.getElementById('topicName').value.trim();
if (!name) return alert('请输入主题名称');
const res = await fetch('/api/topics', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name,
description: document.getElementById('topicDesc').value,
prompt: document.getElementById('topicPrompt').value,
category_ids: selectedCategoryIds,
tag_ids: selectedTagIds,
new_tags: newTagNames
})
});
if (res.ok) location.reload();
else { const d = await res.json(); alert(d.error || '创建失败'); }
}
async function deleteTopic(id, name) {
if (!confirm(`确定删除主题「${name}」?所有素材和文章将被清除!`)) return;
const res = await fetch(`/api/topics/${id}`, {method: 'DELETE'});
if (res.ok) location.reload();
}
// ===== 分类管理 =====
async function showCategoryModal() {
categoryModalInstance.show();
await loadCategoryList();
}
async function loadCategoryList() {
try {
const res = await fetch('/api/categories');
const cats = await res.json();
const container = document.getElementById('categoryList');
if (cats.length === 0) {
container.innerHTML = '<div class="text-muted small text-center py-2">暂无分类</div>';
return;
}
container.innerHTML = cats.map(c => `
<div class="d-flex justify-content-between align-items-center p-2 mb-1" style="background:var(--bg-dark);border-radius:6px;">
<span><i class="bi bi-folder2 text-warning me-2"></i>${c.name} <span class="text-muted small">(${c.topic_count || 0})</span></span>
<button class="btn btn-sm btn-link text-danger p-0" onclick="deleteCategory('${c.id}','${c.name}')"><i class="bi bi-trash3"></i></button>
</div>
`).join('');
} catch(e) {}
}
async function createCategory() {
const name = document.getElementById('newCatName').value.trim();
if (!name) return alert('请输入分类名称');
const res = await fetch('/api/categories', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name})
});
if (res.ok) {
document.getElementById('newCatName').value = '';
await loadCategoryList();
} else {
const d = await res.json(); alert(d.error || '创建失败');
}
}
async function deleteCategory(id, name) {
if (!confirm(`确定删除分类「${name}」?`)) return;
await fetch(`/api/categories/${id}`, {method: 'DELETE'});
await loadCategoryList();
}
// ===== LLM配置 =====
async function showConfigModal() {
try {
const res = await fetch('/api/llm-config');
@@ -211,7 +541,7 @@
model: document.getElementById('cfgModel').value.trim()
};
const key = document.getElementById('cfgKey').value.trim();
if (key) data.api_key = key; // 只在有新值时传递
if (key) data.api_key = key;
const res = await fetch('/api/llm-config', {
method: 'PUT',
@@ -219,7 +549,6 @@
body: JSON.stringify(data)
});
if (res.ok) {
// 更新指示器
const ind = document.getElementById('configIndicator');
ind.innerHTML = `<i class="bi bi-circle-fill text-success"></i> ${data.model}`;
configModalInstance.hide();
@@ -228,28 +557,6 @@
alert(d.error || '保存失败');
}
}
async function createTopic() {
const name = document.getElementById('topicName').value.trim();
if (!name) return alert('请输入主题名称');
const res = await fetch('/api/topics', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name,
description: document.getElementById('topicDesc').value,
prompt: document.getElementById('topicPrompt').value
})
});
if (res.ok) location.reload();
else { const d = await res.json(); alert(d.error || '创建失败'); }
}
async function deleteTopic(id, name) {
if (!confirm(`确定删除主题「${name}」?所有素材和文章将被清除!`)) return;
const res = await fetch(`/api/topics/${id}`, {method: 'DELETE'});
if (res.ok) location.reload();
}
</script>
</body>
</html>

View File

@@ -60,6 +60,20 @@
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg-dark); }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
/* 分类和标签样式 */
.badge-cat { background: rgba(210,153,34,0.15); color: var(--warning); font-size: 0.78rem; }
.badge-tag { background: rgba(63,185,80,0.15); color: var(--success); font-size: 0.78rem; }
.info-bar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 8px 16px; background: var(--bg-card); border-bottom: 1px solid var(--border); }
.info-bar .edit-btn { cursor: pointer; color: var(--text-muted); font-size: 0.8rem; }
.info-bar .edit-btn:hover { color: var(--accent); }
.select-pills { display: flex; flex-wrap: wrap; gap: 6px; }
.pill-option { padding: 4px 12px; border-radius: 16px; border: 1px solid var(--border); cursor: pointer; font-size: 0.85rem; transition: all 0.15s; color: var(--text-muted); }
.pill-option:hover { border-color: var(--accent); color: var(--accent); }
.pill-option.selected { background: rgba(88,166,255,0.15); border-color: var(--accent); color: var(--accent); }
.pill-option.selected-tag { background: rgba(63,185,80,0.15); border-color: var(--success); color: var(--success); }
.tag-input-group { display: flex; gap: 6px; }
.tag-input-group input { flex: 1; }
</style>
</head>
<body>
@@ -70,6 +84,27 @@
</div>
</nav>
<!-- 分类/标签信息条 -->
<div class="info-bar">
<span class="text-muted small"><i class="bi bi-folder2 me-1"></i>分类:</span>
{% if topic.categories %}
{% for c in topic.categories %}
<span class="badge badge-cat">{{c.name}}</span>
{% endfor %}
{% else %}
<span class="text-muted small">未分类</span>
{% endif %}
<span class="text-muted small ms-2"><i class="bi bi-tags me-1"></i>标签:</span>
{% if topic.tags %}
{% for tg in topic.tags %}
<span class="badge badge-tag">{{tg.name}}</span>
{% endfor %}
{% else %}
<span class="text-muted small">无标签</span>
{% endif %}
<span class="edit-btn ms-2" onclick="showEditCatTagModal()"><i class="bi bi-pencil"></i> 编辑</span>
</div>
<div class="container-fluid px-4 py-3">
<div class="row g-3">
<!-- 左栏:素材 + Prompt -->
@@ -180,6 +215,38 @@
</div>
</div>
<!-- 编辑分类/标签模态框 -->
<div class="modal fade" id="catTagModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="bi bi-tags me-2"></i>编辑分类与标签</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">分类(可多选)</label>
<div class="select-pills" id="editCategoryPills"></div>
<div class="form-text">点击选择所属分类</div>
</div>
<div class="mb-3">
<label class="form-label">标签</label>
<div class="select-pills mb-2" id="editTagPills"></div>
<div class="tag-input-group">
<input type="text" class="form-control form-control-sm" id="editNewTagInput" placeholder="输入新标签,回车添加">
<button class="btn btn-sm btn-outline-accent" onclick="addEditNewTag()">添加</button>
</div>
<div class="select-pills mt-1" id="editNewTagPills"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-accent" onclick="saveCatTag()">保存</button>
</div>
</div>
</div>
</div>
<!-- 添加文本模态框 -->
<div class="modal fade" id="textModal" tabindex="-1">
<div class="modal-dialog">
@@ -255,7 +322,99 @@
const textModal = new bootstrap.Modal(document.getElementById('textModal'));
const imageModal = new bootstrap.Modal(document.getElementById('imageModal'));
const pasteModal = new bootstrap.Modal(document.getElementById('pasteModal'));
let pastedBlob = null; // 暂存粘贴的图片
const catTagModal = new bootstrap.Modal(document.getElementById('catTagModal'));
let pastedBlob = null;
// 当前主题的分类和标签
const currentCategoryIds = [{% for c in topic.categories %}'{{c.id}}',{% endfor %}];
const currentTagIds = [{% for tg in topic.tags %}'{{tg.id}}',{% endfor %}];
// ===== 分类/标签编辑 =====
let editCategoryIds = [...currentCategoryIds];
let editTagIds = [...currentTagIds];
let editNewTagNames = [];
async function showEditCatTagModal() {
editCategoryIds = [...currentCategoryIds];
editTagIds = [...currentTagIds];
editNewTagNames = [];
document.getElementById('editNewTagInput').value = '';
document.getElementById('editNewTagPills').innerHTML = '';
// 加载分类选项
try {
const res = await fetch('/api/categories');
const cats = await res.json();
document.getElementById('editCategoryPills').innerHTML = cats.map(c =>
`<span class="pill-option ${editCategoryIds.includes(c.id) ? 'selected' : ''}" data-id="${c.id}" onclick="toggleEditCategory(this,'${c.id}')">${c.name}</span>`
).join('');
} catch(e) {}
// 加载标签选项
try {
const res = await fetch('/api/tags');
const tags = await res.json();
document.getElementById('editTagPills').innerHTML = tags.map(t =>
`<span class="pill-option ${editTagIds.includes(t.id) ? 'selected-tag' : ''}" data-id="${t.id}" onclick="toggleEditTag(this,'${t.id}')">${t.name}</span>`
).join('');
} catch(e) {}
catTagModal.show();
}
function toggleEditCategory(el, id) {
const idx = editCategoryIds.indexOf(id);
if (idx >= 0) { editCategoryIds.splice(idx, 1); el.classList.remove('selected'); }
else { editCategoryIds.push(id); el.classList.add('selected'); }
}
function toggleEditTag(el, id) {
const idx = editTagIds.indexOf(id);
if (idx >= 0) { editTagIds.splice(idx, 1); el.classList.remove('selected-tag'); }
else { editTagIds.push(id); el.classList.add('selected-tag'); }
}
function addEditNewTag() {
const input = document.getElementById('editNewTagInput');
const name = input.value.trim();
if (!name || editNewTagNames.includes(name)) return;
editNewTagNames.push(name);
input.value = '';
renderEditNewTagPills();
}
document.getElementById('editNewTagInput').addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); addEditNewTag(); }
});
function renderEditNewTagPills() {
document.getElementById('editNewTagPills').innerHTML = editNewTagNames.map((n, i) =>
`<span class="pill-option selected-tag" onclick="removeEditNewTag(${i})">${n} <i class="bi bi-x"></i></span>`
).join('');
}
function removeEditNewTag(idx) {
editNewTagNames.splice(idx, 1);
renderEditNewTagPills();
}
async function saveCatTag() {
const res = await fetch(`/api/topics/${topicId}`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
category_ids: editCategoryIds,
tag_ids: editTagIds,
new_tags: editNewTagNames
})
});
if (res.ok) {
catTagModal.hide();
location.reload();
} else {
const d = await res.json(); alert(d.error || '保存失败');
}
}
// ===== 粘贴截图上传 =====
document.addEventListener('paste', function(e) {
@@ -266,7 +425,6 @@
e.preventDefault();
const blob = items[i].getAsFile();
pastedBlob = blob;
// 预览
const reader = new FileReader();
reader.onload = (ev) => {
document.getElementById('pastePreview').innerHTML = `<img src="${ev.target.result}" style="max-width:100%;max-height:200px;border-radius:6px;">`;
@@ -279,7 +437,6 @@
}
});
// 粘贴区拖拽高亮
const pasteZone = document.getElementById('pasteZone');
document.addEventListener('paste', () => { pasteZone.classList.add('active'); setTimeout(() => pasteZone.classList.remove('active'), 1000); });
@@ -290,16 +447,10 @@
fd.append('file', pastedBlob, `paste_${Date.now()}.png`);
fd.append('content', document.getElementById('pasteDesc').value);
const res = await fetch(`/api/topics/${topicId}/materials`, {method: 'POST', body: fd});
if (res.ok) {
pastedBlob = null;
pasteModal.hide();
location.reload();
} else {
const d = await res.json(); alert(d.error);
}
if (res.ok) { pastedBlob = null; pasteModal.hide(); location.reload(); }
else { const d = await res.json(); alert(d.error); }
}
// 图片预览(选择文件)
document.getElementById('imageFile').addEventListener('change', function(e) {
const preview = document.getElementById('imagePreview');
if (e.target.files[0]) {
@@ -361,10 +512,7 @@
async function togglePromptHistory() {
const area = document.getElementById('promptHistoryArea');
if (area.classList.contains('show')) {
area.classList.remove('show');
return;
}
if (area.classList.contains('show')) { area.classList.remove('show'); return; }
if (!promptHistoryLoaded) {
const res = await fetch(`/api/topics/${topicId}/prompt-history`);
const history = await res.json();
@@ -384,9 +532,7 @@
area.classList.add('show');
}
function restorePrompt(text) {
document.getElementById('promptText').value = text;
}
function restorePrompt(text) { document.getElementById('promptText').value = text; }
// ===== 文章生成 =====
async function generateArticle() {
@@ -400,12 +546,10 @@
if (!res.ok) { const d = await res.json(); throw new Error(d.error || '生成失败'); }
const article = await res.json();
// 清除空状态提示
const area = document.getElementById('articlesArea');
const empty = area.querySelector('.text-center');
if (empty) empty.remove();
// 插入新文章
const html = `<div class="article-card" id="article-${article.id}">
<div class="article-header">
<span class="small text-muted">