Trae Assistant commited on
Commit
c2b307b
·
0 Parent(s):

Initial commit: Synapse Flow Agent

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. .gitignore +4 -0
  3. Dockerfile +18 -0
  4. README.md +79 -0
  5. app.py +164 -0
  6. requirements.txt +4 -0
  7. templates/index.html +500 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.db filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ instance/
2
+ __pycache__/
3
+ *.pyc
4
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ RUN mkdir -p instance && chmod 777 instance
11
+
12
+ RUN useradd -m -u 1000 user
13
+ USER user
14
+
15
+ ENV HOME=/home/user \
16
+ PATH=/home/user/.local/bin:$PATH
17
+
18
+ CMD ["gunicorn", "-b", "0.0.0.0:7860", "app:app"]
README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: 突触流 - Synapse Flow Agent
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ short_description: 智能脑机接口与神经数据分析平台 (BCI SaaS)
9
+ ---
10
+
11
+ # 突触流 - Synapse Flow Agent
12
+
13
+ **智能脑机接口与神经数据分析平台 (Intelligent BCI & Neuroscience Data Analytics Platform)**
14
+
15
+ Synapse Flow Agent 是一个面向未来的神经科技 SaaS 平台,旨在为脑机接口(BCI)研究、神经反馈训练和认知状态监测提供一站式解决方案。项目结合了实时信号可视化、AI 数据分析和数字化档案管理,适用于医疗科技、科研实验室及个人健康监测领域。
16
+
17
+ ## 核心功能 (Key Features)
18
+
19
+ 1. **实时信号监控 (Signal Scope)**
20
+ - 可视化 EEG(脑电图)波形,支持 Alpha, Beta, Theta, Delta 频带展示。
21
+ - 实时频谱分析,动态展示大脑活跃区域。
22
+ - 模拟数据生成器 (Mock Mode),无需硬件即可演示。
23
+
24
+ 2. **AI 认知评估 (Mind State Radar)**
25
+ - 集成 **SiliconFlow (硅基流)** 大模型 API,对会话数据进行深度解读。
26
+ - 自动生成认知状态报告(专注、放松、疲劳、压力)。
27
+ - 提供多维度雷达图评分及个性化改进建议。
28
+
29
+ 3. **数字化档案 (Subject Vault)**
30
+ - 完整的受试者/用户数据管理系统。
31
+ - 历史会话记录回放与对比分析。
32
+ - 数据持久化存储 (SQLite)。
33
+
34
+ 4. **现代化交互体验**
35
+ - **移动端优先**: 适配手机与平板的响应式设计。
36
+ - **极简 UI**: 清爽的浅色主题,专注于数据可读性。
37
+ - **智能解析**: 内置 Markdown 解析器,美化 AI 输出报告。
38
+
39
+ ## 技术栈 (Tech Stack)
40
+
41
+ - **Backend**: Python 3.9, Flask, SQLite, Gunicorn
42
+ - **Frontend**: Vue.js 3, Tailwind CSS, ECharts, Marked.js
43
+ - **AI Integration**: SiliconFlow API (Qwen/Qwen2.5-7B-Instruct)
44
+ - **Deployment**: Docker, Hugging Face Spaces
45
+
46
+ ## 快速开始 (Quick Start)
47
+
48
+ ### 本地运行
49
+
50
+ 1. 克隆项目
51
+ ```bash
52
+ git clone <repository-url>
53
+ cd synapse-flow-agent
54
+ ```
55
+
56
+ 2. 安装依赖
57
+ ```bash
58
+ pip install -r requirements.txt
59
+ ```
60
+
61
+ 3. 运行应用
62
+ ```bash
63
+ python app.py
64
+ ```
65
+ 访问: `http://localhost:7860`
66
+
67
+ ### Docker 部署
68
+
69
+ ```bash
70
+ docker build -t synapse-flow .
71
+ docker run -p 7860:7860 synapse-flow
72
+ ```
73
+
74
+ ## 商业前景
75
+
76
+ 随着脑机接口技术的普及(如 Neuralink),个人神经数据分析将成为继基因检测后的下一个蓝海市场。Synapse Flow Agent 定位于 B2B 科研工具与 B2C 高端健康管理的交叉点,具有极高的资产沉淀价值和数据变现潜力。
77
+
78
+ ---
79
+ *Built by Trae AI Agent*
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import sqlite3
4
+ import requests
5
+ import random
6
+ import time
7
+ from flask import Flask, render_template, request, jsonify, g
8
+ from flask_cors import CORS
9
+
10
+ app = Flask(__name__)
11
+ CORS(app)
12
+
13
+ # Configuration
14
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB
15
+ app.config['DATABASE'] = os.path.join(app.instance_path, 'synapse.db')
16
+ SILICONFLOW_API_KEY = "sk-vimuseiptfbomzegyuvmebjzooncsqbyjtlddrfodzcdskgi"
17
+ SILICONFLOW_API_URL = "https://api.siliconflow.cn/v1/chat/completions"
18
+
19
+ # Ensure instance folder exists
20
+ try:
21
+ os.makedirs(app.instance_path)
22
+ except OSError:
23
+ pass
24
+
25
+ # Database Setup
26
+ def get_db():
27
+ db = getattr(g, '_database', None)
28
+ if db is None:
29
+ db = g._database = sqlite3.connect(app.config['DATABASE'])
30
+ db.row_factory = sqlite3.Row
31
+ return db
32
+
33
+ @app.teardown_appcontext
34
+ def close_connection(exception):
35
+ db = getattr(g, '_database', None)
36
+ if db is not None:
37
+ db.close()
38
+
39
+ def init_db():
40
+ with app.app_context():
41
+ db = get_db()
42
+ db.execute('''
43
+ CREATE TABLE IF NOT EXISTS history (
44
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
45
+ timestamp TEXT NOT NULL,
46
+ subject_id TEXT,
47
+ session_type TEXT,
48
+ analysis_result TEXT,
49
+ raw_metrics TEXT
50
+ )
51
+ ''')
52
+ db.commit()
53
+
54
+ init_db()
55
+
56
+ # --- Routes ---
57
+
58
+ @app.route('/')
59
+ def index():
60
+ return render_template('index.html')
61
+
62
+ @app.route('/api/mock/signal')
63
+ def mock_signal():
64
+ """Generate mock EEG signal data for visualization."""
65
+ # Generate 4 channels of data (Alpha, Beta, Theta, Delta)
66
+ timestamp = time.time()
67
+ data = []
68
+ for i in range(50): # 50 points
69
+ t = timestamp + i * 0.1
70
+ data.append({
71
+ 'time': i,
72
+ 'alpha': 10 + 5 * random.sin(t),
73
+ 'beta': 20 + 8 * random.cos(t * 2),
74
+ 'theta': 5 + 3 * random.sin(t * 0.5),
75
+ 'delta': 2 + 1 * random.cos(t * 0.2)
76
+ })
77
+ return jsonify({'status': 'success', 'data': data})
78
+
79
+ @app.route('/api/analyze', methods=['POST'])
80
+ def analyze_session():
81
+ data = request.json
82
+ subject_id = data.get('subject_id', 'Unknown')
83
+ session_type = data.get('session_type', 'Focus Training')
84
+
85
+ # Construct prompt for SiliconFlow
86
+ prompt = f"""
87
+ 作为神经科学专家,请分析以下脑机接口(BCI)会话数据并生成中文报告。
88
+ 受试者ID: {subject_id}
89
+ 会话类型: {session_type}
90
+
91
+ 模拟采集数据特征:
92
+ - Alpha波 (8-12Hz): 活跃度中等偏高 (放松状态)
93
+ - Beta波 (12-30Hz): 间歇性峰值 (集中注意力)
94
+ - Theta波 (4-8Hz): 低 (无困倦)
95
+ - 专注度指数: 75/100
96
+ - 疲劳度指数: 20/100
97
+
98
+ 请输出JSON格式,包含以下字段:
99
+ - summary: 会话总结 (Markdown格式)
100
+ - cognitive_state: 认知状态评估 (Focus, Relaxed, Stressed, Fatigued)
101
+ - recommendations: 3条改进建议 (数组)
102
+ - radar_chart: 雷达图数据 (5个维度: 专注, 放松, 反应速度, 记忆负荷, 情绪稳定性, 0-100分)
103
+ """
104
+
105
+ headers = {
106
+ "Authorization": f"Bearer {SILICONFLOW_API_KEY}",
107
+ "Content-Type": "application/json"
108
+ }
109
+ payload = {
110
+ "model": "Qwen/Qwen2.5-7B-Instruct",
111
+ "messages": [
112
+ {"role": "system", "content": "你是一个专业的神经科学和脑机接口数据分析师。请只输出JSON格式。"},
113
+ {"role": "user", "content": prompt}
114
+ ],
115
+ "response_format": {"type": "json_object"}
116
+ }
117
+
118
+ try:
119
+ response = requests.post(SILICONFLOW_API_URL, json=payload, headers=headers, timeout=10)
120
+ response.raise_for_status()
121
+ result_json = response.json()
122
+ content = result_json['choices'][0]['message']['content']
123
+ # Parse JSON from content
124
+ analysis = json.loads(content)
125
+ except Exception as e:
126
+ print(f"API Error: {e}")
127
+ # Mock Fallback
128
+ analysis = {
129
+ "summary": f"**模拟分析报告**: 由于API连接受限,这是基于本地规则生成的分析。\n\n受试者 **{subject_id}** 在 **{session_type}** 中表现出良好的认知稳定性。Alpha波活动表明处于放松警觉状态,适合进行高负荷任务前的调整。",
130
+ "cognitive_state": "Relaxed & Focused",
131
+ "recommendations": ["增加5分钟Theta波诱导训练", "保持当前呼吸节奏", "建议在下午时段进行下一次训练"],
132
+ "radar_chart": {"专注": 78, "放松": 85, "反应速度": 60, "记忆负荷": 45, "情绪稳定性": 90}
133
+ }
134
+
135
+ # Save to DB
136
+ try:
137
+ db = get_db()
138
+ db.execute(
139
+ 'INSERT INTO history (timestamp, subject_id, session_type, analysis_result, raw_metrics) VALUES (?, ?, ?, ?, ?)',
140
+ (time.strftime('%Y-%m-%d %H:%M:%S'), subject_id, session_type, json.dumps(analysis), "mock_raw_data")
141
+ )
142
+ db.commit()
143
+ except Exception as e:
144
+ print(f"DB Error: {e}")
145
+
146
+ return jsonify({'status': 'success', 'result': analysis})
147
+
148
+ @app.route('/api/history')
149
+ def get_history():
150
+ db = get_db()
151
+ rows = db.execute('SELECT * FROM history ORDER BY id DESC LIMIT 10').fetchall()
152
+ history = []
153
+ for row in rows:
154
+ history.append({
155
+ 'id': row['id'],
156
+ 'timestamp': row['timestamp'],
157
+ 'subject_id': row['subject_id'],
158
+ 'session_type': row['session_type'],
159
+ 'analysis': json.loads(row['analysis_result'])
160
+ })
161
+ return jsonify({'status': 'success', 'history': history})
162
+
163
+ if __name__ == '__main__':
164
+ app.run(host='0.0.0.0', port=7860, debug=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ flask
2
+ flask-cors
3
+ requests
4
+ gunicorn
templates/index.html ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>突触流 Synapse Flow | 智能BCI数据平台</title>
7
+ <!-- Vue 3 -->
8
+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
9
+ <!-- Tailwind CSS -->
10
+ <script src="https://cdn.tailwindcss.com"></script>
11
+ <!-- ECharts -->
12
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
13
+ <!-- Marked.js -->
14
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
15
+ <!-- Font Awesome -->
16
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
17
+
18
+ <style>
19
+ [v-cloak] { display: none; }
20
+ .chart-container { height: 300px; width: 100%; }
21
+ /* Custom Scrollbar */
22
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
23
+ ::-webkit-scrollbar-track { background: #f1f1f1; }
24
+ ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
25
+ ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
26
+ </style>
27
+ <script>
28
+ tailwind.config = {
29
+ theme: {
30
+ extend: {
31
+ colors: {
32
+ brand: {
33
+ 50: '#f0f9ff',
34
+ 100: '#e0f2fe',
35
+ 500: '#0ea5e9',
36
+ 600: '#0284c7',
37
+ 700: '#0369a1',
38
+ 900: '#0c4a6e',
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ </script>
45
+ </head>
46
+ <body class="bg-slate-50 text-slate-800 font-sans antialiased">
47
+ <div id="app" v-cloak class="flex h-screen overflow-hidden">
48
+
49
+ <!-- Mobile Sidebar Overlay -->
50
+ <div v-if="mobileMenuOpen" class="fixed inset-0 bg-black/50 z-40 md:hidden" @click="mobileMenuOpen = false"></div>
51
+
52
+ <!-- Sidebar -->
53
+ <aside :class="{'translate-x-0': mobileMenuOpen, '-translate-x-full': !mobileMenuOpen}" class="fixed md:static inset-y-0 left-0 z-50 w-64 bg-white border-r border-slate-200 transition-transform duration-300 md:translate-x-0 flex flex-col">
54
+ <div class="p-6 border-b border-slate-100 flex items-center gap-3">
55
+ <div class="w-10 h-10 rounded-xl bg-brand-600 flex items-center justify-center text-white text-xl shadow-lg shadow-brand-500/30">
56
+ <i class="fa-solid fa-brain"></i>
57
+ </div>
58
+ <div>
59
+ <h1 class="font-bold text-lg tracking-tight text-slate-900">突触流</h1>
60
+ <p class="text-xs text-slate-500 font-medium">Synapse Flow Agent</p>
61
+ </div>
62
+ </div>
63
+
64
+ <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
65
+ <a href="#" @click.prevent="currentView = 'dashboard'" :class="{'bg-brand-50 text-brand-700': currentView === 'dashboard', 'text-slate-600 hover:bg-slate-50': currentView !== 'dashboard'}" class="flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-colors">
66
+ <i class="fa-solid fa-chart-line w-5"></i> 实时监控
67
+ </a>
68
+ <a href="#" @click.prevent="currentView = 'analysis'" :class="{'bg-brand-50 text-brand-700': currentView === 'analysis', 'text-slate-600 hover:bg-slate-50': currentView !== 'analysis'}" class="flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-colors">
69
+ <i class="fa-solid fa-microchip w-5"></i> 智能分析
70
+ </a>
71
+ <a href="#" @click.prevent="currentView = 'history'" :class="{'bg-brand-50 text-brand-700': currentView === 'history', 'text-slate-600 hover:bg-slate-50': currentView !== 'history'}" class="flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-colors">
72
+ <i class="fa-solid fa-clock-rotate-left w-5"></i> 历史档案
73
+ </a>
74
+ </nav>
75
+
76
+ <div class="p-4 border-t border-slate-100">
77
+ <div class="bg-slate-900 rounded-xl p-4 text-white">
78
+ <div class="flex items-center justify-between mb-2">
79
+ <span class="text-xs font-semibold text-slate-300">设备状态</span>
80
+ <span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium bg-green-500/20 text-green-400 border border-green-500/20">
81
+ <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse"></span> 在线
82
+ </span>
83
+ </div>
84
+ <div class="flex items-end gap-1 h-8 mt-2">
85
+ <div v-for="i in 10" :key="i" class="flex-1 bg-brand-500/40 rounded-sm transition-all duration-300" :style="{height: Math.random() * 100 + '%'}"></div>
86
+ </div>
87
+ </div>
88
+ </div>
89
+ </aside>
90
+
91
+ <!-- Main Content -->
92
+ <main class="flex-1 flex flex-col h-full overflow-hidden bg-slate-50/50">
93
+ <!-- Header -->
94
+ <header class="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-4 md:px-8">
95
+ <button @click="mobileMenuOpen = !mobileMenuOpen" class="md:hidden p-2 text-slate-600 hover:bg-slate-100 rounded-lg">
96
+ <i class="fa-solid fa-bars"></i>
97
+ </button>
98
+ <div class="flex items-center gap-4 ml-auto">
99
+ <button @click="toggleRecording" :class="isRecording ? 'bg-red-50 text-red-600 border-red-200' : 'bg-slate-50 text-slate-600 border-slate-200 hover:bg-slate-100'" class="px-4 py-2 rounded-lg text-sm font-medium border flex items-center gap-2 transition-all">
100
+ <i :class="isRecording ? 'fa-solid fa-stop animate-pulse' : 'fa-solid fa-play'"></i>
101
+ ${ isRecording ? '停止记录' : '开始记录' }
102
+ </button>
103
+ <div class="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center text-slate-500 border border-white shadow-sm">
104
+ <i class="fa-solid fa-user"></i>
105
+ </div>
106
+ </div>
107
+ </header>
108
+
109
+ <!-- Scrollable Area -->
110
+ <div class="flex-1 overflow-y-auto p-4 md:p-8">
111
+
112
+ <!-- Dashboard View -->
113
+ <div v-if="currentView === 'dashboard'" class="space-y-6">
114
+ <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
115
+ <div v-for="(val, key) in metrics" :key="key" class="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
116
+ <div class="text-xs text-slate-500 font-medium uppercase tracking-wider mb-1">${ key }</div>
117
+ <div class="text-2xl font-bold text-slate-800 flex items-baseline gap-2">
118
+ ${ val.toFixed(1) }
119
+ <span class="text-xs font-normal text-slate-400">μV</span>
120
+ </div>
121
+ </div>
122
+ </div>
123
+
124
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
125
+ <div class="flex items-center justify-between mb-6">
126
+ <h3 class="font-bold text-slate-800">实时 EEG 波形监控</h3>
127
+ <div class="flex gap-2 text-xs">
128
+ <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-blue-500"></span> Alpha</span>
129
+ <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-indigo-500"></span> Beta</span>
130
+ </div>
131
+ </div>
132
+ <div ref="signalChart" class="chart-container"></div>
133
+ </div>
134
+
135
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
136
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
137
+ <h3 class="font-bold text-slate-800 mb-4">频带能量分布</h3>
138
+ <div ref="spectrumChart" class="chart-container" style="height: 250px;"></div>
139
+ </div>
140
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm flex flex-col">
141
+ <h3 class="font-bold text-slate-800 mb-4">会话控制</h3>
142
+ <div class="space-y-4 flex-1">
143
+ <div>
144
+ <label class="block text-sm font-medium text-slate-700 mb-1">受试者 ID</label>
145
+ <input v-model="subjectId" type="text" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-sm">
146
+ </div>
147
+ <div>
148
+ <label class="block text-sm font-medium text-slate-700 mb-1">训练类型</label>
149
+ <select v-model="sessionType" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-sm">
150
+ <option>Focus Training (专注训练)</option>
151
+ <option>Relaxation (放松引导)</option>
152
+ <option>Motor Imagery (运动想象)</option>
153
+ </select>
154
+ </div>
155
+ <button @click="analyzeSession" :disabled="isAnalyzing" class="w-full mt-auto bg-brand-600 hover:bg-brand-700 text-white py-2.5 rounded-lg font-medium transition-all shadow-lg shadow-brand-500/30 disabled:opacity-50 disabled:cursor-not-allowed flex justify-center items-center gap-2">
156
+ <i v-if="isAnalyzing" class="fa-solid fa-circle-notch animate-spin"></i>
157
+ ${ isAnalyzing ? '正在分析数据...' : '生成分析报告' }
158
+ </button>
159
+ </div>
160
+ </div>
161
+ </div>
162
+ </div>
163
+
164
+ <!-- Analysis View -->
165
+ <div v-if="currentView === 'analysis'" class="space-y-6">
166
+ <div v-if="!lastAnalysis" class="text-center py-20 bg-white rounded-xl border border-slate-200 border-dashed">
167
+ <div class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-300 text-2xl">
168
+ <i class="fa-solid fa-file-contract"></i>
169
+ </div>
170
+ <h3 class="text-slate-900 font-medium">暂无分析报告</h3>
171
+ <p class="text-slate-500 text-sm mt-1">请在“实时监控”页面生成一次会话分析。</p>
172
+ <button @click="currentView = 'dashboard'" class="mt-4 text-brand-600 font-medium text-sm hover:underline">去生成 &rarr;</button>
173
+ </div>
174
+
175
+ <div v-else class="grid grid-cols-1 lg:grid-cols-3 gap-6">
176
+ <!-- Left: Report -->
177
+ <div class="lg:col-span-2 space-y-6">
178
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
179
+ <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-100">
180
+ <div class="p-2 bg-brand-50 text-brand-600 rounded-lg">
181
+ <i class="fa-solid fa-wand-magic-sparkles"></i>
182
+ </div>
183
+ <div>
184
+ <h2 class="font-bold text-slate-900">AI 认知评估报告</h2>
185
+ <p class="text-xs text-slate-500">Based on SiliconFlow Intelligence</p>
186
+ </div>
187
+ </div>
188
+ <div class="prose prose-slate prose-sm max-w-none" v-html="parsedSummary"></div>
189
+ </div>
190
+
191
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
192
+ <h3 class="font-bold text-slate-800 mb-4">改进建议</h3>
193
+ <ul class="space-y-3">
194
+ <li v-for="(rec, idx) in lastAnalysis.recommendations" :key="idx" class="flex items-start gap-3 bg-slate-50 p-3 rounded-lg border border-slate-100">
195
+ <span class="flex-shrink-0 w-6 h-6 bg-brand-100 text-brand-600 rounded-full flex items-center justify-center text-xs font-bold">${ idx + 1 }</span>
196
+ <span class="text-sm text-slate-700">${ rec }</span>
197
+ </li>
198
+ </ul>
199
+ </div>
200
+ </div>
201
+
202
+ <!-- Right: Visuals -->
203
+ <div class="space-y-6">
204
+ <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
205
+ <h3 class="font-bold text-slate-800 mb-2">认知状态雷达</h3>
206
+ <div ref="radarChart" class="chart-container" style="height: 300px;"></div>
207
+ </div>
208
+
209
+ <div class="bg-gradient-to-br from-slate-900 to-slate-800 p-6 rounded-xl text-white shadow-lg">
210
+ <div class="text-xs text-slate-400 uppercase font-medium mb-1">主要状态</div>
211
+ <div class="text-2xl font-bold mb-4">${ lastAnalysis.cognitive_state }</div>
212
+ <div class="h-1 bg-white/10 rounded-full overflow-hidden">
213
+ <div class="h-full bg-brand-400 w-3/4"></div>
214
+ </div>
215
+ <div class="mt-2 text-xs text-slate-400 flex justify-between">
216
+ <span>Confidence</span>
217
+ <span>88%</span>
218
+ </div>
219
+ </div>
220
+ </div>
221
+ </div>
222
+ </div>
223
+
224
+ <!-- History View -->
225
+ <div v-if="currentView === 'history'" class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
226
+ <div class="p-6 border-b border-slate-100 flex justify-between items-center">
227
+ <h3 class="font-bold text-slate-800">历史会话档案</h3>
228
+ <button @click="fetchHistory" class="text-sm text-brand-600 hover:text-brand-700 font-medium">
229
+ <i class="fa-solid fa-rotate-right mr-1"></i> 刷新
230
+ </button>
231
+ </div>
232
+ <div class="overflow-x-auto">
233
+ <table class="w-full text-sm text-left">
234
+ <thead class="bg-slate-50 text-slate-500 font-medium">
235
+ <tr>
236
+ <th class="px-6 py-3">ID</th>
237
+ <th class="px-6 py-3">时间</th>
238
+ <th class="px-6 py-3">受试者</th>
239
+ <th class="px-6 py-3">类型</th>
240
+ <th class="px-6 py-3">状态评估</th>
241
+ <th class="px-6 py-3">操作</th>
242
+ </tr>
243
+ </thead>
244
+ <tbody class="divide-y divide-slate-100">
245
+ <tr v-for="item in historyList" :key="item.id" class="hover:bg-slate-50/50">
246
+ <td class="px-6 py-3 font-mono text-xs text-slate-400">#${ item.id }</td>
247
+ <td class="px-6 py-3 text-slate-600">${ item.timestamp }</td>
248
+ <td class="px-6 py-3 font-medium text-slate-900">${ item.subject_id }</td>
249
+ <td class="px-6 py-3">
250
+ <span class="px-2 py-1 rounded-full bg-blue-50 text-blue-600 text-xs font-medium border border-blue-100">${ item.session_type }</span>
251
+ </td>
252
+ <td class="px-6 py-3 text-slate-600">${ item.analysis.cognitive_state }</td>
253
+ <td class="px-6 py-3">
254
+ <button @click="loadAnalysis(item.analysis)" class="text-brand-600 hover:text-brand-700 font-medium text-xs">查看报告</button>
255
+ </td>
256
+ </tr>
257
+ <tr v-if="historyList.length === 0">
258
+ <td colspan="6" class="px-6 py-8 text-center text-slate-400">暂无历史记录</td>
259
+ </tr>
260
+ </tbody>
261
+ </table>
262
+ </div>
263
+ </div>
264
+
265
+ </div>
266
+ </main>
267
+ </div>
268
+
269
+ <script>
270
+ const { createApp, ref, onMounted, computed, watch, nextTick } = Vue;
271
+
272
+ createApp({
273
+ delimiters: ['${', '}'],
274
+ setup() {
275
+ const currentView = ref('dashboard');
276
+ const mobileMenuOpen = ref(false);
277
+ const isRecording = ref(false);
278
+ const isAnalyzing = ref(false);
279
+
280
+ const subjectId = ref('SUB-001');
281
+ const sessionType = ref('Focus Training (专注训练)');
282
+
283
+ const metrics = ref({ alpha: 0, beta: 0, theta: 0, delta: 0 });
284
+ const lastAnalysis = ref(null);
285
+ const historyList = ref([]);
286
+
287
+ // Chart Refs
288
+ const signalChart = ref(null);
289
+ const spectrumChart = ref(null);
290
+ const radarChart = ref(null);
291
+
292
+ let signalChartInst = null;
293
+ let spectrumChartInst = null;
294
+ let radarChartInst = null;
295
+ let timer = null;
296
+
297
+ // Data Buffers
298
+ const xData = [];
299
+ const yDataAlpha = [];
300
+ const yDataBeta = [];
301
+
302
+ const parsedSummary = computed(() => {
303
+ if (!lastAnalysis.value || !lastAnalysis.value.summary) return '';
304
+ return marked.parse(lastAnalysis.value.summary);
305
+ });
306
+
307
+ const initCharts = () => {
308
+ if (signalChart.value) {
309
+ signalChartInst = echarts.init(signalChart.value);
310
+ signalChartInst.setOption({
311
+ grid: { top: 20, right: 20, bottom: 30, left: 40 },
312
+ xAxis: { type: 'category', data: xData, boundaryGap: false },
313
+ yAxis: { type: 'value', min: 0, max: 40 },
314
+ series: [
315
+ { name: 'Alpha', type: 'line', smooth: true, data: yDataAlpha, showSymbol: false, lineStyle: { color: '#3b82f6', width: 2 } },
316
+ { name: 'Beta', type: 'line', smooth: true, data: yDataBeta, showSymbol: false, lineStyle: { color: '#6366f1', width: 2 } }
317
+ ],
318
+ animation: false
319
+ });
320
+ }
321
+
322
+ if (spectrumChart.value) {
323
+ spectrumChartInst = echarts.init(spectrumChart.value);
324
+ spectrumChartInst.setOption({
325
+ color: ['#3b82f6', '#6366f1', '#10b981', '#f59e0b'],
326
+ tooltip: { trigger: 'axis' },
327
+ xAxis: { type: 'category', data: ['Alpha', 'Beta', 'Theta', 'Delta'] },
328
+ yAxis: { type: 'value' },
329
+ series: [{
330
+ data: [10, 20, 5, 2],
331
+ type: 'bar',
332
+ itemStyle: { borderRadius: [4, 4, 0, 0] }
333
+ }]
334
+ });
335
+ }
336
+ };
337
+
338
+ const updateCharts = (data) => {
339
+ // Update Metrics
340
+ const latest = data[data.length - 1];
341
+ metrics.value = {
342
+ alpha: latest.alpha,
343
+ beta: latest.beta,
344
+ theta: latest.theta,
345
+ delta: latest.delta
346
+ };
347
+
348
+ // Update Signal Chart
349
+ data.forEach(p => {
350
+ xData.push(new Date().toLocaleTimeString());
351
+ yDataAlpha.push(p.alpha);
352
+ yDataBeta.push(p.beta);
353
+ if (xData.length > 50) {
354
+ xData.shift();
355
+ yDataAlpha.shift();
356
+ yDataBeta.shift();
357
+ }
358
+ });
359
+
360
+ if (signalChartInst) {
361
+ signalChartInst.setOption({
362
+ xAxis: { data: xData },
363
+ series: [
364
+ { data: yDataAlpha },
365
+ { data: yDataBeta }
366
+ ]
367
+ });
368
+ }
369
+
370
+ // Update Spectrum
371
+ if (spectrumChartInst) {
372
+ spectrumChartInst.setOption({
373
+ series: [{
374
+ data: [latest.alpha, latest.beta, latest.theta, latest.delta]
375
+ }]
376
+ });
377
+ }
378
+ };
379
+
380
+ const startMockData = () => {
381
+ timer = setInterval(() => {
382
+ if (!isRecording.value) return;
383
+ fetch('/api/mock/signal')
384
+ .then(res => res.json())
385
+ .then(res => {
386
+ if(res.status === 'success') {
387
+ updateCharts(res.data);
388
+ }
389
+ });
390
+ }, 1000);
391
+ };
392
+
393
+ const toggleRecording = () => {
394
+ isRecording.value = !isRecording.value;
395
+ };
396
+
397
+ const analyzeSession = async () => {
398
+ isAnalyzing.value = true;
399
+ try {
400
+ const res = await fetch('/api/analyze', {
401
+ method: 'POST',
402
+ headers: {'Content-Type': 'application/json'},
403
+ body: JSON.stringify({
404
+ subject_id: subjectId.value,
405
+ session_type: sessionType.value
406
+ })
407
+ });
408
+ const data = await res.json();
409
+ if (data.status === 'success') {
410
+ lastAnalysis.value = data.result;
411
+ currentView.value = 'analysis';
412
+ // Wait for DOM update then init radar
413
+ setTimeout(initRadarChart, 100);
414
+ }
415
+ } catch (e) {
416
+ alert('分析失败,请重试');
417
+ } finally {
418
+ isAnalyzing.value = false;
419
+ }
420
+ };
421
+
422
+ const initRadarChart = () => {
423
+ if (radarChart.value && lastAnalysis.value) {
424
+ radarChartInst = echarts.init(radarChart.value);
425
+ const radarData = lastAnalysis.value.radar_chart;
426
+ radarChartInst.setOption({
427
+ radar: {
428
+ indicator: Object.keys(radarData).map(k => ({ name: k, max: 100 })),
429
+ splitArea: {
430
+ areaStyle: {
431
+ color: ['#f8fafc', '#f1f5f9', '#e2e8f0', '#cbd5e1'].reverse()
432
+ }
433
+ }
434
+ },
435
+ series: [{
436
+ type: 'radar',
437
+ data: [{
438
+ value: Object.values(radarData),
439
+ name: '当前状态',
440
+ areaStyle: { color: 'rgba(14, 165, 233, 0.4)' },
441
+ lineStyle: { color: '#0ea5e9' }
442
+ }]
443
+ }]
444
+ });
445
+ }
446
+ };
447
+
448
+ const fetchHistory = async () => {
449
+ const res = await fetch('/api/history');
450
+ const data = await res.json();
451
+ if (data.status === 'success') {
452
+ historyList.value = data.history;
453
+ }
454
+ };
455
+
456
+ const loadAnalysis = (analysis) => {
457
+ lastAnalysis.value = analysis;
458
+ currentView.value = 'analysis';
459
+ setTimeout(initRadarChart, 100);
460
+ };
461
+
462
+ onMounted(() => {
463
+ initCharts();
464
+ startMockData();
465
+ fetchHistory();
466
+
467
+ // Responsive charts
468
+ window.addEventListener('resize', () => {
469
+ signalChartInst && signalChartInst.resize();
470
+ spectrumChartInst && spectrumChartInst.resize();
471
+ radarChartInst && radarChartInst.resize();
472
+ });
473
+ });
474
+
475
+ watch(currentView, (newVal) => {
476
+ if (newVal === 'dashboard') {
477
+ nextTick(() => {
478
+ initCharts();
479
+ });
480
+ } else if (newVal === 'analysis') {
481
+ nextTick(() => {
482
+ initRadarChart();
483
+ });
484
+ } else if (newVal === 'history') {
485
+ fetchHistory();
486
+ }
487
+ });
488
+
489
+ return {
490
+ currentView, mobileMenuOpen, isRecording, isAnalyzing,
491
+ subjectId, sessionType, metrics, lastAnalysis, historyList,
492
+ signalChart, spectrumChart, radarChart,
493
+ parsedSummary,
494
+ toggleRecording, analyzeSession, fetchHistory, loadAnalysis
495
+ };
496
+ }
497
+ }).mount('#app');
498
+ </script>
499
+ </body>
500
+ </html>