57 Commits

Author SHA1 Message Date
pluv 4ca9c65bea feat: 代码格式化, 改进仪表盘, 新增多CSS支持 2026-04-20 16:30:04 +08:00
pluv 8677e828c7 feat: 试增加单元集独立设置 2026-04-20 07:39:57 +08:00
pluv 709e15663b feat: 增加 ZMQ 调试服务器并完善设置功能 2026-04-20 06:37:46 +08:00
pluv 85925b9d44 feat: 补全设置提示与完善设置页 2026-04-20 05:05:44 +08:00
pluv 82fd8ab199 feat(interface): 图形化设置页原型 2026-04-20 03:33:05 +08:00
pluv 334d04444d style: 删除旧配置文件 2026-04-20 01:46:40 +08:00
pluv d1a1fa193f refactor: 对配置处理器和配置结构进行重构 2026-04-20 01:44:43 +08:00
pluv a8cd774123 fix: 变更哈希注册表以修复重复键造成的崩溃 2026-04-19 12:08:58 +08:00
pluv 0572848803 feat: FAST-0 特殊算法 2026-04-19 00:05:49 +08:00
pluv 279a78f7ce style: 移除设计不当的部分模块 2026-04-16 13:20:12 +08:00
pluv 2a388642e0 build: 修改依赖并引入外部库 2026-03-27 19:31:40 +08:00
pluv 92b4772eda feat(interface): 改进界面 2026-01-28 03:35:58 +08:00
pluv b38eaf4ef6 feat(interface): 改进仪表盘 2026-01-22 06:13:01 +08:00
pluv dde6df9bf0 fix: 修复若干问题 2026-01-17 05:45:45 +08:00
pluv 1077fcab39 fix(interface): 修复按钮标识和一个哈希问题 2026-01-15 12:49:57 +08:00
pluv bcb198f4d4 feat(interface): 改进状态显示 2026-01-13 23:39:10 +08:00
pluv ed361f88e2 build: 使用 uv 包管理器 2026-01-09 00:47:34 +08:00
pluv dd50dc7511 fix: 改进 2026-01-08 01:00:08 +08:00
pluv 67809463f1 fix: 小范围修补 2026-01-08 00:56:04 +08:00
pluv c051f0ffdd feat: 一系列新功能 2026-01-08 00:05:00 +08:00
pluv 1398368e18 feat(interface): 完成队列式记忆模块更新 2026-01-06 20:32:27 +08:00
pluv 85f9e84da4 fix: 修复完成屏幕问题 2026-01-06 19:58:46 +08:00
pluv 1f97a0c5ed fix: 修正逻辑问题 2026-01-06 18:28:57 +08:00
pluv 7d0f4e1466 feat: 更新状态机 2026-01-05 05:25:14 +08:00
pluv 1c297d3949 fix: 改进代码 2026-01-04 04:46:19 +08:00
pluv 5f64ae7250 fix(interface): 界面兼容性改进 2026-01-04 04:14:57 +08:00
pluv d9bf28cf75 fix(interface): 完成主要屏幕重构 2026-01-04 03:46:45 +08:00
pluv f4fd966373 fix: 部分修复重构数据格式差异 2026-01-04 02:11:07 +08:00
pluv 8cd6a8ccc6 feat(reactor): 状态机进一步改进 2026-01-04 00:28:44 +08:00
pluv 64223ce948 feat: 改进状态机 2026-01-03 13:08:08 +08:00
pluv e7e26e3e45 feat(kernel): 状态机改进 2026-01-03 05:05:41 +08:00
pluv 64c9a5c1a7 feat: 完成部分界面重构 2026-01-02 06:12:49 +08:00
pluv 238013ac46 feat: 改进对象系统 2026-01-01 20:18:18 +08:00
pluv 52ef6c65d4 feat: 基本完成对象系统更新 2026-01-01 16:19:46 +08:00
pluv 3ce102b358 feat: 改进粒子对象 2026-01-01 06:36:27 +08:00
pluv e830989368 feat: 进一步改进 2025-12-31 00:57:07 +08:00
pluv f056aaf00d feat: 一些改进 2025-12-29 21:53:20 +08:00
pluv 82560ef4e7 refactor: 部分更改数据结构 2025-12-28 06:16:21 +08:00
pluv ddcebb6dcd style: 格式化代码 2025-12-21 23:44:13 +08:00
pluv ce4860b930 feat(interface): 增加智能单元集排序 2025-12-21 23:42:02 +08:00
pluv 44dfd63212 fix: 暂时禁用实验性功能 2025-12-21 23:06:17 +08:00
pluv f6572cf5dd refactor(synctool): 改进同步方案 2025-12-21 21:18:31 +08:00
pluv 5c35e14d0f feat(synctool): 虚拟文件系统初步方案 2025-12-21 18:48:25 +08:00
pluv 490b87c639 style: 格式化代码 2025-12-21 07:56:10 +08:00
pluv 22eea3d668 feat(synctool): 增加同步功能 2025-12-21 07:49:19 +08:00
pluv 29b5978f8a feat(kernel): 添加算法切换设置 2025-12-21 06:48:30 +08:00
pluv 94f788d8f4 style: 更新版本号和合并规则 2025-12-21 06:34:17 +08:00
pluv ebaaac81db fix(interface): 修复仪表盘详情 2025-12-21 06:27:00 +08:00
pluv b8cfc03c2e feat(interface): 更改启动方式 2025-12-21 06:06:16 +08:00
pluv 9b7b633ec0 fix(interface): 修复显示问题 2025-12-21 05:47:22 +08:00
pluv fd0c197e98 feat: 自动音频播放与改进设计 2025-12-21 05:32:58 +08:00
pluv 4070246041 style(version): 更新版本号 2025-12-21 03:02:29 +08:00
pluv 083f813651 feat: 实验性 SM-15M 算法实现
实验性 SM-15M 逆向工程算法实现
2025-12-21 02:15:23 +08:00
pluv 2600dffee3 style: isort 格式化 2025-12-19 15:13:42 +08:00
pluv b09e67b3eb style: 格式化代码 2025-12-19 15:08:26 +08:00
pluv 218dba21f2 fix(interface): 修复默认配置文件 2025-12-18 15:53:18 +08:00
pluv 3866b9620c refactor: 完成 0.4.0 版本更新
完成 0.4.0 版本更新, 为了消除此前提交消息风格不一致与错误提交超大文件的问题, 维持代码统计数据的准确性和提交消息风格的一致性, 重新初始化仓库; 旧的提交历史在 HeurAMS-legacy 仓库(https://gitea.imwangzhiyu.xyz/ajax/HeurAMS-legacy)
2025-12-17 22:31:38 +08:00
161 changed files with 24211 additions and 5993 deletions
+155 -28
View File
@@ -1,19 +1,33 @@
# HeurAMS specific rules
*.log.*
*.log
*.pkl
/data
# Editor
# Project specific additions
.devflag
.vscode/
.directory
__pycache__/
.idea/
cache/
data/repo/cngk
data/repo/eotgk
data/repo/evtgk
*.egg-info/
build/
dist/
old/
data/cache/
data/global/
config/config_dev.toml
AGENTS.md
*.log.*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
@@ -32,6 +46,16 @@ share/python-wheels/
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
@@ -46,10 +70,73 @@ coverage.xml
.hypothesis/
.pytest_cache/
cover/
.claude/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly used for packaging.
#poetry.lock
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
#pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
@@ -59,32 +146,72 @@ ENV/
env.bak/
venv.bak/
# Linux
*~
.fuse_hidden*
.directory
.Trash-*
.nfs*
## KDE Dolphin
.directory
# Spyder project settings
.spyderproject
.spyproject
# macOS
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
.idea/
# Audio cache and temporary files
*.mp3
*.wav
*.ogg
*.tmp
# LLM cache files
*.cache
*.jsonl
# Log files
*.log
logs/
# OS generated files
.DS_Store
.AppleDouble
.LSOverride
.DS_Store?
._*
.AppleDB
.AppleDesktop
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Windows
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
[Dd]esktop.ini
$RECYCLE.BIN/
*.lnk
Desktop.ini
# Other trash
AGENT.md
# It's not AGENTS.md
# Linux
*~
# VSCode
.vscode/
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Temporary files
*.tmp
*.temp
-50
View File
@@ -1,50 +0,0 @@
# AI 编程工具说明
本文档为 AI 工具以及在使用 AI 辅助向 HeurAMS 项目贡献代码的开发者提供指导, 一般而言此文件会被自动读入多种 AI 工具的上下文.
AI 工具应当完整阅读此 `/AGENTS.md` 文件.
## 查阅开发文档
在帮助进行 HeurAMS 开发时,AI 工具应遵循标准的开发规范与流程, 应当自动查看或是在用户发出"初始化/init"指令后查看:
- [贡献指南](/CONTRIBUTING.md)
- [自述文件](/README.md)
- [项目架构](/ARCHITECTURE.md)
## 明确禁止行为
1. 禁止 AI 自动生成 PR 或 patch 文件
2. 禁止 AI 在未经人工确认的情况下修改现有代码
3. 禁止 AI 不使用格式化工具而生成格式化文件的行为
4. 禁止 AI 修复任何"bug", 而不经人工确认
5. 禁止一切不遵循项目设计原则, 另造独立库的 "糊屎" 行为
6. 禁止 AI 直接操作 pip, uv, apt 等工具修改外部依赖或工具, 而应让人类开发者自己操作依赖
7. 禁止使用不同于任何现有文件的现有注释语言的其他语言写新注释
8. 禁止不读文件就直接覆写
9. 绝对禁止修改此 `/AGENTS.md` 文件
## 许可证与法律要求
所有贡献必须符合许可要求, 所有代码必须与 AGPL-3.0-or-later 许可以及项目附加豁免条款(位于 LICENSE 文件尾部 237 至 245 行)兼容.
## Signed-off-by 与 DCO
AI 代理**严禁添加** Signed-off-by 标签.
只有人类能够合法地认证 DCO.
人类提交者负责:
- 审阅所有 AI 生成的代码
- 确保符合许可要求
- 添加自己的 Signed-off-by 标签以认证 DCO
- 对贡献负责任
AI 助手负责:
- 了解运行环境, 例如操作系统或具体发行版
- 遵循此文档所述规则
- 主动提醒使用 AI 工具的开发者
本文档参考自 <a href="https://docs.kernel.org/process/coding-assistants.html" target="_blank" rel="noopener noreferrer">AI Coding Assistants — The Linux Kernel documentation</a>
-438
View File
@@ -1,438 +0,0 @@
## 整体架构概览
```mermaid
graph TB
subgraph "用户界面层 (TUI)"
TUI[Textual App]
Screens[应用屏幕]
Widgets[谜题组件]
end
subgraph "内核层 Kernel"
Reactor[调度反应器]
Algorithms[算法模块]
Particles[数据模型]
Puzzles[谜题引擎]
RepoLib[仓库系统]
Auxiliary[辅助工具]
end
subgraph "服务层"
Config[配置管理 ConfigDict]
Logger[日志系统]
Timer[时间服务]
Audio[音频服务]
TTS[TTS 服务]
Favorites[收藏管理]
Attic[持久化]
Hasher[哈希服务]
end
subgraph "提供者层"
AudioProv[音频提供者]
TTSProv[TTS 提供者]
LLMProv[LLM 提供者]
end
subgraph "数据层"
RepoDir[TOML/JSON 仓库目录]
ConfigDir[TOML 配置目录]
Logs[日志文件]
end
TUI --> Screens
Screens --> Reactor
Screens --> RepoLib
Screens --> Widgets
Widgets --> Puzzles
Widgets --> Reactor
Reactor --> Algorithms
Reactor --> Particles
Reactor --> Puzzles
Particles --> RepoLib
RepoLib --> Config
RepoLib --> Auxiliary
Auxiliary --> Lict
Auxiliary --> Evalizer
TUI --> Config
TUI --> Logger
TUI --> Audio
TUI --> TTS
Config --> ConfigDir
Audio --> AudioProv
TTS --> TTSProv
Attic --> RepoDir
```
## 数据模型
项目以物理粒子隐喻为核心, 将记忆单元拆解为三个模型:
### Nucleon (核子) - 内容层
```
Nucleon(ident, payload, common)
```
- **只读**内容容器. 通过 `Evalizer` (基于 `eval()` 的模板系统)对 payload 和 common 进行编译展开.
- 包含 `puzzles` 字段, 定义该记忆单元支持哪些谜题类型.
-`repo.payload``repo.typedef["common"]` 配对创建.
- 一旦创建, 内容不可修改 (`__setitem__` 抛出 `AttributeError`).
### Electron (电子) - 状态层
```
Electron(ident, algodata, algo_name)
```
- 算法状态数据的包装器. 每个 Electron 绑定一个算法 (`algorithms[algo_name]`).
- `algodata` 是到仓库 `algodata.lict` 中对应字典的**引用**, 修改即持久化.
- 核心方法:`activate()` (标记激活)、`revisor()` (评分迭代)、`is_due()` (到期判断).
### Orbital (轨道) - 策略层
```
orbital = {
"schedule": ["quick_review", "recognition"],
"routes": {
"quick_review": [["MCQ", "1.0"], ["Cloze", "0.5"]],
"recognition": [["Recognition", "1.0"]],
}
}
```
- 定义复习阶段流程和各阶段内谜题选择策略的纯字典.
- 每个阶段对应一组 `(谜题类型, 概率系数)` 元组列表, 概率系数 >1 的部分表示强制重复次数.
### Atom (原子) - 运行时组装
```
Atom(nucleon, electron, orbital)
```
- 三者的运行时组合, 附带 `runtime` 运行时标志 (`locked`, `min_rate`, `new_activation`).
- 是 UI 和调度层操作的基本单位.
- `revise()` 方法在 `locked` 为真时调用 `electron.revisor(min_rate)`, 执行最终评分迭代.
**关系图**
```mermaid
graph LR
subgraph "持久化存储"
Payload[(payload.toml)]
Common[(typedef.toml)]
Algodata[(algodata.json)]
Schedule[(schedule.toml)]
end
subgraph "运行时组装"
Nucleon -->|内容| Atom
Electron -->|状态| Atom
Orbital -->|策略| Atom
end
Payload -->|Repo| Nucleon
Common -->|Repo| Nucleon
Algodata -->|Repo| Electron
Schedule -->|Repo| Orbital
```
## 调度反应器 (Reactor)
调度反应器是核心业务流程引擎, 采用三层嵌套的有限状态机设计 (基于 `transitions` 库).
### 状态枚举定义
| 状态机 | 状态 | 说明 |
|--------|------|------|
| **RouterState** | `unsure` | 初始状态, 自动推进 |
| | `quick_review` | 快速复习阶段 |
| | `recognition` | 新记忆识别阶段 |
| | `final_review` | 最终总复习阶段 |
| | `finished` | 完成, 执行评分 |
| **ProcessionState** | `active` | 进行中 |
| | `finished` | 已完成 |
| **ExpanderState** | `exammode` | 考试模式 (正面答题) |
| | `retronly` | 回溯模式 (仅识别) |
### 状态机嵌套结构
```mermaid
graph TB
subgraph "Router (全局路由器)"
R[Router<br/>状态: unsure→quick_review<br/>→recognition→final_review<br/>→finished]
P1[Procession 队列1: 快速复习]
P2[Procession 队列2: 新记忆]
P3[Procession 队列3: 总复习]
R --> P1
R --> P2
R --> P3
end
subgraph "Procession (单阶段队列)"
P1 --> E1[Expander 原子A]
P1 --> E2[Expander 原子B]
P1 --> E3[Expander 原子C]
M{forward 推进} --> |完成| Finish((FINISHED))
end
subgraph "Expander (单原子展开器)"
E1 --> S[(轨道策略)]
S -->|概率展开| PZ1[谜题1: MCQ]
S -->|概率展开| PZ2[谜题2: Cloze]
PZ1 -->|评分| RPT[report]
PZ2 -->|评分| RPT
RPT -->|finish| RETRO[retronly 回溯模式]
end
```
### 数据流详解
```
Router.__init__(atoms)
├─ 新旧原子分流
│ ├─ old_atoms → Procession(quick_review) "初始复习"
│ └─ new_atoms → Procession(recognition) "新记忆"
└─ 所有原子 → Procession(final_review) "总体复习"
└─ Procession.forward()
├─ cursor >= len(atoms) → finish()
└─ cursor < len(atoms) → next_atom
└─ Procession.get_expander()
└─ Expander(atom, route)
├─ 读取 orbital.routes[route_value]
├─ 概率展开为谜题列表 self.puzzles_inf
├─ exammode → 依次展示谜题
├─ report(rating) → 记录最低评分
├─ forward() → 下一个谜题或 finish → retronly
└─ retronly → 展示 Recognition
└─ Atom.revise()
└─ Electron.revisor(min_rate)
└─ Algorithm.revisor(algodata, feedback)
```
评分累积机制: 原子在多谜题阶段的最终评分取所有谜题的最低评分 (`min_rate`), 确保严格评估.
## 算法系统
所有算法继承自 `BaseAlgorithm`, 以类方法的风格实现, 通过 `algorithms` 字典注册.
| 算法 | 文件 | 状态 | 说明 |
|------|------|------|------|
| **SM-2** | `sm2.py` | ✅ 完成 | 经典 SuperMemo 1987 算法 |
| **NSP-0** | `nsp0.py` | ✅ 完成 | 非间隔过滤调度器 |
| **SM-15M** | `sm15m.py` | ✅ 完成 | 从 CoffeeScript 移植的 SM-15 |
| **FSRS** | `fsrs.py` | ✅ 部分完成 | 优化器不可用 |
| **Base** | `base.py` | ✅ 基类 | 定义 `AlgodataDict` 结构和默认值 |
每个算法提供以下类方法:
| 方法 | 功能 |
|------|------|
| `revisor(algodata, feedback, is_new_activation)` | 根据评分迭代记忆数据 |
| `is_due(algodata)` | 判断是否到期复习 |
| `get_rating(algodata)` | 获取评分信息 |
| `nextdate(algodata)` | 获取下一次复习时间戳 |
| `check_integrity(algodata)` | 校验 algodata 数据结构完整性 |
### 算法数据结构 (AlgodataDict)
```python
{
"real_rept": int, # 实际复习次数
"rept": int, # 当前重复计数
"interval": int, # 间隔天数
"last_date": int, # 上次复习日期
"next_date": int, # 下次到期日期
"is_activated": int, # 是否已激活 (0/1)
"last_modify": float, # 最后修改时间戳
}
```
## 仓库系统 (Repo)
仓库为 TOML/JSON 文件目录, 无数据库依赖.
### 目录结构
```
data/repo/<package_name>/
├── manifest.toml # 元信息: title, author, package, desc
├── typedef.toml # 通用元数据、谜题定义、注解
├── payload.toml # 记忆条目 (key=ident)
├── algodata.json # 算法状态 (key=ident)
└── schedule.toml # 轨道/复习策略
```
### Repo 类设计
```mermaid
classDiagram
class Repo {
+dict schedule
+Lict payload
+dict manifest
+dict typedef
+Lict algodata
+Path source
+Lict nucleonic_data_lict
+dict orbitic_data
+Lict electronic_data_lict
+from_repodir(source) ~Repo
+from_dict(dictdata) ~Repo
+create_new_repo() ~Repo
+persist_to_repodir(save_list, source)
+export_to_dict() dict
}
```
- `payload``algodata` 使用 `Lict` (列表+字典混合容器), 支持双模式访问.
- `_generate_particles_data()` 在初始化时自动将 payload 数据转换为 `Nucleon` 所需的格式.
- 默认保存列表 `default_save_list = ["algodata"]`, 仅持久化算法状态.
## Lict 集合
`Lict` 继承 `MutableSequence`, 同时维护列表和字典访问:
```python
lict = Lict()
lict.append(("key1", value1)) # 列表追加
lict["key1"] # 字典访问
lict[0] # 索引访问
lict.keys() # 所有键
lict.dicted_data # 纯字典导出
```
脏同步机制:修改列表时自动同步字典, 修改字典时自动同步列表. 用于 `payload``algodata` 的双模式访问需求.
## 配置系统 (ConfigDict)
`ConfigDict` 继承 `UserDict`, 是**单例模式**的 TOML 懒加载配置管理器.
### 配置目录约定
```
data/config/
├── _.toml # 顶层默认值 (递归合并)
├── interface/
│ ├── _.toml # interface 层默认值
│ ├── global.toml
│ └── puzzles.toml
├── services/
│ ├── _.toml # services 层默认值
│ ├── audio.toml
│ └── tts.toml
└── repo/
└── _.toml
```
- `_.toml` 文件 = 该目录层级的默认值, 合并到父级
- 带后缀文件 = 按需懒加载
- 子目录 = 递归子配置
### 上下文管理
```python
from heurams.context import config_var, ConfigContext
# 全局访问
config = config_var.get()
algo = config["interface"]["global"]["algorithm"]
# 作用域覆盖
with ConfigContext(test_config):
... # 临时使用测试配置
```
## 提供者系统 (Providers)
可插拔的后端实现, 通过 `providers/__init__.py` 中的字典注册.
| 类别 | 提供者 | 说明 |
|------|--------|------|
| **TTS** | `edge_tts` | Microsoft Edge TTS (在线) |
| | `basetts` | 桩基类 (未实现) |
| **Audio** | `playsound` | 跨平台音频播放 |
| | `termux` | Android Termux 环境 |
| **LLM** | `openai` | OpenAI 兼容 API (未完整实现) |
选择方式:`services/*.toml` 中的 `provider` 字段.
## 谜题系统 (Puzzles)
谜题引擎用于在复习阶段生成评估视图:
| 谜题 | 文件 | 说明 |
|------|------|------|
| **MCQ** | `mcq.py` | 选择题 (Multiple Choice) |
| **Cloze** | `cloze.py` | 完形填空 (Cloze Deletion) |
| **Recognition** | `recognition.py` | 认读识别 |
| **Guess** | `guess.py` | 猜测词义 |
| **Base** | `base.py` | 抽象基类 |
谜题通过轨道策略 (Orbital)在 `Expander` 中按概率展开, 每个原子可产生多个谜题, 每个谜题独立评分.
## 服务层
| 服务 | 文件 | 说明 |
|------|------|------|
| **Config** | `config.py` | `ConfigDict(UserDict)` TOML 懒加载单例 |
| **Logger** | `logger.py` | `get_logger(name)` → 层级日志 (`heurams.*`) |
| **Timer** | `timer.py` | `get_daystamp()` / `get_timestamp()`, 支持可配置覆盖 |
| **Audio** | `audio_service.py` | 音频播放, 路由到配置的音频提供者 |
| **TTS** | `tts_service.py` | 文本转语音, 路由到配置的 TTS 提供者 |
| **Favorites** | `favorite_service.py` | JSON5 持久化的收藏管理器 (单例) |
| **Attic** | `attic.py` | 结构化 pickle 持久化, 支持 `<DAYSTAMP>`/`<TIMESTAMP>` 占位符 |
| **Hasher** | `hasher.py` | MD5 哈希 |
| **Epath** | `epath.py` | 点符号嵌套字典访问 (`epath(dct, "a.b.c")`) |
| **TextProc** | `textproc.py` | `truncate()`, `domize()`, `undomize()` |
日志系统:每个模块通过 `get_logger(__name__)` 创建自己的日志器, 日志文件 10MB 轮转, 最多 5 个备份, 追加到 `heurams.log`.
## 复习全流程
```mermaid
sequenceDiagram
participant User as 用户
participant UI as TUI
participant Router as Router
participant Procession as Procession
participant Expander as Expander
participant Atom as Atom
participant Electron as Electron
participant Algo as Algorithm
User->>UI: 开始复习
UI->>Router: Router(atoms)
Router->>Procession: 创建复习队列
Router->>Procession: 创建新记忆队列
Router->>Procession: 创建总复习队列
Procession->>Expander: 展开当前原子
Expander->>Expander: 解析轨道策略
Expander-->>UI: 展示谜题
User->>UI: 评分 (1-5)
UI->>Expander: report(rating)
Expander->>Expander: forward() 下一个谜题
Expander-->>UI: 下一个谜题或回溯
Expander->>Expander: finish() → retronly
Expander-->>UI: Recognition 回溯
User->>UI: 最终评分
UI->>Atom: revise()
Atom->>Electron: revisor(min_rate)
Electron->>Algo: revisor(algodata, feedback)
Algo-->>Electron: 更新 algodata
Algo-->>Atom: 更新 interval, next_date
Procession->>Procession: forward() 下一原子
Procession-->>Router: 队列完成
Router->>Router: 切换阶段
Router-->>UI: 完成 (finished)
UI->>User: 显示总结
```
+26 -103
View File
@@ -1,119 +1,42 @@
# 贡献指南与二次开发
# 贡献指南
欢迎支持此项目!
目前, 项目仓库主服务器为<a href="https://git.pluv27.top/pluv/HeurAMS" target="_blank" rel="noopener noreferrer">作者的 Gitea 实例</a>, 它负责管理同步, 保证可用性并同时接受来自多个社区的协作, 并在 <a href="https://github.com/pluvium27/HeurAMS" target="_blank" rel="noopener noreferrer">GitHub</a>, <a href="https://invent.kde.org/pluv/HeurAMS" target="_blank" rel="noopener noreferrer">KDE Invent</a> 和 <a href="https://gitee.com/pluv/HeurAMS" target="_blank" rel="noopener noreferrer">Gitee</a> 设置了镜像同步.
这丝毫不影响项目接受来自 <a href="https://github.com/pluvium27/HeurAMS" target="_blank" rel="noopener noreferrer">GitHub</a>, <a href="https://invent.kde.org/pluv/HeurAMS" target="_blank" rel="noopener noreferrer">KDE Invent</a> 和 <a href="https://gitee.com/pluv/HeurAMS" target="_blank" rel="noopener noreferrer">Gitee</a> 的 PR, 在 GitHub, KDE Invent 和 Gitee 所接受的 PR 会保留贡献者标识并按原样同步回所有平台, 欢迎在任意平台为项目做出贡献.
> [!NOTE]
> 我们已经开始着手于基于 KDE 用户界面框架 `Kirigami` 的现代跨平台前端开发, 称作 "KiriMemo", 包名是 "org.kde.kirimemo", 但其并非 KDE 项目\
> 它通过 `PyOtherSide` 直接复用 python 内核, 为 Windows, Linux, macOS, Android, iOS 和 Plasma Mobile 提供现代用户界面
> 如果您善于开发 C++, QML, Qt 与 KDE 框架, 欢迎加入到 KiriMemo 项目的开发
欢迎此项目做出贡献!\
本项目是一个开源项目, 我们鼓励社区成员参与改进.
## 开发规范
分支划分:
- `dev` 分支(仓库默认分支): 主线开发分支, 自身仅用于非重构的问题修复和整合功能分支, 拉取请求在该分支合并
- `master` 分支: 主线稳定版本, 仅当稳定版本释出或修补版本时将 `dev` 合并到 `master`
- 功能与重构分支: 从 `dev` 分支创建, 命名格式为 `feature/描述``fix/描述``refactor/描述``next/版本号`
- 功能与重构分支应先合并至 `dev`, 再合并至 `master`
代码格式化:
- 安装工具:
```bash
python -m pip install black autoflake mdformat
```
- 对于 Python, 使用 `black` 与 `autoflake` 格式化\
命令:
```bash
# black 的多线程在某些环境下有兼容性问题
black . --workers=1
```
```bash
# autoflake 注意排除 __init__.py
autoflake --in-place --remove-all-unused-imports --recursive ./src/ --exclude __init__.py
```
- 对于 Markdown, 使用 `mdformat` 格式化
命令:
```bash
mdformat --number .
```
- 对于 Textual CSS, 可以使用 `prettier` 格式化
- 格式化不是必需的, 可以整合入一次 `style` 提交, 但 `master` 和 `dev` 分支上的代码应尽量整洁, 以便合并时审查
提交消息:
- 使用简体中文或英文撰写清晰的提交消息
- 提交消息格式: 遵循 [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) 规范, 建议使用 `koji` 工具
合并方式:
- 为了一致性和可追溯性, 项目自 v0.4.0 重构后重新初始化仓库起就禁止使用 Fast-forward 合并
- 可以设置 `git config merge.ff false`
提交署名方式:
由于 KDE Invent 设施的奇怪 git hook, commit 的 Author 字段需要看起来像个真名(例如 Wang Zhiyu 不能写为 wangzhiyu, 否则 KDE Invent 的 hook 会拒绝 push),
所以请确保您的 git 配置使用了类似正式姓名的格式 (例如 git config user.name "Li Hua", 也即中间需要空格), 不一定要真实姓名, 邮箱无要求, 也可以将单名重复使用两次 (例如 Thura Thura) 以通过检测.
1. 分支划分:
- `main` 分支: 稳定版本
- `dev` 分支: 开发版本
- 功能分支: 从 `dev` 分支创建, 命名格式为 `feature/描述``fix/描述``refactor/描述`
1. 代码风格:
- 请使用 Black 格式化代码
- 遵循 PEP 8 规范
- 添加适当的文档字符串
1. 提交消息:
- 使用简体中文或英文撰写清晰的提交消息
- 格式: 遵循 Conventional Commits 规范
1. 合并方式:
- 不使用 Fast-forward 合并
- 可以设置 `git config merge.ff false`
## 设置开发环境
```bash
git clone https://git.pluv27.top/pluv/HeurAMS # 默认分支为 dev, 所以不必切换分支
# 克隆仓库
git clone https://gitea.imwangzhiyu.xyz/ajax/HeurAMS
cd HeurAMS
# 如果决定使用 uv (推荐)
# 你可能需要切换分支
python3 -m pip install uv
# 安装依赖
pip install -r requirements.txt
uv sync --all-extras # 同步开发运行环境
uv run heurams
# 如果决定使用原生 python 环境 (不推荐, 但我们保留了这种方式以便在不便支持 uv 与硬链接的环境和文件系统(例如 termux)上运行)
python3 -m pip install -e .[all] # 安装依赖并将 HeurAMS 安装为本地包
python3 -m heurams # 验证安装
python3 -m heurams.interface # 启动 TUI
# 安装开发版本
pip install -e .
```
## 许可证与外部引用
## 许可证
贡献者拥有其贡献部分的版权同意其贡献将在 AGPL-3.0 许可证(包括附加的本机 API 调用豁免条款)下发布.
如有以下情况, 请在 PR 描述中注明:
- 如果需要引入其他开源 vendor
- 如果需要引入其他专有的网络服务(例如当前项目中的 edgetts)
- 如果需要升级某个依赖或运行环境的版本
## 新的用户界面前端
HeurAMS 被设计为一个可独立于前端的程序库, 这意味着:
- 我们的内置 Textual TUI 前端不是唯一可用的前端
- 如果您有一个自己开发的且可用的 HeurAMS 前端 (例如未实现的 Flutter 前端), 并且以 AGPL-3.0/GPL-3.0 开放源代码, 可以联系我们将它转移到 HeurAMS 的官方仓库中以便共同维护, 您将保留您的版权并可主导该仓库下的开发工作 :)
- 您还可以在自己的项目中以独立进程/服务调用 HeurAMS, 根据 AGPL-3.0 及本项目的附加许可条款, 如果调用发生在同一主机上且不涉及外部网络转发, 则可豁免许可证规定的特定义务而免于受 AGPL-3.0 "污染". 为了这点, 我们正在完善可选择启用的跨进程 RPC 模块, 这将成为潜进内核的跨平台标准件.
- 如果您通过独立进程/服务调用方式开发了另外的软件, 开源但不愿使用 AGPL-3.0/GPL-3.0 许可证, 也可以联系我们, 我们乐于将您的项目链接添加到友链中
## 软件开发之外的贡献
即使您不是软件开发人员, 我们也欢迎您加入贡献!
您可以:
- 协助创建或核对各种语言的翻译来翻译软件的界面和文档
- 制作开放的记忆单元集(包括但不限于文字、图像、音效)给其他用户使用
- 改进软件配套的文档
- 给其他用户答疑解惑或分享自己的经验
- 在讨论区提出新想法或反馈问题
您的角色您来定!
贡献者同意其贡献将在 AGPL-3.0 许可证下发布.
-416
View File
@@ -1,416 +0,0 @@
# 常见问题
## 什么是终端模拟器?
终端模拟器是在图形桌面环境中模拟并使用终端的应用程序, 例如 KDE Konsole, GNOME Terminal, Windows Terminal, iTerm2 等.
较旧 Windows 的那个很寒酸的小黑窗口也是终端模拟器(conhost.exe), 但它对此软件基本用户界面(以及一切现代终端应用)支持不佳, 建议在 Windows 平台使用 WezTerm (支持 sixel) 或 Windows Terminal (不支持 sixel).
## 软件支持移动设备吗?
基本用户界面 (Textual TUI) 可在 Android Termux 中良好运行.
此外, 正在开发的 KiriMemo 前端基于 KDE Kirigami 框架, 将原生支持 Android 和 iOS.
## HeurAMS 和 Anki 有什么区别?
大体地说:
| 方面 | HeurAMS | Anki |
|------|---------|------|
| 数据格式 | 文本文件 (TOML/JSON), 人类可读 | SQLite 和资源文件组成的专有压缩格式 (.apkg) |
| 复习模式 | 多阶段流程 + 多种谜题类型 | 单面/双面闪卡 |
| 算法系统 | 模块化, 可插拔, 多种算法可选 | 内置 SM-2 / FSRS |
| 插件生态 | 较少, 体现于类似微内核架构的"能力扩展", 例如新算法或新服务 | 多, 但为不受限的"猴子补丁" |
| 用户基数 | 少 | 多 |
| 现有资源丰富度 | 少 | 多 |
| AI 辅助产生单元集/牌组 | 原生支持 | 困难 |
| 协议 | AGPL-3.0, 有一个附加豁免条款 | AGPL-3.0 |
## 软件是免费的吗?
是的, 完全免费, 且开源. 您无需支付任何费用即可使用全部功能.
## 黑乎乎的这个界面我怎么用?
首先, 如果您只是想要一个亮色模式, 可以直接按下 `d` 键或点击 "d 主题" 按钮, 这会让您的界面变得白乎乎的(
得益于微软几十年对用户进行的"命令行即落后"教育, 以及 `conhost.exe``cmd.exe` 的糟糕体验, 您对终端用户界面感到不适应是完全正常的.
但实际上, 虽然看起来像老式电脑屏幕, Textual 和终端标准其实比您想象得要现代一些.
### 可以用鼠标
现代终端模拟器 (如 Windows Terminal、Konsole、iTerm2、WezTerm 等) 支持一个叫做 "鼠标跟踪" (Mouse Tracking) 的功能, 而 Textual 启动时会发送特殊指令给终端让它报告鼠标事件.
所以可能和您的想象不同, 您事实上可以直接用鼠标点击按钮, 就像使用普通软件一样.
### 也可以用键盘
- `Tab` 键在不同区域之间切换焦点
- `方向键` 在列表中上下移动
- `Enter` 确认选择
- `q` 返回
- 屏幕上会有按键提示, 例如 `[n] 导航器` 表示按 `n` 键打开导航器
### 触屏也可以
在平板或手机 Termux 中, 您可以触摸或者滑动屏幕操作.
## 我怎么启动这个软件?
首先需要确保系统中安装了 Python (推荐 3.12.13 版本) 并安装了 HeurAMS 的所需组件.
### Windows
打开"命令提示符"或"PowerShell", 输入以下命令后按回车, 或者把这玩意另存为快捷方式:
```
python -m heurams.interface
```
### macOS
打开"终端"应用程序, 输入以上命令.
### Linux
打开您的终端模拟器 (一般是按 Ctrl + Alt + T), 输入以上命令.
如果您觉得每次输入命令太麻烦, 可以创建一个桌面快捷方式或脚本文件, 详见网上的相关教程.
## 我怎么退出软件?
按键盘上的 `q` 键返回主界面后退出.
您的学习进度会自动保存, 不会丢失.
## 图片像素很大, 模糊得像马赛克一样怎么办?
这说明图像以 Halfcell 兼容模式显示
终端模拟器需要支持 sixel 图像协议才能高清地显示图片, 对于不支持的图片, 软件只能以低清的兼容模式显示.
- WezTerm (适用于几乎所有操作系统): 支持
- KDE Konsole: 支持
- GNOME Terminal: 不支持
- iTerm2 (macOS): 支持
- Windows Terminal: 不支持
- mintty (Windows): 支持
如果您的终端不支持图片, 软件的其他功能不受影响, 只是记忆内容中的图片无法显示.
## 中文显示成乱码或方框怎么办?
这说明您没有正确设置终端中文字体. 请检查:
1. 您没有使用 getty 和 xterm 这种明确不支持非 ASCII 字体的终端
2. 终端设置中的字体选项, 选择一款支持中文的字体, 例如 "Noto Sans SC", "微软雅黑", "Source Han Sans"
3. 确保终端的字符编码设置为 UTF-8 (通常是默认值)
## 我的数据存哪里了? 会不会丢?
数据存储在软件安装目录下的 `data/` 文件夹中:
- 您可以用记事本直接打开查看和修改
- 复制粘贴 `data/` 文件夹到 U 盘或网盘即可完成备份 (推荐定期备份)
- 即使软件卸载了, 只要保留 `data/` 文件夹, 重新安装后复制回去, 所有学习记录都在
## 怎么跟朋友分享我的单元集?
找到 `data/repo/` 下的对应文件夹, 复制整个文件夹发给朋友即可. 对方把它放到自己的 `data/repo/` 目录下就能用.
您也可以导出为单一文本文件或压缩包, 通过微信、QQ、邮件等方式分享.
## 我复制粘贴不了内容?
一般来说, 在终端中:
- 复制: Ctrl+Shift+C
- 粘贴: Ctrl+Shift+V
这和普通软件的操作习惯不太一样(因为 Ctrl + C 在终端中的语义是 "中断进程"), 但稍加适应即可.
## 字体太小/太大怎么办?
在您的终端模拟器设置中找到"字体大小"选项进行调整.
软件会跟随终端的字体设置.
## 为什么我的界面和截图不一样?
截图使用的是 KDE Plasma 桌面上的 Konsole, 80x25 字符尺寸, Cascadia Code 和 Noto Sans SC 字体.
如果您的终端尺寸更大, 界面会更宽裕; 如果使用不同字体或者不同操作系统, 视觉效果会略有差异.
功能上完全一致.
## 评分 (1-5) 是什么意思? 我该怎么打分?
需要说明的是, 我们非常不鼓励这种类似 Anki, 让用户自己直接给自己评分的单元集设计(在我们的程序中, 这种方式的实现被称为 `basic_puzzle`, 基本只用于算法测试).
因为我们认为这种方式非常主观, 而且还需要您思考"我是多少分""我是不是乐观了""我是不是分低了""我要是把分评错了怎么办"这一系列打断记忆进程且令人焦虑的问题, 这本质上是把责任推给用户, 并且违背了认知科学原理.
并且这种方式于学术研究与实验不利, 用户自评分产生的数据是不可靠的.
因此 HeurAMS 的前端内建了基于用户行为分析的自动评分系统, 也就是"谜题".
它会根据题目本身难度和您的答题行为(包括但不限于正确性, 操作回退次数, 有效答题时间)并自动为您评分.
但如果您或者某个单元集选择使用 `basic_puzzle`, 或者打算自己实现自动评分系统, 分数含义如下:
| 分数 | 含义 | 说明 |
|------|------|------|
| 1 | 完全忘了 | 一点都没想起来, 跟没学过一样 |
| 2 | 模糊 | 好像见过, 但答不上来 |
| 3 | 有点印象 | 想了一会儿才答对, 不太确定 |
| 4 | 比较顺利 | 能答对, 但稍微犹豫了一下 |
| 5 | 非常轻松 | 立刻反应过来, 毫不费力 |
-**1-2 分**: 软件会认为您还没掌握, 短期内会再次安排复习
-**3 分**: 正常掌握, 按计划间隔复习
-**4-5 分**: 掌握得很好, 下次复习间隔会拉长
我们建议您不要纠结, 凭第一感觉打分就好, 软件会根据您的评分自动调整复习节奏.
当然我们还是建议尽量避免这种方式并尽量使用其他谜题评测.
您可能认为那种方式可以让用户直接"干预"算法, 类似百词斩的"斩"功能用于跳过已经熟悉的内容, 实际上您并不需要那样做: 我们内建了"快速通过/正确应答"功能, 等同于直接选择"5".
## 我每天都要打开软件吗? 不学会怎样?
理论上不需要每天打开. 软件会自动记录每个知识点下次该复习的时间.
但建议您每天打开软件看下状态.
即使隔了几天甚至几周没学:
- 已经记住的知识点不会消失, 只是下次复习时会多复习几次
- 学习记录完好保存在 `data/` 文件夹里, 不会丢失
建议尽量按软件的提醒复习, 效果最好; 但忙的时候跳过几天也没关系.
## 能同时学多个科目吗?
可以.
每个科目或课程可以做成独立的"单元集".
## 我换电脑了, 怎么迁移数据?
1. 在旧电脑上复制整个 `data/` 文件夹到 U 盘或网盘
2. 在新电脑上安装好 HeurAMS
3. 用 U 盘里的 `data/` 文件夹覆盖新电脑上的 `data/` 文件夹
所有学习记录、配置、单元集全部迁移完毕.
## 一些术语听不懂
| 术语 | 意思 |
|------|--------|
| **单元集** | 相当于"一本书"或"一门课", 包含一系列知识点 |
| **谜题** | 测试您的题目类型 (选择题、填空题等) |
| **算法** | 决定什么时候该复习哪个知识点的"智能排课表" |
| **复习队列** | 今天需要复习的知识点列表 |
| **激活** | 第一次开始学习某个知识点 |
| **到期** | 到了该复习这个知识点的时间了 |
## 软件卡住了/没反应怎么办?
1. 建议先等片刻
2. 如果不行, 直接关闭终端窗口
3. 重新打开软件
4. 如果您有时间的话, 欢迎报告问题, 我们为此深表歉意
## 同时用 Anki 和 HeurAMS 会冲突吗?
不会.
两者是独立的软件, 数据互不影响. 您可以逐步将内容迁移到 HeurAMS, 也可以两个一起用.
## 我需要安装 Python 吗?
需要的, HeurAMS 是基于 Python 的软件.
- Windows/macOS: 从 python.org 下载安装即可
- Linux: 系统通常已自带 Python
- Android: 安装 Termux 应用, 然后在 Termux 中安装 Python (运行 `pkg in python`)
如果看到"python 不是内部或外部命令"的提示, 说明 Python 没有正确安装或添加到系统路径, 搜索"Python 安装教程"按步骤操作即可.
HeurAMS 建议的 Python 版本是 3.12.13.
## 软件安全吗? 会不会有病毒?
HeurAMS 是开源软件, 所有代码公开可查阅, 不会有病毒或后门.
它只读写自己的 `data/` 文件夹, 不会动您电脑上的其他文件.
## 软件报错, 出现一堆我看不懂的英文怎么办?
1. 把错误信息复制下来
2. 先找一下这个页面有没有收录您遇到的问题
3. 如果没有, 可以和软件日志一起上传到 issues, 我们会尽快处理
## 复习到一半可以暂停吗? 下次会从头开始吗?
暂时没有保存中间状态的功能, 但我们很快会添加.
## 怎么看我学了多少? 有统计吗?
仪表盘界面会显示统计信息.
您可以通过导航器随时回到仪表盘查看.
## 我觉得复习太快/太慢了, 能调吗?
可以. 您可以通过切换算法或调整算法参数或改变记忆单元数来改变复习节奏.
在设置界面可以找到相关设置.
## 能换界面颜色/主题吗?
能的, Textual 框架提供了多种主题.
## 我不小心删了东西, 能恢复吗?
这取决于您系统是否启用回收站, 软件本身没有自动备份功能.
## 能把软件放 U 盘随身带吗?
可以. 将整个 HeurAMS 文件夹复制到 U 盘, 在任意电脑上安装 Python 后运行即可. `data/` 目录下的学习数据也会一同携带.
## 怎么关掉语音朗读?
在设置界面中找到 TTS 相关选项, 将其关闭即可.
## 哪里可以下载别人做好的单元集?
目前项目还没有官方的单元集市场.
但随着社区发展, 未来可能会有用户分享的单元集, 您也可以和朋友互相分享.
## 我能把学习内容导出打印吗?
可以.
软件本身支持将单元集导出为单一文本文件, 您可以用任何文本编辑器打开并打印. 也可以直接复制内容到 Word 等软件.
## 我想从头重新学, 怎么重置?
删除 `data/repo/` 下对应单元集文件夹中的 `algodata.json` 文件即可重置所有学习进度.
## 如何创建自己的单元集?
`data/repo/` 目录下创建一个新文件夹, 包含以下文件即可:
```
data/repo/my_pack/
├── manifest.toml # 元信息: title, author 等
├── typedef.toml # 通用字段定义和谜题配置
├── payload.toml # 记忆条目内容
├── algodata.json # 算法状态数据 (可留空)
└── schedule.toml # 复习策略配置
```
您也可以使用我们提供的工具从 CSV 等格式转换, 或利用 AI 工具生成.
## 如何切换算法?
设置界面中有详细的说明.
## 如何从 Anki 导入?
暂时没有迁移工具, 因为两个软件的设计思路不同.
但欢迎关注 HeurStudio 项目, 它能从根本上解决内容创建与迁移问题 :)
## 为什么不用 Flutter?
Flutter 是构建跨平台图形界面的优秀框架, HeurAMS 的设计目标之一是保持核心程序库独立于特定前端.
但 Flutter 在 "集成 python" 方面不如 PyOtherSide, 只能通过 RPC 标准件和程序库通讯, 并且 Flutter 的桌面多窗口一直以来没有被官方稳定支持, 所以我们暂时放弃了 Flutter 而选择了 Kirigami.
当前我们优先开发了基于 Textual 的 TUI 前端和基于 Kirigami 的原生前端, 但这不排除未来出现 Flutter 或其他框架前端的可能性.
如果您有兴趣开发 Flutter 前端, 欢迎参考[贡献指南](CONTRIBUTING.md#%E6%96%B0%E7%9A%84%E7%94%A8%E6%88%B7%E7%95%8C%E9%9D%A2%E5%89%8D%E7%AB%AF).
## 软件需要联网吗?
核心复习功能完全离线可用. 以下功能需要联网:
- 文本转语音 (TTS) 的 Edge TTS 提供者
- LLM 提供者 (如 OpenAI 兼容 API)
- 从远程仓库下载单元集
## 许可证中的"本机 API 调用豁免"是什么?
简言之, 如果您在自己的程序中通过本地进程间 API 方式的通信 (如同一主机上的 RPC 调用) 使用 HeurAMS, 而无需通过网络转发, 则您的程序不受 AGPL-3.0 许可证的约束.
这项附加条款旨在鼓励第三方前端和工具的开发.
所以 HeurAMS 的许可证实质上是比原始的 AGPL-3.0 松一点的.
## HeurAMS 和百词斩有什么区别?
大体地说:
| 方面 | HeurAMS | 百词斩 |
|------|---------|--------|
| 使用场景 | 电脑/终端 | 手机 App |
| 学习内容 | 任何知识, 不限语言和科目 | 英语单词 |
| 记忆策略 | 多算法可选, 可自定义复习流程 | 固定算法, 不可调 |
| 测验方式 | 选择题/填空题/识别题等多种谜题 | 看图选词/听音选义等多种谜题 |
| 内容创建 | 自己创建或导入, 完全自由 | 仅官方提供词书 |
| 费用 | 完全免费, 无内购 | 免费记忆功能 + 付费课程 |
| 数据所有权 | 数据在您自己手上, 文本文件 | 数据不可被提取 |
| 离线使用 | 核心功能完全离线 | 部分功能需联网 |
| 学习统计 | 基础统计 | 打卡/排行榜/社交 |
## 百词斩有图片联想记忆, HeurAMS 也有吗?
支持.
如果您的终端支持图片显示 (如 Konsole 或者 WezTerm), 单元集中可以包含图片, 复习时会直接展示.
但图片需要您自己放入单元集.
## 百词斩有打卡和排行榜, HeurAMS 有吗?
目前没有.
HeurAMS 不设打卡、排行榜或社交功能, 也不向任何人收集您的学习数据.
## 百词斩有现成的词书, HeurAMS 去哪找内容?
百词斩的课程是官方制作好的, HeurAMS 的内容需要您自己创建或从社区获取.
详见"如何创建自己的单元集?".
## 百词斩在手机上用很方便, HeurAMS 能在手机用吗?
可以, 但现阶段需要您"折腾"一下.
Android 手机安装 Termux 后可运行 HeurAMS 的基本用户界面.
此外, 正在开发的 KiriMemo 前端将原生支持 Android 和 iOS, 这就不需要用户去折腾了.
## 百词斩能背单词, HeurAMS 还能学什么?
任何需要记忆的知识都可以: 外语单词、医学名词、法律条文、历史年代、化学方程式、编程语法、乐谱符号...
单元集的内容完全由您自己定义.
## 百词斩学英语效果很好, 换成 HeurAMS 会不会效果差?
考虑到百词斩的算法和词库是事实上闭源的, 我们无从得知算法来源.
但 HeurAMS 的架构设计可保证单元集制成后效果不比百词斩差, 甚至优于百词斩.
HeurAMS 的间隔重复算法基于相同的认知科学原理, 且算法透明可调, 您可以自由选择最适合自己的调度策略.
## 如何参与项目?
详见[贡献指南](CONTRIBUTING.md).
即使不是开发者, 您也可以通过编写文档、制作记忆单元集、翻译界面、答疑等方式参与.
-84
View File
@@ -1,84 +0,0 @@
## 特性
### 间隔重复调度器
> 许多出版物都广泛讨论了不同重复间隔对学习效果的影响. 特别是, 间隔效应被认为是一种普遍现象. 间隔效应是指, 如果重复的间隔是分散/稀疏的, 而不是集中重复, 那么学习任务的表现会更好. 因此, 有观点提出, 学习中使用的最佳重复间隔是**最长的, 但不会导致遗忘的间隔**.
- 软件开箱即用, 无需多加配置即可使用默认的 `SM-2` 算法进行学习
- 算法模块是 "潜进" 内核 (heurams.kernel) 中的一等公民, 内核天然支持插拔各型算法
- 无需安装繁杂的插件即可分单元集完成算法快速切换与调优, 研究者可以方便地修改算法模块以便捷地进行研究与测试
- 默认使用 `SM-2` 简单间隔重复算法, 此算法亦用作 `Anki` 闪卡记忆软件的默认闪卡调度器
- 还内置了 `NSP-0` 筛选用非间隔重复算法以便快速筛选记忆内容, `FSRS` 先进间隔重复算法作为效率更高的调度器, 与 `SM-15M (移植自 sm.js 项目)` 复杂间隔重复算法(逆向工程)
- 算法模块可以标记记忆项目, 也可以动态规划每个记忆单元的记忆间隔时间表, 动态跟踪记忆反馈数据, 以优化长期记忆保留率与稳定性
- 得益于项目的模块化架构与单元集结构设计, 同一个单元集可以与任意种算法共存并互通, 这对研究者及想探索/实验高效率方法的用户极其友好
### 多模态学习进程
与 Anki 的 SQLite `.apkg` 包不同, 我们坚持使用人类可读的文件夹组织单元集, 这带来了若干好处, 包括:
- 人类可读: 您可以用任意工具, 乃至一个记事本自由修改记忆载荷数据而无需打开软件
- 元数据配置: 配置自由度极高, 可以任意组合, 重造, 乃至创造新内容
- 测验, 算法与知识互相隔离: 一条知识不再是单一的闪卡, 不仅可以用若干不同的算法规划, 还可以用多种并行的谜题类型测验, 极大地提升学习效果和丰富度. 作为学习者, 您无需担忧概念复杂--仅需从云端下载单元集即可开箱即用上述特性!
- 多模态学习
- 软件自身集成了文本转语音 (TTS) , 音频与语言模型 (LLM) 模块, 这些功能乃至功能本身都是可插拔, 可扩展, 可切换驱动的, 这为内容创建了极大的丰富度
- 软件内置多种谜题类型, 包括选择题 (MCQ), 填空题 (Cloze) 与识别题 (Recognition), 您可在同一单元应用多种, 或是选择性启用
- 软件天然支持动态内容生成, 支持宏驱动的模板系统, 根据上下文乃至语言模型动态生成知识点的解析
- 在间隔重复研究尚被 SuperMemo 系列独占的时代, Wozniak 就早已表示 "如果不能理解知识, 就无需记忆它". 今天, 我们依然相信理解是记忆的基石
- 云同步与分享优化:
- 由于记忆数据和单元集文件都是文本文件, 故可进行快速的增量同步而无需完整地上传所有文件, 并且设计天然支持版本控制
- 如果您想分享单文件, 软件也支持导出为压缩包或合并成单文本文件以通过纯文本文件形式在 pastebin 等平台分享
- 性能提升: 得益于现代且支持分块的文件组织结构, 潜进能在保持高自由度的同时仅使用 python 就能达到敏捷且低占用的用户体验
- AI 辅助友好: 想象您有一些 `.apkg` 牌组或一大段教材内容, 您可以方便且高效率地使用 AI 工具以创建可在 HeurAMS 使用的单元集
### 内置实用用户界面
尽管不是唯一前端, 但响应式 Textual 框架构建的内置终端用户界面在多种场景下仍具有独特优势:
- 跨平台, 并支持触屏/鼠标/键盘多操作模式
- 与几乎所有现代终端模拟器相容
- 对于<a href="https://www.arewesixelyet.com/" target="_blank" rel="noopener noreferrer">支持 sixel 协议的终端模拟器</a>, 可高清显示图像内容
- 对于不支持 sixel 协议的终端模拟器, 也支持图片低清的兼容显示模式
- 可通过 textual-web 作为服务部署, 并在任意浏览器使用
- 简洁直观, 键盘友好, 全功能且高效率的用户界面设计
- 易于嵌入: 可在 getty/kmscon 中运行而无需任何桌面图形服务
- 资源占用小, 运行流畅, 不拖泥带水
- 便于测试与调试程序库
查看[屏幕截图](SCREENSHOTS.md).
## 包依赖组说明
由于部分依赖只被少数功能需要, 所以我们把可选依赖分得比较细, 前面提供的命令会安装部分可选依赖, 以下是依赖组列表:
| 依赖组 | 包含模块 | 说明 |
|--------|----------|------|
| 构建系统 | hatchling | 构建时安装 |
| 最小化安装 | tabulate, toml, transitions, click | 核心驱动程序库, 始终必需 |
| interface | textual | 基本用户界面依赖 |
| algo-fsrs | fsrs | FSRS 算法模块 |
| tts-edgetts | edge-tts | 微软文本转语音 |
| llm | llms-py | API 调用 |
| audio-playsound | playsound3 | 通用音频模块 |
| dev | zmq, pytest, pytest-cov | 开发调试与测试工具 |
| basic | [tts-edgetts], [llm], [algo-fsrs] | 适用于用户体验的较轻依赖组(推荐) |
| all | 以上所有依赖 | 完整安装组 |
## 关于此仓库
此仓库为 "潜进" 的核心程序库在 python 语言下的实现\
包含数据模型与框架, 并内置了基于 textual 框架的前端实现 (interface 子模块)\
除了通过内置前端进行学习外, 开发者也能在 python 环境中导入 `heurams` 库或使用 `RPC``heurams` 程序库实例通讯, 使用框架构建其他辅助记忆功能前端或其他应用程序
潜进项目的所有仓库如下:
| 项目名称 | 状态 | 说明 | 包名 | 技术栈 | 目标平台 |
| :--- | :--- | :--- | :--- | :--- | :--- |
| HeurAMS | 开发中<br/>原型可用 | 提供通用核心程序库与基本用户界面 | `heurams` | Python | 标准 Python 环境 |
| KiriMemo | 开发中<br/>原型可用 | 基于 KDE 技术的现代跨平台前端 | `org.kde.kirimemo` | C++, Qt6, Kirigami, PyOtherSide | 桌面与移动设备 |
| ArkMemo | 开发中 | 基于 ArkUI 的现代跨平台前端 | `top.pluv27.arkmemo` | ArkTS, ArkUI | 移动设备 |
| HeurStudio | 计划中 | AI 辅助的单体单元集高级创建与编辑工具 | `top.pluv27.heurstudio` | C++, Qt6, Kirigami, PyOtherSide | 桌面 |
| HeurSync | 开发中 | 用户数据同步服务器<br/>集成 Web 前端与排行榜 | `heursync` | Go, SQL | 网页与服务器 |
| HeurRepo | 开发中 | 单元集文档源服务器<br/>与单元集分享平台 | `heurrepo` | Go, SQL | 网页与服务器 |
尽管现在后三样有点画大饼的意思, 但是我们的路线是明了的
+621 -205
View File
@@ -1,245 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and modification follow.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
1. Source Code.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
HeurAMS
Copyright (C) 2025 Wang Zhiyu (pluvium27)
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
---
Additional Permission under AGPL Section 7
Local API exemption: When the program is accessed solely via API (including RPC, REST API, GraphQL, or any machine-to-machine interface) from a caller on the same host machine, the source disclosure requirement of AGPL Section 13 is waived.
Any API call from a different machine (including LAN, private network, or the internet) remains fully subject to AGPL Section 13.
This exemption does NOT apply to human-facing web interfaces.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+130 -114
View File
@@ -1,142 +1,158 @@
# 潜进 (HeurAMS) - 启发式辅助记忆调度器
# 潜进 (HeurAMS) - 启发式辅助记忆程序
## 概述
"潜进" (HeurAMS: Heuristic Auxiliary Memorizing Scheduler, 启发式记忆辅助调度器) 是一种基于启发式算法与认知科学理论的辅助记忆调度器, 旨在帮助用户更高效地进行记忆工作与学习规划,
也是一种开放, 优雅, 易于扩展的间隔重复调度器实验平台, 旨在帮助研究者更高效地进行前沿记忆算法的调查实验与研究.
"潜进" (HeurAMS: Heuristic Auxiliary Memorizing Scheduler, 启发式记忆辅助调度器) 是为习题册, 古诗词, 及其他问答/记忆/理解型知识设计的开放源代码多用途辅助记忆软件, 提供动态规划的优化记忆方案
[详细介绍](INTRODUCTION.md) [屏幕截图](SCREENSHOTS.md)
## 关于此仓库
<p align="left">
<a href="https://github.com/pluvium27/HeurAMS" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/GitHub-fafafa?style=for-the-badge&logo=github&logoColor=181717" alt="GitHub" /></a><a href="https://invent.kde.org/pluv/HeurAMS" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/KDE_Invent-1D99F3?style=for-the-badge&logo=kde&logoColor=white" alt="KDE Invent" /></a><a href="https://gitee.com/pluv/HeurAMS" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/Gitee-C71D23?style=for-the-badge&logo=gitee&logoColor=white" alt="Gitee" /></a><a href="https://git.pluv27.top/pluv/HeurAMS" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/git.pluv27.top-609926?style=for-the-badge&logo=gitea&logoColor=white" alt="git.pluv27.top" /></a>
</p>
本仓库为 "潜进" 软件组项目的核心部分, 包含核心功能模块以及基于 Textual 框架的基础用户界面(heurams.interface)实现\
除了通过用户界面进行学习外, 你也可以在 Python 中导入 `heurams` 库, 使用其中实现的状态机, 算法迭代器和数据模型构建辅助记忆功能
## 快速开始
## 特性
### 安装软件
### 间隔迭代算法
#### 从包管理器安装
> 许多出版物都广泛讨论了不同重复间隔对学习效果的影响. 特别是, 间隔效应被认为是一种普遍现象. 间隔效应是指, 如果重复的间隔是分散/稀疏的, 而不是集中重复, 那么学习任务的表现会更好. 因此, 有观点提出, 学习中使用的最佳重复间隔是**最长的, 但不会导致遗忘的间隔**.
潜进 (包名是 `heurams`) 处于早期开发考虑, 尚未上架 PyPI.
但可以用 pip 从仓库安装稳定版和开发版本, 这要求设备上安装了 python 环境 (建议 3.12.13 及之后版本).
- 采用经实证的 SM-2 间隔迭代算法, 此算法亦用作 Anki 闪卡记忆软件的默认闪卡调度器
- 动态规划每个记忆单元的记忆间隔时间表
- 动态跟踪记忆反馈数据, 优化长期记忆保留率与稳定性
从稳定的 `master` 分支安装, 并安装适用于用户体验的可选依赖(推荐):
### 学习进程优化
```
pip install --upgrade 'heurams[basic] @ https://git.pluv27.top/pluv/HeurAMS/archive/master.zip'
- 元数据配置: 支持配置详细附加数据
- 自然语音: 集成文本转语音 (TTS) 功能, 支持"电台"回顾功能
- 多种谜题类型: 选择题 (MCQ), 填空题 (Cloze), 识别题 (Recognition)
- 动态内容生成: 支持宏驱动的模板系统, 根据上下文动态生成题目
- 云同步支持: 通过多种协议同步数据到远程服务器
### 实用用户界面
- 响应式 Textual 框架构建的跨平台 TUI 界面
- 支持触屏/鼠标/键盘多操作模式
- 简洁直观的复习流程设计
## 安装
### 从源码安装
1. 克隆仓库:
```bash
git clone https://gitea.imwangzhiyu.xyz/ajax/HeurAMS
cd HeurAMS
```
1. 安装依赖:
```bash
pip install -r requirements.txt
```
1. 以开发模式安装包:
```bash
pip install -e .
```
### 从包管理器安装
暂时还没有:(
## 启动应用
```bash
# 在任一目录(建议是空目录或者包根目录, 将被用作存放数据)下运行
python -m heurams.interface
```
从较前沿, 大致稳定的 `dev` 分支安装, 并安装适用于用户体验的可选依赖(如果您追求较前沿的改进):
配置文件位于 `./data/config/config.toml`(相对于工作目录).\
如果不存在, 会使用内置的默认配置.
```
pip install --force-reinstall --no-deps 'heurams[basic] @ https://git.pluv27.top/pluv/HeurAMS/archive/dev.zip'
## 项目结构
### 架构图(待更新 0.5.0)
以下 Mermaid 图展示了 HeurAMS 的主要组件及其关系:
```mermaid
graph TB
subgraph "用户界面层 (TUI)"
TUI[Textual TUI]
Widgets[界面组件]
Screens[应用屏幕]
end
subgraph "服务层"
Config[配置管理]
Logger[日志系统]
Timer[时间服务]
AudioService[音频服务]
TTSService[TTS服务]
SyncService[同步服务]
OtherServices[其他服务]
end
subgraph "内核层"
Algorithms[算法模块]
Particles[数据模型]
Puzzles[谜题模块]
Reactor[调度反应器]
end
subgraph "提供者层"
AudioProvider[音频提供者]
TTSProvider[TTS提供者]
OtherProviders[其他提供者]
end
subgraph "数据层"
Files[本地文件数据]
end
subgraph "上下文管理"
Context[ConfigContext]
CtxVar[config_var]
end
TUI --> Config
TUI --> Logger
TUI --> AudioService
TUI --> TTSService
TUI --> OtherServices
Config --> Files
Config --> Context
AudioService --> AudioProvider
TTSService --> TTSProvider
OtherServices --> OtherProviders
Reactor --> Algorithms
Reactor --> Particles
Reactor --> Puzzles
Particles --> Files
Algorithms --> Files
```
安装适用于一般计算机的通用音频模块 (基于 playsound3):\
(此项不适用于 termux 环境, termux 的音频支持是内建的)
```
pip install --upgrade 'heurams[audio-playsound] @ https://git.pluv27.top/pluv/HeurAMS/archive/master.zip'
```
> 您也可以从 `refactor/...` 等特定分支安装以测试某项更改
[依赖分组说明](INTRODUCTION.md#包依赖组说明)
#### 从源码安装
我们提供原生 python 和 uv 两种源码安装方式.\
详见[贡献指南 - 设置开发环境](CONTRIBUTING.md#设置开发环境).
### 使用软件
在终端中运行 `heurams`, 您会看到一系列帮助信息, 例如:
```plain
~ $ heurams
Usage: heurams [OPTIONS] COMMAND [ARGS]...
HeurAMS 0.5.1 - 启发式辅助记忆调度器
Options:
-v, --version Show the version and exit.
-h, --help Show this message and exit.
Commands:
help 显示此帮助信息
tui 启动内置基本用户界面 (TUI)
version 输出版本信息
```
可以通过键入 `heurams tui` 启动基本用户界面, 例如:
```plain
~ $ heurams tui
欢迎使用基本用户界面!
加载配置与上下文... 已完成! (耗时: 33ms)
加载用户界面框架... 已完成! (耗时: 169ms)
加载用户界面布局... 已完成! (耗时: 165ms)
组件目录: <软件包所在目录>
工作目录: <运行目录, 将在此目录下建立 ./data 文件夹>
前置工作共计耗时: 142ms
(此时您的终端将转为呈现美观的 TUI 基本用户界面)
```
通过键入 `heurams -v` 查看版本:
```
~ $ heurams -v
HeurAMS 0.5.1 stable (fulcrum/支点), Linux
```
## 常见问题 (FAQ)
详见[常见问题](FAQ.md).
## 项目架构
详见[架构说明](ARCHITECTURE.md).
## 参与项目
欢迎参与到项目协作中!\
详见[贡献指南](CONTRIBUTING.md).\
关于 AI 辅助开发的说明, 请参阅 [AGENTS.md](AGENTS.md).
## 项目标识
HeurAMS 项目标识如下, 文件(位图和矢量图)位于 `./src/heurams/assets/art/` 目录.
<img src="src/heurams/assets/art/banner128-light.png" height="96px" title="位图横幅(不透明)">
<div style="display: flex; flex-wrap: wrap; gap: 5px;">
<img src="src/heurams/assets/art/logo.svg" height="96px" title="矢量图标">
<img src="src/heurams/assets/art/logo-mono-light.svg" height="96px" title="单色明亮矢量图标">
<img src="src/heurams/assets/art/logo-mono-dark.svg" height="96px" title="单色暗色矢量图标">
</div>
颜色分别是: `#1660A5 (海蓝色)` `#545F70 (蓝灰色)` `#FFFFFF (单色明亮图标白色)` `#1A1A1A (单色暗色图标深黑色)` `#2f2f35 (文字颜色)`.
## 贡献
欢迎贡献! 请参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 了解贡献指南.
## 许可证
### 项目本身
本项目基于 AGPL-3.0 许可证开放源代码, 并有一个豁免本机 API 调用的附加条款, 较标准 AGPL-3.0 更宽松.
详见根目录下 [LICENSE](LICENSE) 文件.
本项目基于 AGPL-3.0 许可证开源. 详见根目录下 [LICENSE](LICENSE) 文件.
### 第三方代码
项目在 `src/heurams/vendor/` 目录下嵌入或在其他位置直接使用了以下第三方代码或其衍生作品 (可能有修改):
项目在 `src/heurams/vendor/` 目录下嵌入了以下第三方代码(可能有修改):
#### SM.js
#### py-fsrs
- 上游版本: commit `6e3bb4a` (2015年2月4日上游已停止维护)
- 引用方式: 将 coffeescript 重写为 python 并间接引用, 数学原理一致; 并对重写后代码进行逻辑, 性能与标准化 API 改进
- 位置: `src/heurams/kernel/algorithms/sm15m.py`
- 原项目: [SM.js](https://github.com/slaypni/SM-15)
- 原版权: Copyright (c) 2014 Kazuaki Tanida
- 原许可证: MIT License
- 上游版本: 6.3.1
- 位置: `src/heurams/vendor/pyfsrs/`
- 原项目: [py-fsrs](https://github.com/open-spaced-repetition/py-fsrs)
- 原许可证: Copyright (c) 2026 Open Spaced Repetition Contributors
- 原许可证: MIT License, 详见 `src/heurams/vendor/pyfsrs/LICENSE`
本项目受益于他们无私且优秀的工作.
本项目受益于他们无私且优秀的工作
-73
View File
@@ -1,73 +0,0 @@
# 用户界面屏幕截图
潜进 (HeurAMS) 项目目前有两个前端实现, 此文档用于呈现它们的截图 (尽量与最新版本同步):
- Textual 基本用户界面 (heurams.interface): 基于 Python Textual 框架构建的程序库内置跨平台 TUI 界面, 支持触屏、鼠标、键盘多操作模式, 是当前开箱即用的默认前端.
- KiriMemo (org.kde.kirimemo): 基于 KDE Kirigami 框架的现代跨平台前端, 使用 C++ 和 QML 构建, 通过 `PyOtherSide` 直接复用 Python 内核, 为多种平台提供原生体验 (尚未稳定).
<!--- ArkMemo (top.pluv27.arkmemo): 基于 ArkUI 的现代移动设备前端, 使用 ArkTS 构建, 通过 API 调用 Python 内核, 为 Android, HarmonyOS, iOS 平台提供原生体验 (尚未稳定)-->
欢迎为现有前端贡献代码, 或开发您自己的前端.\
详见[贡献指南](CONTRIBUTING.md#%E6%96%B0%E7%9A%84%E7%94%A8%E6%88%B7%E7%95%8C%E9%9D%A2%E5%89%8D%E7%AB%AF).
## 基本用户界面前端的截图
> 截图所使用的终端模拟器为 KDE Konsole\
> 字体为 Cascadia Code 和 Noto Sans SC\
> 终端尺寸设置为 80x25 (软件也支持更大的终端尺寸)
### 仪表盘与导航器
仪表盘包含学习面板的总体视图, 包括不同功能区域的操作入口, 统计信息, 以及单元集概览.\
导航器是一个实用的模态窗口, 能带您在多种功能间自如切换, 按 `n` 键或单击下方按钮可在任意界面迅速打开/关闭导航器.
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<img src="screenshots/dashboard_1.png" width="48%">
<img src="screenshots/dashboard_2.png" width="48%">
<img src="screenshots/navigator_1.png" width="48%">
</div>
### 准备界面与预缓存工具
学习准备界面展示了单元集基本信息和每个单元的学习状态, 并提供了学习和预缓存的入口.\
预缓存工具使您能提前预缓存文本转语音资源以确保复习流程的顺畅体验和离线复习能力, 但即使您不预先缓存, 资源也会在复习播放时被自动加载.
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<img src="screenshots/preparation.png" width="48%">
<img src="screenshots/precache_1.png" width="48%">
</div>
### 记忆队列界面
队列式学习记忆的主要界面.\
同一知识点可产生多种谜题类型的评估方式, 软件内置完形填空与识别题等多种测试类型, 您可在复习流程中按顺序完成不同测试.
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<img src="screenshots/memoqueue_cloze_1.png" width="48%">
<img src="screenshots/memoqueue_recognition_1.png" width="48%">
<img src="screenshots/memoqueue_recognition_2.png" width="48%">
</div>
### 设置界面
配置界面包含算法选择、音频与多种服务的提供者切换、以及界面与算法设置等选项.
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<img src="screenshots/setting_1.png" width="48%">
<img src="screenshots/setting_2.png" width="48%">
</div>
### 其他界面
收藏管理器可管理您手动标记的个人收藏集.\
关于页面提供了程序版本号、许可协议等信息.
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<img src="screenshots/about_1.png" width="48%">
<img src="screenshots/favmanager_1.png" width="48%">
</div>
## KiriMemo 前端的截图
截图将在 KiriMemo 前端开发趋于稳定后补充.
<!-- TODO: 补充截图 -->
+6
View File
@@ -0,0 +1,6 @@
_services_desc = '服务模块(services)设置'
_providers_desc = '驱动模块(providers)设置'
_repo_desc = '单元集独立设置'
_interface_desc = '基本用户界面设置'
_default_desc = '默认设置'
_global_desc = '底层设置'
@@ -1,8 +1,8 @@
zmq_debug = false
_zmq_debug_desc = "[调试] ZeroMQ 调试服务器, 这会在 zmq_debug_port 上打开一个服务器\n调试工具可远程在 HeurAMS 内执行任意 python 代码, 无必要请关闭"
zmq_debug = true
_zmq_debug_desc = "[调试] ZMQ 调试服务器, 这会在 zmq_debug_port 上打开一个服务器\n调试工具可远程在 HeurAMS 内执行任意 python 代码, 无必要请关闭"
zmq_debug_port = 5555
_zmq_debug_port_desc = "[调试] ZeroMQ 调试服务器端口"
enable_built_in_interface = true
_zmq_debug_port_desc = "[调试] ZMQ 调试服务器端口"
enable_built_in_interface = false
_enable_built_in_interface_desc = "启用内置基本用户界面\n(当且仅当 HeurAMS 作为程序库时禁用, 以跳过用户界面逻辑)"
_paths_desc = "用户数据路径定义"
@@ -15,7 +15,3 @@ config = "./data/config"
_config_desc = "配置文件根目录"
repo = "./data/repo"
_repo_desc = "记忆单元集根目录"
misc = "./data/misc"
_misc_desc = "扩展程序和 whisper 等模块的数据存储根目录"
_addons = "./data/addons"
__addons_desc = "扩展程序根目录"
@@ -1,4 +1,4 @@
_global_desc = "用户界面通用设置"
_widgets_desc = "组件设置"
_screens_desc = "界面设置"
_widgets_desc = "组件设置"
_screens_desc = "界面设置"
_puzzles_desc = "谜题生成器设置"
+17
View File
@@ -0,0 +1,17 @@
persist_to_file = true
_persist_to_file_desc = "[调试] 将记忆更改保存到文件"
quick_pass = true
_quick_pass_desc = "[调试] 启用快速应答功能(跳过测验)"
auto_pass = false
_auto_pass_desc = "[调试] 自动通过测试模式"
scheduled_num = 420
_scheduled_num_desc = "默认记忆单元数量(可被单元集设置覆盖)"
algorithm = "NSP-0"
_algorithm_desc = "默认记忆调度算法(可被单元集设置覆盖)"
[_algorithm_candidate]
NSP-0 = "筛选用非间隔重复调度器"
none = "不设置默认调度器"
SM-2 = "第二代 SuperMemo 简单间隔重复调度器"
SM-15M = "第15代 SuperMemo 复杂间隔重复调度器 (不稳定且逆向工程)"
FSRS = "先进开放间隔重复调度器"
@@ -1,2 +1,2 @@
min_denominator = " 1"
min_denominator = "3"
_min_denominator_desc = "设空比例系数的倒数"
+2
View File
@@ -0,0 +1,2 @@
_cngk-t_desc = "高考必备古诗文"
_cngk_desc = "高考必备古诗文"
+11
View File
@@ -0,0 +1,11 @@
algorithm = "NSP-0"
_algorithm_desc = "记忆调度算法"
scheduled_num = 420
_scheduled_num_desc = "单次记忆单元数量"
[_algorithm_candidate]
NSP-0 = "筛选用非间隔重复调度器"
none = "不设置默认调度器"
SM-2 = "第二代 SuperMemo 简单间隔重复调度器"
SM-15M = "第15代 SuperMemo 复杂间隔重复调度器 (不稳定且逆向工程)"
FSRS = "先进开放间隔重复调度器"
+11
View File
@@ -0,0 +1,11 @@
algorithm = "SM-2"
_algorithm_desc = "记忆调度算法"
scheduled_num = 20
_scheduled_num_desc = "单次记忆单元数量"
[_algorithm_candidate]
NSP-0 = "筛选用非间隔重复调度器"
none = "不设置默认调度器"
SM-2 = "第二代 SuperMemo 简单间隔重复调度器"
SM-15M = "第15代 SuperMemo 复杂间隔重复调度器 (不稳定且逆向工程)"
FSRS = "先进开放间隔重复调度器"
@@ -2,7 +2,7 @@ provider = "playsound"
_provider_desc = "音频驱动类型"
[_provider_candidate]
playsound = "Python 桌面跨平台音频系统, 使用了 playsound3 替代了老旧的 playsound"
playsound = "python 跨平台音频系统"
termux = "Android Termux 音频系统"
mpg123 = "通用音频系统, 依赖系统 mpg123"
pulseaudio = "高级音频路由系统"
@@ -1,4 +1,4 @@
provider = "none"
provider = "openai"
_provider_desc = "模型接口类型"
[_provider_candidate]
@@ -1,4 +1,4 @@
provider = "none"
provider = "webdav"
_provider_desc = "同步服务驱动类型"
[_provider_candidate]
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
title = "高考必背古诗文-0"
package = "cngk-0"
author = "__heurams__"
desc = "高考古诗文 60 篇"
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
schedule = ["quick_review", "recognition", "final_review"]
[phases]
quick_review = [["FillBlank", "1.0"], ["Recognition", "1.0"]]
recognition = [["FillBlank", "1.0"]]
final_review = [["FillBlank", "1.0"], ["Recognition", "1.0"]]
[annotation]
"quick_review" = "复习旧知"
"recognition" = "新知识"
"final_review" = "总复习"
+17
View File
@@ -0,0 +1,17 @@
[annotation]
note = "笔记"
keyword_note = "关键词翻译"
translation = "语句翻译"
delimiter = "分隔符"
content = "内容"
tts_text = "文本转语音文本"
[common]
delimiter = "/"
tts_text = "eval:payload['content'].replace('/', '')"
[common.puzzles] # 谜题定义
# 我们称 "Recognition" 为 recognition 谜题的 alia
"Recognition" = { __origin__ = "recognition", __hint__ = "", primary = "eval:payload['content']", secondary = ["eval:payload['keyword_note']", "eval:payload['note']"], top_dim = ["eval:payload['translation']"] }
"SelectMeaning" = { __origin__ = "mcq", __hint__ = "eval:payload['content']", primary = "eval:payload['content']", mapping = "eval:payload['keyword_note']", jammer = "eval:list(payload['keyword_note'].values())", max_riddles_num = "eval:default['mcq']['max_riddles_num']", prefix = "选择正确项: " }
"FillBlank" = { __origin__ = "cloze", __hint__ = "", text = "eval:payload['content']", delimiter = "eval:nucleon['delimiter']", min_denominator = "eval:default['cloze']['min_denominator']"}
+14
View File
@@ -0,0 +1,14 @@
# encoding=utf-8
import jieba
# jieba.enable_paddle()# 启动paddle模式。 0.40版之后开始支持,早期版本不支持
strs = ["我来到北京清华大学", "乒乓球拍卖完了", "中国科学技术大学"]
# for str in strs:
# seg_list = jieba.cut(str,use_paddle=True) # 使用paddle模式
# print("Paddle Mode: " + '/'.join(list(seg_list)))
seg_list = jieba.cut("秦孝公据崤函之固, 拥雍州之地", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 精确模式
seg_list = jieba.cut("他来到了网易杭研大厦") # 默认是精确模式
print(", ".join(seg_list))
+764
View File
@@ -0,0 +1,764 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "51b89355",
"metadata": {},
"source": [
"# 演练场\n",
"此笔记本将带你了解 repomgr 与 particles 对象相关操作 \n",
"此笔记本内含的系统命令默认仅存在于 Linux 操作系统, 如果你使用 Windows, 请在安装 busybox 或 cygwin 或 WSL 的环境下执行此笔记本"
]
},
{
"cell_type": "markdown",
"id": "f5c49014",
"metadata": {},
"source": [
"# 从一个例子开始\n",
"## 了解文件结构\n",
"了解一下文件结构"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "a5ed9864",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[01;34m.\u001b[0m\n",
"├── \u001b[01;34mdata\u001b[0m\n",
"│   └── \u001b[01;34mconfig\u001b[0m\n",
"│   └── \u001b[00mconfig.toml\u001b[0m\n",
"├── \u001b[00mjiebatest.py\u001b[0m\n",
"├── \u001b[00mrepo.ipynb\u001b[0m\n",
"├── \u001b[00msimplemem.py\u001b[0m\n",
"└── \u001b[01;34mtest_repo\u001b[0m\n",
" ├── \u001b[00malgodata.json\u001b[0m\n",
" ├── \u001b[00mmanifest.toml\u001b[0m\n",
" ├── \u001b[00mpayload.toml\u001b[0m\n",
" ├── \u001b[00mschedule.toml\u001b[0m\n",
" └── \u001b[00mtypedef.toml\u001b[0m\n",
"\n",
"4 directories, 9 files\n"
]
}
],
"source": [
"!tree # 了解文件结构"
]
},
{
"cell_type": "markdown",
"id": "4e10922b",
"metadata": {},
"source": [
"如果你先前运行了单元格, 请运行下面一格清理."
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "9777730e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"zsh:1: no matches found: heurams.log*\n"
]
}
],
"source": [
"!rm -rf test_new_repo\n",
"!rm -rf heurams.log*"
]
},
{
"cell_type": "markdown",
"id": "058c098f",
"metadata": {},
"source": [
"## 导入模块\n",
"导入所需模块, 你会看到欢迎信息, 标示了库所使用的配置. \n",
"HeurAMS 在基础设施也使用配置文件实现隐式的依赖注入. "
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "bf1b00c8",
"metadata": {},
"outputs": [],
"source": [
"import heurams.kernel.repolib as repolib # 这是 RepoLib 子模块, 用于管理和结构化 repo(中文含义: 仓库) 数据结构与本地文件间的联系\n",
"import heurams.kernel.particles as pt # 这是 Particles(中文含义: 粒子) 子模块, 用于运行时的记忆管理操作\n",
"from pathlib import (\n",
" Path,\n",
") # 这是 Python 的 Pathlib 模块, 用于表示文件路径, 在整个项目中, 都使用此模块表示路径"
]
},
{
"cell_type": "markdown",
"id": "ea1f68bb",
"metadata": {},
"source": [
"## 运行时检查\n",
"如你所见, repo 在文件系统内存储为一个文件夹. \n",
"因此在载入之前, 首先要检查这是否是一个合乎标准的 repo 文件夹. "
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "897b62d7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"这是一个 合规 的 repo!\n"
]
}
],
"source": [
"is_vaild = repolib.Repo.check_repodir(Path(\"./test_repo\"))\n",
"print(f\"这是一个 {'合规' if is_vaild else '不合规'} 的 repo!\")"
]
},
{
"cell_type": "markdown",
"id": "24a19991",
"metadata": {},
"source": [
"## 加载仓库\n",
"接下来, 正式加载 repo."
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "708ae7e4",
"metadata": {},
"outputs": [],
"source": [
"test_repo = repolib.Repo.create_from_repodir(Path(\"./test_repo\"))"
]
},
{
"cell_type": "markdown",
"id": "474f8eb7",
"metadata": {},
"source": [
"## 导出为字典\n",
"作为一个数据容器, repo 相应地建立了导入和导出的功能. \n",
"我们刚刚从本地文件夹导入了一个 repo. \n",
"现在试试导出为一个字典."
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "a11115fb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'algodata': [('秦孝公据崤函之固, 拥雍州之地,', {}), ('君臣固守以窥周室,', {})],\n",
" 'manifest': {'author': '__heurams__',\n",
" 'desc': '高考古诗文: 过秦论',\n",
" 'title': '测试单元: 过秦论'},\n",
" 'payload': [('秦孝公据崤函之固, 拥雍州之地,',\n",
" {'content': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/',\n",
" 'keyword_note': {'崤函': '崤山和函谷关', '据': '占据', '雍州': '古代九州之一'},\n",
" 'note': [],\n",
" 'translation': '秦孝公占据着崤山和函谷关的险固地势,拥有雍州的土地,'}),\n",
" ('君臣固守以窥周室,',\n",
" {'content': '君臣/固守/以窥/周室,/',\n",
" 'keyword_note': {'窥': '窥视'},\n",
" 'note': [],\n",
" 'translation': '君臣牢固地守卫着,借以窥视周王室的权力,'})],\n",
" 'schedule': {'phases': {'final_review': [['FillBlank', '0.7'],\n",
" ['SelectMeaning', '0.7'],\n",
" ['Recognition', '1.0']],\n",
" 'quick_review': [['FillBlank', '1.0'],\n",
" ['SelectMeaning', '0.5'],\n",
" ['Recognition', '1.0']],\n",
" 'recognition': [['Recognition', '1.0']]},\n",
" 'schedule': ['quick_review', 'recognition', 'final_review']},\n",
" 'source': PosixPath('test_repo'),\n",
" 'typedef': {'annotation': {'content': '内容',\n",
" 'delimiter': '分隔符',\n",
" 'keyword_note': '关键词翻译',\n",
" 'note': '笔记',\n",
" 'translation': '语句翻译',\n",
" 'tts_text': '文本转语音文本'},\n",
" 'common': {'delimiter': '/',\n",
" 'puzzles': {'FillBlank': {'__hint__': '',\n",
" '__origin__': 'cloze',\n",
" 'delimiter': \"eval:nucleon['delimiter']\",\n",
" 'min_denominator': \"eval:default['cloze']['min_denominator']\",\n",
" 'text': \"eval:payload['content']\"},\n",
" 'Recognition': {'__hint__': '',\n",
" '__origin__': 'recognition',\n",
" 'primary': \"eval:payload['content']\",\n",
" 'secondary': [\"eval:payload['keyword_note']\",\n",
" \"eval:payload['note']\"],\n",
" 'top_dim': [\"eval:payload['translation']\"]},\n",
" 'SelectMeaning': {'__hint__': \"eval:payload['content']\",\n",
" '__origin__': 'mcq',\n",
" 'jammer': \"eval:list(payload['keyword_note'].values())\",\n",
" 'mapping': \"eval:payload['keyword_note']\",\n",
" 'max_riddles_num': \"eval:default['mcq']['max_riddles_num']\",\n",
" 'prefix': '选择正确项: ',\n",
" 'primary': \"eval:payload['content']\"}},\n",
" 'tts_text': \"eval:payload['content'].replace('/', \"\n",
" \"'')\"}}}\n"
]
}
],
"source": [
"test_repo_dic = test_repo.export_to_single_dict()\n",
"from pprint import pprint\n",
"\n",
"pprint(test_repo_dic)"
]
},
{
"cell_type": "markdown",
"id": "35a2e06f",
"metadata": {},
"source": [
"## 持久化与部分保存\n",
"如你所见, 所有内容被结构化地输出了! \n",
"\n",
"现在写回到文件夹! \n",
"\n",
"我们注意到, 并非所有的内容都要被修改. \n",
"我们可以只保存接受修改的一部分, 默认情况下, 是迭代的记忆数据(algodata). \n",
"这就是为什么我们一般不使用单个 json 或 toml 来存储 repo.\n",
"\n",
"persist_to_repodir 接受两个可选参数: \n",
"- save_list: 默认为 [\"algodata\"], 是要持久化的数据.\n",
"- source: 默认为原目录, 你也可以手动指定为其他文件夹(通过 Path)\n",
"\n",
"现在做一些演练, 我们将创建一个位于 test_new_repo 的\"克隆\". \n",
"除非文件夹已经存在, Repo 对象将会为你自动创建新文件夹."
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "05eeaacc",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[01;34m.\u001b[0m\n",
"├── \u001b[01;34mdata\u001b[0m\n",
"│   └── \u001b[01;34mconfig\u001b[0m\n",
"│   └── \u001b[00mconfig.toml\u001b[0m\n",
"├── \u001b[00mjiebatest.py\u001b[0m\n",
"├── \u001b[00mrepo.ipynb\u001b[0m\n",
"├── \u001b[00msimplemem.py\u001b[0m\n",
"├── \u001b[01;34mtest_new_repo\u001b[0m\n",
"│   ├── \u001b[00malgodata.json\u001b[0m\n",
"│   ├── \u001b[00mmanifest.toml\u001b[0m\n",
"│   ├── \u001b[00mpayload.toml\u001b[0m\n",
"│   ├── \u001b[00mschedule.toml\u001b[0m\n",
"│   └── \u001b[00mtypedef.toml\u001b[0m\n",
"└── \u001b[01;34mtest_repo\u001b[0m\n",
" ├── \u001b[00malgodata.json\u001b[0m\n",
" ├── \u001b[00mmanifest.toml\u001b[0m\n",
" ├── \u001b[00mpayload.toml\u001b[0m\n",
" ├── \u001b[00mschedule.toml\u001b[0m\n",
" └── \u001b[00mtypedef.toml\u001b[0m\n",
"\n",
"5 directories, 14 files\n"
]
}
],
"source": [
"test_repo.persist_to_repodir(\n",
" save_list=[\"schedule\", \"payload\", \"manifest\", \"typedef\", \"algodata\"],\n",
" source=Path(\"test_new_repo\"),\n",
")\n",
"!tree"
]
},
{
"cell_type": "markdown",
"id": "059d7bdf",
"metadata": {},
"source": [
"如你所见, test_new_repo 已被生成!"
]
},
{
"cell_type": "markdown",
"id": "4ef8925c",
"metadata": {},
"source": [
"# 数据结构\n",
"现在讲解 repo 的数据结构"
]
},
{
"cell_type": "markdown",
"id": "c19fed95",
"metadata": {},
"source": [
"## Lict 对象\n",
"Lict 对象集成了部分列表和字典的功能, 数据在这两种风格的 API 间都可用, 且修改是同步的. \n",
"Lict 默认情况下不会保存序列顺序, 而是在列表形式下, 自动按索引字符序排布, 详情请参阅源代码. \n",
"现在导入并初始化一个 Lict 对象:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "7e88bd7c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('name', 'tom'), ('age', 12), ('enemy', 'jerry')]\n",
"[('name', 'tom'), ('age', 12), ('enemy', 'jerry')]\n"
]
}
],
"source": [
"from heurams.kernel.auxiliary.lict import Lict\n",
"\n",
"lct = Lict() # 空的\n",
"lct = Lict(initlist=[(\"name\", \"tom\"), (\"age\", 12), (\"enemy\", \"jerry\")]) # 基于列表\n",
"print(lct)\n",
"lct = Lict(initdict={\"name\": \"tom\", \"age\": 12, \"enemy\": \"jerry\"}) # 基于字典\n",
"print(lct)"
]
},
{
"cell_type": "markdown",
"id": "4d760bf9",
"metadata": {},
"source": [
"### 输出形式\n",
"Lict 的\"官方\"输出形式是列表形式\n",
"你也可以选择输出字典形式"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "248f6cba",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'tom', 'age': 12, 'enemy': 'jerry'}\n"
]
}
],
"source": [
"print(lct.dicted_data)"
]
},
{
"cell_type": "markdown",
"id": "29dce184",
"metadata": {},
"source": [
"### dicted_data 属性与修改方式\n",
"dicted_data 属性是一个字典, 它自动同步来自 Lict 对象操作的修改.\n",
"一个注意事项: 不要直接修改 dicted_data, 这将不会触发同步 hook.\n",
"如果你一定要这样做, 请在完事后手动运行同步 hook.\n",
"推荐的修改方式是直接把 lct 当作一个字典"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "a0eb07a7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('name', 'tom'), ('age', 12), ('enemy', 'jerry')]\n",
"[('name', 'tom'), ('age', 12), ('enemy', 'jerry'), ('type', 'cat')]\n",
"[('name', 'tom'), ('age', 12), ('enemy', 'jerry'), ('type', 'cat'), ('is_human', False)]\n"
]
}
],
"source": [
"# 由于 jupyter 的环境处理, 请不要重复运行此单元格, 如果想再看一遍, 请重启 jupyter 后再全部运行\n",
"\n",
"# 错误的方式\n",
"lct.dicted_data[\"type\"] = \"cat\"\n",
"print(lct) # 将不会同步修改\n",
"\n",
"# 不推荐, 但可用的方式\n",
"lct.dicted_data[\"type\"] = \"cat\"\n",
"lct._sync_based_on_dict()\n",
"print(lct)\n",
"\n",
"# 推荐方式\n",
"lct[\"is_human\"] = False\n",
"print(lct)"
]
},
{
"cell_type": "markdown",
"id": "2337d113",
"metadata": {},
"source": [
"### data 属性与修改方式\n",
"data 属性是一个列表, 它自动同步来自 Lict 对象操作的修改.\n",
"一个注意事项: 不要直接修改 data, 这将不会触发同步 hook, 并且可能破坏排序.\n",
"如果你一定要这样做, 请在完事后手动运行同步 hook 和 sort, 此处不演示.\n",
"推荐的修改方式是直接把 lct 当作一个列表, 且避免使用索引修改"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0ab442d4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'tom', 'age': 12, 'enemy': 'jerry', 'type': 'cat', 'is_human': False, 'enemy_2': 'spike'}\n"
]
}
],
"source": [
"# 由于 Jupyter 的环境处理(环境状态会累积), 请不要重复运行此单元格, 如果想再看一遍, 请重启 jupyter 后再全部运行\n",
"\n",
"# 唯一推荐方式\n",
"lct.append((\"enemy_2\", \"spike\"))\n",
"print(lct.dicted_data)"
]
},
{
"cell_type": "markdown",
"id": "a3383f59",
"metadata": {},
"source": [
"### 多面手\n",
"Lict 有一些很酷的功能\n",
"详情请看源文件\n",
"此处是一些例子"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "f3ca752f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('age', 12), ('enemy', 'jerry'), ('is_human', False), ('name', 'tom'), ('type', 'cat'), ('enemy_2', 'spike')]\n",
"{'age': 12, 'enemy': 'jerry', 'is_human': False, 'name': 'tom', 'type': 'cat', 'enemy_2': 'spike'}\n",
"------\n",
"('age', 12)\n",
"('enemy', 'jerry')\n",
"('is_human', False)\n",
"('name', 'tom')\n",
"('type', 'cat')\n",
"('enemy_2', 'spike')\n",
"6\n",
"('enemy_2', 'spike')\n",
"[('age', 12), ('enemy', 'jerry'), ('is_human', False), ('name', 'tom'), ('type', 'cat')]\n",
"('type', 'cat')\n",
"[('age', 12), ('enemy', 'jerry'), ('is_human', False), ('name', 'tom')]\n",
"('name', 'tom')\n",
"[('age', 12), ('enemy', 'jerry'), ('is_human', False)]\n",
"('is_human', False)\n",
"[('age', 12), ('enemy', 'jerry')]\n",
"('enemy', 'jerry')\n",
"[('age', 12)]\n",
"('age', 12)\n",
"[]\n"
]
},
{
"data": {
"text/plain": [
"Ellipsis"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lct = Lict(\n",
" initdict={\n",
" \"age\": 12,\n",
" \"enemy\": \"jerry\",\n",
" \"is_human\": False,\n",
" \"name\": \"tom\",\n",
" \"type\": \"cat\",\n",
" \"enemy_2\": \"spike\",\n",
" }\n",
")\n",
"print(lct)\n",
"print(lct.dicted_data)\n",
"print(\"------\")\n",
"for i in lct:\n",
" print(i)\n",
"print(len(lct))\n",
"while len(lct) > 0:\n",
" print(lct.pop())\n",
" print(lct)\n",
"lct = Lict(\n",
" initdict={\n",
" \"age\": 12,\n",
" \"enemy\": \"jerry\",\n",
" \"is_human\": False,\n",
" \"name\": \"tom\",\n",
" \"type\": \"cat\",\n",
" \"enemy_2\": \"spike\",\n",
" }\n",
")\n",
"..."
]
},
{
"cell_type": "markdown",
"id": "2d6d3483",
"metadata": {},
"source": [
"关爱环境 从你我做起"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "773bf99c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"zsh:1: no matches found: heurams.log*\n"
]
}
],
"source": [
"!rm -rf test_new_repo\n",
"!rm -rf heurams.log*"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "8645c5a2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{ 'content': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/',\n",
" 'delimiter': '/',\n",
" 'keyword_note': {'崤函': '崤山和函谷关', '据': '占据', '雍州': '古代九州之一'},\n",
" 'note': [],\n",
" 'puzzles': { 'FillBlank': { '__hint__': '',\n",
" '__origin__': 'cloze',\n",
" 'delimiter': '/',\n",
" 'min_denominator': 3,\n",
" 'text': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/'},\n",
" 'Recognition': { '__hint__': '',\n",
" '__origin__': 'recognition',\n",
" 'primary': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/',\n",
" 'secondary': [ { '崤函': '崤山和函谷关',\n",
" '据': '占据',\n",
" '雍州': '古代九州之一'},\n",
" []],\n",
" 'top_dim': [ '秦孝公占据着崤山和函谷关的险固地势,拥有雍州的土地,']},\n",
" 'SelectMeaning': { '__hint__': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/',\n",
" '__origin__': 'mcq',\n",
" 'jammer': ['占据', '崤山和函谷关', '古代九州之一'],\n",
" 'mapping': { '崤函': '崤山和函谷关',\n",
" '据': '占据',\n",
" '雍州': '古代九州之一'},\n",
" 'max_riddles_num': 2,\n",
" 'prefix': '选择正确项: ',\n",
" 'primary': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/'}},\n",
" 'translation': '秦孝公占据着崤山和函谷关的险固地势,拥有雍州的土地,',\n",
" 'tts_text': '秦孝公据崤函之固, 拥雍州之地,'}\n",
"{ 'SM-2': { 'efactor': 2.5,\n",
" 'interval': 1,\n",
" 'is_activated': 1,\n",
" 'last_date': 20459,\n",
" 'last_modify': 1767700296.4950516,\n",
" 'next_date': 20460,\n",
" 'real_rept': 1,\n",
" 'rept': 0}}\n",
"{ 'content': '君臣/固守/以窥/周室,/',\n",
" 'delimiter': '/',\n",
" 'keyword_note': {'窥': '窥视'},\n",
" 'note': [],\n",
" 'puzzles': { 'FillBlank': { '__hint__': '',\n",
" '__origin__': 'cloze',\n",
" 'delimiter': '/',\n",
" 'min_denominator': 3,\n",
" 'text': '君臣/固守/以窥/周室,/'},\n",
" 'Recognition': { '__hint__': '',\n",
" '__origin__': 'recognition',\n",
" 'primary': '君臣/固守/以窥/周室,/',\n",
" 'secondary': [{'窥': '窥视'}, []],\n",
" 'top_dim': ['君臣牢固地守卫着,借以窥视周王室的权力,']},\n",
" 'SelectMeaning': { '__hint__': '君臣/固守/以窥/周室,/',\n",
" '__origin__': 'mcq',\n",
" 'jammer': ['窥视'],\n",
" 'mapping': {'窥': '窥视'},\n",
" 'max_riddles_num': 2,\n",
" 'prefix': '选择正确项: ',\n",
" 'primary': '君臣/固守/以窥/周室,/'}},\n",
" 'translation': '君臣牢固地守卫着,借以窥视周王室的权力,',\n",
" 'tts_text': '君臣固守以窥周室,'}\n",
"{ 'SM-2': { 'efactor': 2.5,\n",
" 'interval': 1,\n",
" 'is_activated': 1,\n",
" 'last_date': 20459,\n",
" 'last_modify': 1767700296.4968777,\n",
" 'next_date': 20460,\n",
" 'real_rept': 1,\n",
" 'rept': 0}}\n",
"{ 'algodata': [ ( '秦孝公据崤函之固, 拥雍州之地,',\n",
" { 'SM-2': { 'efactor': 2.5,\n",
" 'interval': 1,\n",
" 'is_activated': 1,\n",
" 'last_date': 20459,\n",
" 'last_modify': 1767700296.4950516,\n",
" 'next_date': 20460,\n",
" 'real_rept': 1,\n",
" 'rept': 0}}),\n",
" ( '君臣固守以窥周室,',\n",
" { 'SM-2': { 'efactor': 2.5,\n",
" 'interval': 1,\n",
" 'is_activated': 1,\n",
" 'last_date': 20459,\n",
" 'last_modify': 1767700296.4968777,\n",
" 'next_date': 20460,\n",
" 'real_rept': 1,\n",
" 'rept': 0}})],\n",
" 'manifest': { 'author': '__heurams__',\n",
" 'desc': '高考古诗文: 过秦论',\n",
" 'title': '测试单元: 过秦论'},\n",
" 'payload': [ ( '秦孝公据崤函之固, 拥雍州之地,',\n",
" { 'content': '秦孝公/据/崤函/之固/, 拥/雍州/之地,/',\n",
" 'keyword_note': { '崤函': '崤山和函谷关',\n",
" '据': '占据',\n",
" '雍州': '古代九州之一'},\n",
" 'note': [],\n",
" 'translation': '秦孝公占据着崤山和函谷关的险固地势,拥有雍州的土地,'}),\n",
" ( '君臣固守以窥周室,',\n",
" { 'content': '君臣/固守/以窥/周室,/',\n",
" 'keyword_note': {'窥': '窥视'},\n",
" 'note': [],\n",
" 'translation': '君臣牢固地守卫着,借以窥视周王室的权力,'})],\n",
" 'schedule': { 'phases': { 'final_review': [ ['FillBlank', '0.7'],\n",
" ['SelectMeaning', '0.7'],\n",
" ['Recognition', '1.0']],\n",
" 'quick_review': [ ['FillBlank', '1.0'],\n",
" ['SelectMeaning', '0.5'],\n",
" ['Recognition', '1.0']],\n",
" 'recognition': [['Recognition', '1.0']]},\n",
" 'schedule': [ 'quick_review',\n",
" 'recognition',\n",
" 'final_review']},\n",
" 'source': PosixPath('test_repo'),\n",
" 'typedef': { 'annotation': { 'content': '内容',\n",
" 'delimiter': '分隔符',\n",
" 'keyword_note': '关键词翻译',\n",
" 'note': '笔记',\n",
" 'translation': '语句翻译',\n",
" 'tts_text': '文本转语音文本'},\n",
" 'common': { 'delimiter': '/',\n",
" 'puzzles': { 'FillBlank': { '__hint__': '',\n",
" '__origin__': 'cloze',\n",
" 'delimiter': \"eval:nucleon['delimiter']\",\n",
" 'min_denominator': \"eval:default['cloze']['min_denominator']\",\n",
" 'text': \"eval:payload['content']\"},\n",
" 'Recognition': { '__hint__': '',\n",
" '__origin__': 'recognition',\n",
" 'primary': \"eval:payload['content']\",\n",
" 'secondary': [ \"eval:payload['keyword_note']\",\n",
" \"eval:payload['note']\"],\n",
" 'top_dim': [ \"eval:payload['translation']\"]},\n",
" 'SelectMeaning': { '__hint__': \"eval:payload['content']\",\n",
" '__origin__': 'mcq',\n",
" 'jammer': \"eval:list(payload['keyword_note'].values())\",\n",
" 'mapping': \"eval:payload['keyword_note']\",\n",
" 'max_riddles_num': \"eval:default['mcq']['max_riddles_num']\",\n",
" 'prefix': '选择正确项: ',\n",
" 'primary': \"eval:payload['content']\"}},\n",
" 'tts_text': \"eval:payload['content'].replace('/', \"\n",
" \"'')\"}}}\n"
]
}
],
"source": [
"repo = repolib.Repo.create_from_repodir(Path(\"./test_repo\"))\n",
"for i in repo.ident_index:\n",
" n = pt.Nucleon.create_on_nucleonic_data(\n",
" nucleonic_data=repo.nucleonic_data_lict.get_itemic_unit(i)\n",
" )\n",
" e = pt.Electron.create_on_electonic_data(\n",
" electronic_data=repo.electronic_data_lict.get_itemic_unit(i)\n",
" )\n",
" e.activate()\n",
" e.revisor(5, True)\n",
" print(repr(n))\n",
" print(repr(e))\n",
"print(repo)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+55
View File
@@ -0,0 +1,55 @@
import time
from pathlib import Path
import heurams.kernel.particles as pt
import heurams.kernel.repolib as repolib
from heurams.services.textproc import truncate
repo = repolib.Repo.from_repodir(Path("./test_repo"))
alist = list()
print(repo.ident_index)
for i in repo.ident_index:
n = pt.Nucleon.from_data(nucleonic_data=repo.nucleonic_data_lict.get_itemic_unit(i))
e = pt.Electron.from_data(
electronic_data=repo.electronic_data_lict.get_itemic_unit(i)
)
print(n)
input()
a = pt.Atom(n, e, repo.orbitic_data)
alist.append(a)
# e.activate()
# e.revisor(5, True)
print(repr(a))
# print(repr(e))
print(repo)
input()
import heurams.kernel.reactor as rt
ph: rt.Phaser = rt.Phaser(alist)
print(ph)
pr: rt.Procession = ph.current_procession() # type: ignore
print(pr)
pr.forward()
print(pr)
pr.forward() # 如果过界了?
print(pr) # 静默设置状态 无报错
pr.forward()
print(pr)
pr = ph.current_procession() # type: ignore # 下一个队列
print(pr)
pr.forward()
print(pr)
pr.append() # 如果记忆失败了?
print(pr)
pr.forward()
pr.append() # 如果记忆失败了?
pr.append() # 如果记忆失败了?
pr.append() # 如果记忆失败了?
pr.append() # 如果记忆失败了?
pr.append() # 如果记忆失败了?
# 重复项目只会占据一个车尾
print(pr)
pr.forward()
print(pr)
pr = ph.current_procession() # type: ignore
print(pr)
+1
View File
@@ -0,0 +1 @@
{}
+3
View File
@@ -0,0 +1,3 @@
title = "测试单元: 过秦论"
author = "__heurams__"
desc = "高考古诗文: 过秦论"
+11
View File
@@ -0,0 +1,11 @@
["秦孝公据崤函之固, 拥雍州之地,"]
note = []
content = "秦孝公/据/崤函/之固/, 拥/雍州/之地,/"
translation = "秦孝公占据着崤山和函谷关的险固地势,拥有雍州的土地,"
keyword_note = {"据"="占据", "崤函"="崤山和函谷关", "雍州"="古代九州之一"}
["君臣固守以窥周室,"]
note = []
content = "君臣/固守/以窥/周室,/"
translation = "君臣牢固地守卫着,借以窥视周王室的权力,"
keyword_note = {"窥"="窥视"}
+5
View File
@@ -0,0 +1,5 @@
schedule = ["quick_review", "recognition", "final_review"]
[phases]
quick_review = [["FillBlank", "1.0"], ["SelectMeaning", "0.5"], ["Recognition", "1.0"]]
recognition = [["Recognition", "1.0"]]
final_review = [["FillBlank", "0.7"], ["SelectMeaning", "0.7"], ["Recognition", "1.0"]]
+17
View File
@@ -0,0 +1,17 @@
[annotation]
note = "笔记"
keyword_note = "关键词翻译"
translation = "语句翻译"
delimiter = "分隔符"
content = "内容"
tts_text = "文本转语音文本"
[common]
delimiter = "/"
tts_text = "eval:payload['content'].replace('/', '')"
[common.puzzles] # 谜题定义
# 我们称 "Recognition" 为 recognition 谜题的 alia
"Recognition" = { __origin__ = "recognition", __hint__ = "", primary = "eval:payload['content']", secondary = ["eval:payload['keyword_note']", "eval:payload['note']"], top_dim = ["eval:payload['translation']"] }
"SelectMeaning" = { __origin__ = "mcq", __hint__ = "eval:payload['content']", primary = "eval:payload['content']", mapping = "eval:payload['keyword_note']", jammer = "eval:list(payload['keyword_note'].values())", max_riddles_num = "eval:default['mcq']['max_riddles_num']", prefix = "选择正确项: " }
"FillBlank" = { __origin__ = "cloze", __hint__ = "", text = "eval:payload['content']", delimiter = "eval:nucleon['delimiter']", min_denominator = "eval:default['cloze']['min_denominator']"}
+15
View File
@@ -0,0 +1,15 @@
# 运行时对象
Atom: 原子, 由核子, 电子, 轨道对象一并构成, 用于处理记忆所需一系列对象
Nucleon: 核子, 负责解析文件动态内容, 并储存记忆材料内容与谜题定义, 是静态只读但可临时覆盖内容的\
Electron: 电子, 负责处理记忆算法数据\
Orbital: 轨道, 储存记忆阶段信息与谜题阶段内出现配置
# 状态机对象
Transitions: 一种状态机框架库
Reactor: 状态机库
Phaser...
rating: 用户评估生成的值
quality: 用于单元反馈的值
+15 -63
View File
@@ -1,76 +1,28 @@
[project]
name = "heurams"
version = "0.5.1"
authors = [{ name = "Wang Zhiyu", email = "pluvium27@outlook.com" }]
version = "0.5.0"
description = "Heuristic Auxiliary Memory Scheduler"
readme = "README.md"
requires-python = ">=3.12"
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
license = "AGPL-3.0-or-later"
license-files = ["LICENSE"]
dependencies = [ # 这些依赖只能驱动 kernel 程序库
"click>=8.3.3",
authors = [{ name = "pluvium27", email = "pluvium27@outlook.com" }]
requires-python = "==3.14.*"
dependencies = [
"edge-tts>=7.2.8",
"jieba>=0.42.1",
"openai>=2.32.0",
"playsound==1.2.2",
"psutil>=7.2.2",
"pygobject>=3.56.2",
"tabulate>=0.10.0",
"textual>=8.2.3",
"toml>=0.10.2",
"transitions>=0.9.3",
"zmq>=0.0.0",
]
[project.optional-dependencies]
interface = [ # 基本用户界面依赖
"textual>=8.2.5",
]
algo-fsrs = [
"fsrs>=6.3.1", # FSRS 算法底层依赖
]
tts-edgetts = [
"edge-tts>=7.2.8", # 微软 TTS
]
llm = ["llms-py>=3.0.0"]
audio-playsound = ["playsound3>=3.3.1"]
dev = [ # 调试所需依赖
"zmq>=0.0.0", # 用于 ZMQ 远程调试服务器, 在 linux 上建议先安装 libzmq
"pytest>=8.0.0", # 用于普通测试
"pytest-cov>=6.0.0",
]
all = [
"heurams[algo-fsrs]",
"heurams[tts-edgetts]",
"heurams[llm]",
"heurams[audio-playsound]",
"heurams[dev]",
]
basic = [
"heurams[algo-fsrs]",
"heurams[interface]",
"heurams[tts-edgetts]",
"heurams[llm]",
]
[project.urls]
Homepage = "https://ams.pluv27.top"
Issues = "https://github.com/heurams/heurams/issues"
[[tool.uv.index]]
url = "https://mirrors.ustc.edu.cn/pypi/simple"
default = true
[project.scripts]
heurams = "heurams.__main__:main"
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
pythonpath = ["src"]
markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"integration: marks tests as integration tests",
]
tui = "heurams.interface.__main__:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["uv_build>=0.9.22,<0.10.0"]
build-backend = "uv_build"
+8
View File
@@ -0,0 +1,8 @@
edge-tts==7.0.2
jieba==0.42.1
openai==1.0.0
playsound==1.2.2
tabulate>=0.9.0
textual==7.0.0
toml==0.10.2
transitions==0.9.3
Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 317 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
#print("欢迎使用 HeurAMS 及其组件!")
print("欢迎使用 HeurAMS 及其组件!")
# 补充日志记录
from heurams.services.logger import get_logger
+16 -57
View File
@@ -1,63 +1,22 @@
import platform
import click
from heurams.services.version import ver, stage, codename, codename_cn
@click.group(
invoke_without_command=True,
help=(
f"HeurAMS {ver} - 启发式辅助记忆调度器"
),
context_settings={"help_option_names": ["-h", "--help"]},
)
@click.version_option(
ver, "-v", "--version",
prog_name="HeurAMS",
message=f"%(prog)s %(version)s {stage} ({codename}/{codename_cn}), {platform.system()}",
)
@click.pass_context
def cli(ctx):
if ctx.invoked_subcommand is None:
click.echo(cli.get_help(ctx))
ctx.exit(0)
@cli.command()
def tui():
"""启动内置基本用户界面 (TUI)"""
import heurams.interface.__main__ as tui_module
tui_module.main()
def _print_version():
click.echo(
f"HeurAMS {ver} ({codename}/{codename_cn}), 阶段: {stage}"
)
@cli.command()
def version():
"""输出版本信息"""
_print_version()
@cli.command(name="ver", hidden=True)
def ver_cmd():
"""输出版本信息"""
_print_version()
@cli.command(name="help")
@click.pass_context
def help_cmd(ctx):
"""显示此帮助信息"""
click.echo(cli.get_help(ctx.parent))
import heurams.services.version as ver
# __main__.py
def main():
cli()
prompt = f"""HeurAMS {ver.ver} 已经被成功地安装在系统中.
HeurAMS 被设计为一个带有辅助记忆调度器功能的软件包, 无法直接被执行, 但可被其他 Python 程序调用.
若您想启动内置的基本用户界面:
请运行 python -m heurams.interface,
或者 python -m heurams.interface.__main__
python 代指您使用的解释器, 在某些发行版中可能是 python3, 而 python 命令被指向了 python2.
尽管项目保留了 requirements.txt, 我们仍不推荐使用系统 python 和原始 venv 进行开发.
项目的推荐开发环境工具是 uv.
如果你的环境已经安装了 uv:
先运行 uv sync 同步环境, 此命令只需要执行一遍, uv 会自动处理依赖.
然后通过运行 uv run tui 启动内置基本用户界面.
此时您的解释器在项目目录里的 .venv/bin 中, 使用 IDE 开发前, 务必切换解释器!
注意: 一个常见的误区是, 执行 interface 下的 __main__.py 运行基本用户界面, 这会导致 Python 上下文环境异常, 请不要这样做."""
print(prompt)
if __name__ == "__main__":
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

-25
View File
@@ -1,25 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 554.4 554.4" version="1.1">
<defs>
<style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
</defs>
<title>HeurAMS Monochrome Logo - Dark</title>
<desc>Dark monochrome logo of the HeurAMS Project</desc>
<g id="figure_1">
<g id="patch_1">
<path d="M 0 554.4 L 554.4 554.4 L 554.4 0 L 0 0 L 0 554.4 z" style="fill: none"/>
</g>
<g id="axes_1">
<g id="patch_2">
<path d="M 66.528 487.872 L 199.584 487.872 L 199.584 354.816 L 66.528 354.816 z" clip-path="url(#p4da876c7a0)" style="fill: #1A1A1A; stroke: #1A1A1A; stroke-linejoin: miter"/>
</g>
<g id="patch_3">
<path d="M 199.584 354.816 L 487.872 354.816 L 487.872 66.528 L 199.584 66.528 z" clip-path="url(#p4da876c7a0)" style="fill: #1A1A1A; stroke: #1A1A1A; stroke-linejoin: miter"/>
</g>
</g>
</g>
<defs>
<clipPath id="p4da876c7a0">
<rect x="0" y="0" width="554.4" height="554.4"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

@@ -1,25 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 554.4 554.4" version="1.1">
<defs>
<style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
</defs>
<title>HeurAMS Monochrome Logo - Light</title>
<desc>Light monochrome logo of the HeurAMS Project</desc>
<g id="figure_1">
<g id="patch_1">
<path d="M 0 554.4 L 554.4 554.4 L 554.4 0 L 0 0 L 0 554.4 z" style="fill: none"/>
</g>
<g id="axes_1">
<g id="patch_2">
<path d="M 66.528 487.872 L 199.584 487.872 L 199.584 354.816 L 66.528 354.816 z" clip-path="url(#p4da876c7a0)" style="fill: #ffffff; stroke: #ffffff; stroke-linejoin: miter"/>
</g>
<g id="patch_3">
<path d="M 199.584 354.816 L 487.872 354.816 L 487.872 66.528 L 199.584 66.528 z" clip-path="url(#p4da876c7a0)" style="fill: #ffffff; stroke: #ffffff; stroke-linejoin: miter"/>
</g>
</g>
</g>
<defs>
<clipPath id="p4da876c7a0">
<rect x="0" y="0" width="554.4" height="554.4"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

-25
View File
@@ -1,25 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 554.4 554.4" version="1.1">
<defs>
<style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
</defs>
<title>HeurAMS Logo</title>
<desc>The logo of the HeurAMS Project</desc>
<g id="figure_1">
<g id="patch_1">
<path d="M 0 554.4 L 554.4 554.4 L 554.4 0 L 0 0 L 0 554.4 z" style="fill: none"/>
</g>
<g id="axes_1">
<g id="patch_2">
<path d="M 66.528 487.872 L 199.584 487.872 L 199.584 354.816 L 66.528 354.816 z" clip-path="url(#p4da876c7a0)" style="fill: #1660a5; stroke: #1660a5; stroke-linejoin: miter"/>
</g>
<g id="patch_3">
<path d="M 199.584 354.816 L 487.872 354.816 L 487.872 66.528 L 199.584 66.528 z" clip-path="url(#p4da876c7a0)" style="fill: #545f70; stroke: #545f70; stroke-linejoin: miter"/>
</g>
</g>
</g>
<defs>
<clipPath id="p4da876c7a0">
<rect x="0" y="0" width="554.4" height="554.4"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

-5
View File
@@ -1,5 +0,0 @@
_services_desc = '服务模块设置'
_providers_desc = '驱动模块设置'
_repo_desc = '单元集独立设置'
_interface_desc = '基本用户界面设置'
_global_desc = '底层设置'
@@ -1,25 +0,0 @@
show_header = true
_show_header_desc = "展示界面顶部的标题栏\n如果您想节省这一行空间, 可以禁用它"
clock_on_header = true
_clock_on_header_desc = "在界面顶部的标题栏显示时间"
change_window_title = true
_change_window_title_desc = "更改终端模拟器窗口的标题\n如果禁用了 header, 则建议启用"
persist_to_file = true
_persist_to_file_desc = "[调试] 将记忆更改保存到文件"
quick_pass = true
_quick_pass_desc = "[调试] 启用快速应答功能(跳过测验)"
auto_pass = false
_auto_pass_desc = "[调试] 自动通过测试模式"
scheduled_num = 35
_scheduled_num_desc = "默认记忆单元数量\n可被单元集设置覆盖"
refresh_on_resume = true
_refresh_on_resume_desc = "[调试] 每当 Screen 激活后都刷新状态"
algorithm = "SM-2"
_algorithm_desc = "默认记忆调度算法\n可被单元集设置覆盖"
[_algorithm_candidate]
NSP-0 = "筛选用非间隔重复调度器"
none = "不设置默认调度器"
SM-2 = "第二代 SuperMemo 简单间隔重复调度器\nWozniak 于 1987 年提出, Anki 的默认算法"
SM-15M = "类第15代 SuperMemo 复杂间隔重复调度器\n不稳定且逆向工程"
FSRS = "先进开放间隔重复调度器"
@@ -1,2 +0,0 @@
_cngk-t_desc = "高考必备古诗文-测试"
_cngk_desc = "高考必备古诗文"
View File
+2 -10
View File
@@ -22,17 +22,9 @@ logger = get_logger(__name__)
logger.debug(f"包目录: {rootdir}")
logger.debug(f"工作目录: {workdir}")
default_data = rootdir / "assets" / "data"
user_data = workdir / "data"
if not user_data.exists():
logger.info("初始化数据目录: %s", user_data)
import shutil
(workdir / "data" / "config").mkdir(parents=True, exist_ok=True)
shutil.copytree(default_data, user_data)
else:
(workdir / "data" / "config").mkdir(parents=True, exist_ok=True)
config_var: ContextVar[ConfigDict] = ContextVar(
config_var: ContextVar[ConfigDict].get = ContextVar(
"config_var",
default=ConfigDict(workdir / "data" / "config"),
)
+22 -31
View File
@@ -1,12 +1,10 @@
from time import sleep, perf_counter
# import gc
# gc.set_threshold(100, 1, 1)
print("欢迎使用基本用户界面!")
print("加载配置与上下文... ", end="", flush=True)
_start_all = perf_counter()
_start = _start_all
from heurams.context import rootdir, workdir, config_var
_start1 = perf_counter()
_start = perf_counter()
from heurams.context import *
_end = perf_counter()
print(f"已完成! (耗时: {round(1000 * (_end - _start))}ms)")
@@ -27,20 +25,20 @@ from .screens.navigator import NavigatorScreen
from .screens.precache import PrecachingScreen
from .screens.setting import SettingScreen
from .screens.synctool import SyncScreen
from . import shim
_end = perf_counter()
print(f"已完成! (耗时: {round(1000 * (_end - _start))}ms)")
print(f"组件目录: {rootdir}")
print(f"工作目录: {workdir}")
_end_all = perf_counter()
print(f"前置工作共计耗时: {round(1000 * (_end_all - _start_all))}ms")
_end1 = perf_counter()
print(f"前置工作共计耗时: {round(1000 * (_end1 - _start1))}ms")
class HeurAMSApp(App):
TITLE = "潜进"
CSS_PATH = rootdir / "interface" / "css" / "main.tcss"
CSS_PATH = "css/main.tcss"
css_dir = pathlib.Path("css").resolve()
SUB_TITLE = "启发式辅助记忆调度器"
BINDINGS = [
("q", "go_back", "退出"),
@@ -58,34 +56,27 @@ class HeurAMSApp(App):
"setting": SettingScreen,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def on_mount(self) -> None:
self.push_screen("dashboard")
def action_go_back(self) -> None:
self.exit() # go_back 在最顶层是退出, Screen 会再次定义为返回, 键位都是 q, 免得不一样
def action_do_nothing(
self,
) -> None: # 用来给没使用/禁用的快捷键占位, 因为 Binding 删除不了
def on_button_pressed(self, event: Button.Pressed) -> None:
pass
# self.exit(event.button.id)
'''
# 移除烦人的 "rich traceback", 但可能导致未定义行为出现, 所以注释掉
def action_go_back(self) -> None:
quit()
def action_do_nothing(self):
self.refresh()
# 移除烦人的 "rich traceback"
# Textual 官方不会管这破事, 写 Rich 写入脑了导致的
# 不知道哪来的自信改标准库的 traceback
# https://github.com/Textualize/textual/discussions/6255
# NOTE: 进行 textual 版本升级时, 确保查看过上游代码, 尤其是 App 的 _exception
# 如果行为变了就把下面的删了 (虽然有 fallback)
def _fatal_error(self):
if hasattr(self, "_exception"):
self._close_messages_no_wait()
raise self._exception
super()._fatal_error() # fallback
self._close_messages_no_wait()
raise self._exception
def panic(self, *args):
if hasattr("_exception"):
self._close_messages_no_wait()
raise self._exception
super().panic(*args) # ditto
'''
self._close_messages_no_wait()
raise self._exception
+19 -1
View File
@@ -2,13 +2,30 @@ from heurams.interface import *
from heurams.context import config_var
from heurams.services.logger import get_logger
import threading
import zmq
import pickle
logger = get_logger(__name__)
def environment_check():
from pathlib import Path
logger.debug("检查环境路径")
subdir = ["cache/voice", "repo", "global", "config"]
for i in subdir:
i = Path(config_var.get()["global"]["paths"]["data"]) / i
if not i.exists():
logger.info("创建目录: %s", i)
print(f"创建 {i}")
i.mkdir(exist_ok=True, parents=True)
else:
logger.debug("目录已存在: %s", i)
print(f"找到 {i}")
logger.debug("环境检查完成")
def start_debug_server(app):
import zmq
logger = get_logger("zmq_debug")
context = zmq.Context()
socket = context.socket(zmq.REP)
@@ -39,6 +56,7 @@ def start_debug_server(app):
def main():
environment_check()
app = HeurAMSApp()
+41 -16
View File
@@ -2,6 +2,22 @@ NavigatorScreen {
align: center middle;
}
.infview {
width: 5fr
}
.dataview {
width: 3fr
}
.repo_listitem {
layout: grid;
grid-size: 2;
}
.repo_listitem_btn {
dock: right;
offset: -5% 0
}
#dialog {
grid-size: 2;
@@ -14,23 +30,32 @@ NavigatorScreen {
background: $surface;
}
.favorite-item {
#dashboardtop {
height: 4
}
#input-container {
height: 3;
margin-top: 1;
align: center middle;
}
.container {
height: auto;
padding: 0 0 1 0;
}
.favorite-item-btn {
dock: right;
width: 8;
padding: 0;
}
.memoqueue-container {
padding: 1 2;
width: auto;
}
.memoqueue-container > * {
border: heavy $secondary;
#message-input {
width: 1fr;
padding: 0 1 0 1;
margin-right: 1;
}
#status-bar {
height: 1;
margin-top: 1;
text-style: italic;
color: $text-muted;
}
.session-label {
color: $primary;
text-style: bold;
}
@@ -3,17 +3,12 @@
}
#header {
height: 3;
height: 4;
}
#analysis {
margin: 0;
padding: 0;
}
.repo-list-item {
layout: grid;
grid-size: 1;
grid-size: 2;
height: 3;
}
@@ -1,8 +0,0 @@
#puzzle_container > * {
height: auto;
width: auto;
}
.hori {
height: auto;
}
@@ -1,24 +0,0 @@
#operations {
height: auto;
}
.btn {
margin: 0 1 0 0;
padding: 0 1 0 1;
}
#main_container {
}
#previewer_container {
}
.unit-statline {
}
#title {
padding: 0;
}
@@ -1,23 +0,0 @@
.foot {
align-vertical: bottom;
}
.setting-switch {
dock: right;
}
Select {
width: 55%;
dock: right;
}
Input {
width: 55%;
dock: right;
}
.setting-item {
width: 100%;
height: 4;
padding: 0 0 1 0;
}
View File
+47 -41
View File
@@ -3,13 +3,13 @@
from textual.app import ComposeResult
from textual.containers import ScrollableContainer
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, Markdown
from textual import events, on
from textual.widgets import Button, Footer, Header, Label, Markdown, Static
import heurams.services.version as version
from heurams.context import *
import platform
import shutil
import psutil
import os
import sys
@@ -17,78 +17,73 @@ import sys
class AboutScreen(Screen):
BINDINGS = [
("q", "go_back", "返回"),
("z", "go_back", "关于"),
]
SUB_TITLE = "关于"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def compose(self) -> ComposeResult:
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
yield Header(show_clock=True)
with ScrollableContainer(id="about_container"):
yield Label("[b]关于与版本信息[/b]")
# 获取系统信息
textual_version = self._get_textual_version()
terminal_info = self._get_terminal_info()
python_version = self._get_python_version()
os_version = self._get_os_version()
disk_usage = self._get_disk_usage()
memory_info = self._get_memory_info()
about_text = f"""
# 关于 HeurAMS "潜进"
# 关于 "潜进"
主程序库版本: `{version.ver}-python`
用户界面分支: `Textual TUI (基本用户界面)`
用户界面版本: `{version.ver}`
API 版本代号: `{version.codename.capitalize()}`
> 一个基于启发式算法与认知科学理论的辅助记忆调度器, 旨在帮助用户更高效地进行记忆工作与学习规划.
> 一个开放, 优雅, 易于扩展的间隔重复调度器实验平台, 旨在帮助研究者更高效地进行前沿记忆算法的研究.
一个基于启发式算法与认知科学理论的辅助记忆调度器, 旨在帮助用户更高效地进行记忆工作与学习规划.
您可在项目主页 https://ams.pluv27.top 获取用户指南, 开发文档与软件更新, 并参与到软件的开发与改进工作.
以 AGPL-3.0 开放源代码, 这直接意味着任何个体直接基于此代码对外或内部提供的应用和服务, 无论本地或网络, 必须向所有用户公开完整修改后的源代码, 且继续沿用 AGPL-3.0 协议.
以 GNU Affero 通用公共许可证 (第3版) 开放源代码, 并有一条豁免本机 API 调用的附加条款, 用于其他前端到程序库的接口调用.
您正使用的 TUI 用户界面是 python 版本程序库自带的基本用户界面, 作为基本的全功能前端实现与程序库测试, 如果您想去除它, 请移除程序库根目录中的 interface 文件夹.
正使用程序库内置的终端用户界面, 它是第一个全功能前端实现与程序库测试套件, 位于程序库的 interface 子目录.
可在项目主页 https://ams.pluv27.top 获取用户指南, 开发文档与软件更新.
开发人员列表:
- Wang Zhiyu ([@pluvium27](https://github.com/pluvium27)): 项目发起与主要开发者
如果您觉得这个软件有用, 可以在它的源代码仓库给它添加一个星标 :)
感谢以下人士与团体, 他们的算法与理论构成了此软件现有算法的基石:
> 潜进(HeurAMS), 以及它作为一个"程序库"是自由且免费的, 但是开发工作必须投入大量精力.
> 您可以加入各种语言的翻译团队来翻译软件的界面, 您还可以制作图像、主题、音效, 或者改进软件配套的文档……
> 不管您来自何方, 我们都欢迎您加入社区并做出贡献.
> 我们的共同目标是为人人带来高品质的辅助记忆 & 学习软件.
> 您的慷慨支持, 我们必当涌泉相报.
开发人员列表:
- Wang Zhiyu([@pluvium27](https://github.com/pluvium27)): 发起项目与主要维护者
特别感谢以下人士, 他们的算法与理论构成了此软件算法的基石:
- [Piotr A. Woźniak](https://supermemo.guru/wiki/Piotr_Wozniak): SM-2 算法与 SM-15 算法理论
- [Jarrett Ye](https://github.com/L-M-Sherlock): FSRS 算法与间隔重复理论文献参考
- [Kazuaki Tanida](https://github.com/slaypni): SM-15 算法的 CoffeeScript 逆向实现
- [Open Spaced Repetition](https://github.com/open-spaced-repetition): FSRS 算法底层实现
- [Kazuaki Tanida](https://github.com/slaypni): SM-15 算法的 CoffeeScript 实现
- [Thoughts Memo](https://www.zhihu.com/people/L.M.Sherlock): 文献参考
# 运行环境信息
Python 解释器版本: {python_version}
Python 解释器路径: {sys.executable}
Textual 框架版本: {textual_version}
终端模拟器: {terminal_info}
操作系统版本: {os_version}
存储余量: {disk_usage}
内存大小: {memory_info}
报告问题时, 请复制这些信息到问题描述, 并上传软件日志 `heurams.log` 作为附件, 以协助开发者定位错误
"""
yield Markdown(about_text, classes="about-markdown")
yield Button(
"返回主界面",
id="back_button",
variant="primary",
flat=True,
classes="back-button",
)
yield Footer()
@@ -107,7 +102,7 @@ Textual 框架版本: {textual_version}
import textual
return textual.__version__
except (ImportError, AttributeError):
except ImportError, AttributeError:
return "未知"
def _get_terminal_info(self) -> str:
@@ -143,7 +138,7 @@ Textual 框架版本: {textual_version}
import distro
return f"{distro.name()} {distro.version()}"
except (ImportError, AttributeError):
except ImportError, AttributeError:
return platform.platform()
else:
return platform.platform()
@@ -152,9 +147,20 @@ Textual 框架版本: {textual_version}
def _get_disk_usage(self) -> str:
"""获取磁盘使用情况"""
usage = shutil.disk_usage("/")
free_gb = usage.free / (1024**3)
total_gb = usage.total / (1024**3)
percent_free = (free_gb / total_gb) * 100
#print(f"{free_gb:.1f} GB ({percent_free:.1f}%)")
return f"{free_gb:.1f} GB ({percent_free:.1f}%)"
try:
usage = psutil.disk_usage("/")
free_gb = usage.free / (1024**3)
total_gb = usage.total / (1024**3)
percent_free = (free_gb / total_gb) * 100
return f"{free_gb:.1f} GB ({percent_free:.1f}%)"
except Exception:
return "未知"
def _get_memory_info(self) -> str:
"""获取内存信息"""
try:
memory = psutil.virtual_memory()
total_gb = memory.total / (1024**3)
return f"{total_gb:.1f} GB"
except Exception:
return "未知"
+39 -63
View File
@@ -1,14 +1,15 @@
"""仪表盘界面"""
from functools import reduce
import pathlib
from pathlib import Path
import os
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Horizontal, Vertical
from textual.containers import ScrollableContainer, Container, Horizontal, Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, ListItem, ListView, Static
from textual import events, on
from textual.reactive import reactive
from textual.layouts import horizontal
import heurams.kernel.particles as pt
import heurams.services.timer as timer
@@ -16,8 +17,10 @@ import heurams.services.version as version
from heurams.context import *
from heurams.kernel.particles import *
from heurams.kernel.repolib import *
from heurams.kernel.algorithms import algorithms
from heurams.services.logger import get_logger
from .about import AboutScreen
from .navigator import NavigatorScreen
from .preparation import PreparationScreen
@@ -32,10 +35,8 @@ class DashboardScreen(Screen):
("q", "go_back", "返回"),
]
CSS_PATH = rootdir / "interface" / "css" / "screens" / "dashboard.tcss"
repolink = reactive({})
CSS_PATH = Path(__file__).parent.parent / 'css' / "screens" / "dashboard.tcss"
def __init__(
self,
name: str | None = None,
@@ -43,58 +44,46 @@ class DashboardScreen(Screen):
classes: str | None = None,
) -> None:
super().__init__(name, id, classes)
self._load_data()
self.repolink = {}
def compose(self) -> ComposeResult:
"""组合界面组件"""
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
self._load_data()
yield Header(show_clock=True)
with ScrollableContainer():
yield Horizontal( # 顶部的状态
Vertical(
Label(f"当前日时间戳: {timer.get_daystamp()}"),
Label(f'欢迎使用 "潜进" 版本 {version.ver}'),
Label(f"当前 UNIX 日时间戳: {timer.get_daystamp()}"),
Label(
f"应用时区修正: UTC+{str(config_var.get()['services']['timer']['timezone_offset'] / 3600).removesuffix('.0')}"
f"应用时区修正: UTC+{config_var.get()['services']['timer']['timezone_offset'] / 3600}"
),
Label(
f"默认算法设置: {config_var.get()['interface']['global']['algorithm']}",
f"默认算法设置: {config_var.get()['interface']['global']['algorithm']}"
),
classes="left",
),
Vertical(
Label(f"已加载 {len(self.repos)} 个单元集"),
Label(
f"共计 {reduce(lambda x, y: x + y, map(lambda x: x.progress['total'], self.repos)) if self.repos else 0} 个单元"
f"共计 {reduce(lambda x, y: x + y, map(lambda x: x.progress['total'], self.repos))} 个单元"
),
Label(
f"已激活 {reduce(lambda x, y: x + y, map(lambda x: x.progress['touched'], self.repos)) if self.repos else 0} 个单元"
f"已激活 {reduce(lambda x, y: x + y, map(lambda x: x.progress['touched'], self.repos))} 个单元"
),
Label(f""),
classes="right",
),
id="header",
)
yield ListView(id="repo_list", classes="repo-list") # 单元集选择
from heurams.services.attic import Attic
a = Attic("ana", {"totaltime": 0, "openpuzzles": 0, "puzzles_err": 0})
yield Label(f"版本 {version.ver}-{version.stage}") # 版本信息
yield ListView(id="repo_list", classes="repo-list") # 单元集选择
yield Label(
f"{round(a.data['totaltime'], 2)} 秒内处理了 {a.data['openpuzzles']} 个谜题, 正确率{'无法求解' if not a.data['openpuzzles'] else ' ' + str(round(100 * (1 - a.data['puzzles_err']/a.data['openpuzzles']), 2)) + '%'}, 平均速度{'无法求解' if not a.data['totaltime'] else ' ' + str(round(a.data['openpuzzles']/a.data['totaltime'], 2)) + ' 个每秒'}",
id="analysis",
f'"潜进" 启发式辅助记忆调度器 版本 {version.ver} {version.stage.capitalize()}'
) # 版本信息
yield Footer()
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
# https://github.com/Textualize/textual/discussions/4268
# self.refresh(recompose=True) 此函数有问题且官方不管 而且性能低
def _load_data(self):
repo_dirs = Repo.probe_valid_repos_in_dir(
Path(config_var.get()["global"]["paths"]["repo"])
@@ -107,6 +96,7 @@ class DashboardScreen(Screen):
# need_review: 需要/不需要学习
# nearest_review_time: 最近下次学习时间
# progress: 进度
# algotype: 算法类型
## initial_time: 起始时间
# package: 包名
# prompt: 最终呈现信息
@@ -115,34 +105,21 @@ class DashboardScreen(Screen):
repo.progress = {
"total": repo.data_length,
"touched": 0,
"have_activated_ever": False,
}
repo.preview = {
"review": 0,
"new": repo.config[
"scheduled_num"
], # TODO: 考虑之后在这里加点运算避免 SM-2 积压, 但现在需要的是直观!
}
initial_time = float("inf")
for i in range(
repo.data_length
): # TODO: 增加异步性能优化, 但是学习数据属实规模小...
e = pt.Electron.from_data(
electronic_data=repo.electronic_data_lict[i],
algo_name=repo.config["algorithm"],
)
# n = pt.Nucleon.from_data(repo.nucleonic_data_lict[i])
for i in range(repo.data_length):
e = pt.Electron.from_data(repo.electronic_data_lict[i])
n = pt.Nucleon.from_data(repo.nucleonic_data_lict[i])
if e.is_activated():
repo.progress["have_activated_ever"] = True # 被激活过~
repo.algotype = e.algoname
repo.progress["touched"] += 1
repo.nearest_review_time = min(repo.nearest_review_time, e.nextdate())
if timer.get_daystamp() >= e.nextdate():
repo.preview["review"] += 1
# initial_time = min(initial_time, e.)
repo.need_review = timer.get_daystamp() >= repo.nearest_review_time
repo.prompt = f"""{repo.manifest['title']} \\[{repo.config['algorithm']}]
[d]进度: {repo.progress['touched']}/{repo.progress['total']} ({round(repo.progress['touched']/repo.progress['total']*100, 1)}%)[/d]
[d]{f'需要学习: {repo.preview['review']}R + {repo.preview['new']}U' if repo.need_review else (f"暂未开始: 0R + {repo.preview['new']}U" if not repo.progress['have_activated_ever'] else '无需操作')}[/d]"""
repo.prompt = f"""{repo.manifest['title']} ({repo.algotype})
进度: {repo.progress['touched']}/{repo.progress['total']} ({round(repo.progress['touched']/repo.progress['total']*100, 1)}%)
{'需要学习' if repo.need_review else "无需操作"}
"""
def on_mount(self) -> None:
"""挂载组件时初始化"""
@@ -152,16 +129,16 @@ class DashboardScreen(Screen):
repodirs = sorted(
self.repos,
key=lambda r: r.nearest_review_time,
reverse=True, # 紧张的先复习
reverse=True,
)
repotitles = map(lambda f: self.repostat[f.name]["title"], repodirs)
# 填充列表
if not repodirs:
repo_list_widget.append(
ListItem(
Static(
f"{config_var.get()['global']['paths']['repo']} 中未找到任何单元集仓库目录.\n"
"请导入单元集后重启应用, 或者新建单元集."
f"{config_var.get()['global']['paths']['repo']} 中未找到任何仓库.\n"
"请导入仓库后重启应用, 或者新建空的仓库."
),
id="not-found",
)
@@ -170,19 +147,18 @@ class DashboardScreen(Screen):
return
for r in self.repos:
self.repolink[str(r.manifest["package"])] = r # 用于规避 ctype id 对象还原
# NOTE: 上一行不要使用 id(), id 可能被重用!
self.repolink[str(id(r))] = r # 用于规避 ctype id 对象还原
list_item = ListItem(
*[Label(line) for line in r.prompt.splitlines()],
Label(r.prompt),
Button(
f"开始学习",
flat=True,
variant="primary",
id=f"slaunch_repo_{r.manifest['package']}",
id=f"slaunch_repo_{id(r)}",
classes="repo-list-item-shortcut",
),
classes="repo-list-item",
id=f"launch_repo_{r.manifest['package']}",
id=f"launch_repo_{id(r)}",
)
repo_list_widget.append(list_item)
@@ -195,7 +171,7 @@ class DashboardScreen(Screen):
return
# 还原对象
selected_repo = self.repolink[event.item.id.removeprefix("launch_repo_")]
selected_repo = self.repolink[event.item.id.lstrip("launch_repo_")]
# 跳转到准备屏幕
self.app.push_screen(PreparationScreen(selected_repo))
@@ -214,5 +190,5 @@ class DashboardScreen(Screen):
if event.button.id.startswith("slaunch_repo_"): # type: ignore
from .preparation import launch
launch(repo=self.repolink[event.button.id.removeprefix("slaunch_repo_")], app=self.app, scheduled_num=-1) # type: ignore
launch(repo=self.repolink[event.button.id.lstrip("slaunch_repo_")], app=self.app, scheduled_num=-1) # type: ignore
# TODO: 这样启动的记忆实例的状态机无法绑定到 PreparationScreen 中
+16 -31
View File
@@ -4,10 +4,8 @@ import base64
from pathlib import Path
from typing import List, Optional
from textual import events, on
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Horizontal
from textual.containers import ScrollableContainer
from textual.screen import Screen
from textual.widgets import (
Button,
@@ -16,10 +14,10 @@ from textual.widgets import (
Label,
ListItem,
ListView,
Markdown,
Static,
)
from textual import events, on
from heurams.context import config_var
from heurams.kernel.repolib import Repo
from heurams.services.favorite_service import FavoriteItem, favorite_manager
@@ -55,11 +53,7 @@ class FavoriteManagerScreen(Screen):
def compose(self) -> ComposeResult:
"""组合界面组件"""
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
yield Header(show_clock=True)
with ScrollableContainer(id="favorites-container"):
if not self.favorites:
yield Label("暂无收藏", classes="empty-label")
@@ -69,12 +63,6 @@ class FavoriteManagerScreen(Screen):
yield ListView(id="favorites-list")
yield Footer()
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def on_mount(self) -> None:
"""挂载后填充列表"""
if self.favorites:
@@ -84,7 +72,7 @@ class FavoriteManagerScreen(Screen):
def _encode_favorite_key(self, repo_path: str, ident: str) -> str:
"""编码仓库路径和标识符为安全的按钮 ID 部分"""
# 使用 \x00 分隔两部分, 然后进行 base64 编码
# 使用 \x00 分隔两部分然后进行 base64 编码
combined = f"{repo_path}\x00{ident}"
encoded = base64.urlsafe_b64encode(combined.encode()).decode()
# 去掉填充的等号
@@ -103,32 +91,29 @@ class FavoriteManagerScreen(Screen):
# 尝试获取仓库信息
repo_info = self._get_repo_info(fav.repo_path, fav)
title = repo_info.get("title", fav.repo_path) if repo_info else fav.repo_path
content_preview = repo_info.get("content_preview", "") if repo_info else ""
added_time = self._format_time(fav.added)
# 构建显示文本
display_text = f"{fav.ident}\n"
display_text += f" [d]添加于: {added_time}\n 来自 {title}[/d]"
display_text = f"[b]{title}[/b] ({fav.ident})\n"
if content_preview:
display_text += f"{content_preview}\n"
display_text += f"添加于: {added_time}"
if fav.tags:
display_text += f"{', '.join(fav.tags)}"
display_text += f" 标签: {', '.join(fav.tags)}"
# 创建安全的按钮 ID
button_key = self._encode_favorite_key(fav.repo_path, fav.ident)
# 创建列表项, 包含移除按钮
container = Horizontal(
Label(display_text, classes="favorite-content"),
Button(
"移除",
id=f"remove-{button_key}",
variant="error",
flat=True,
classes="favorite-item-btn",
),
# 创建列表项包含移除按钮
container = ScrollableContainer(
Markdown(display_text, classes="favorite-content"),
Button("移除", id=f"remove-{button_key}", variant="error"),
classes="favorite-item",
)
return ListItem(container)
def _get_repo_info(self, repo_path: str, fav: FavoriteItem) -> Optional[dict]:
"""获取仓库信息 (标题、原子内容预览) """
"""获取仓库信息标题、原子内容预览"""
try:
data_repo = Path(config_var.get()["global"]["paths"]["data"]) / "repo"
repo_dir = data_repo / repo_path
@@ -200,7 +185,7 @@ class FavoriteManagerScreen(Screen):
# 重新组合
if not self.favorites:
container.mount(Label("暂无收藏", classes="empty-label"))
container.mount(Static("使用 * 键在记忆界面中添加收藏. "))
container.mount(Static("使用 * 键在记忆界面中添加收藏"))
else:
container.mount(
Label(f"{len(self.favorites)} 个收藏项", classes="count-label")
+67 -100
View File
@@ -1,102 +1,84 @@
"""队列式记忆工作界面"""
from enum import Enum, auto
from pathlib import Path
from typing import Callable
from textual.app import ComposeResult
from textual.containers import ScrollableContainer
from textual.containers import Center, ScrollableContainer
from textual.reactive import reactive
from textual.screen import Screen
from textual.widgets import Footer, Header, Label, Static
from textual import events, on
from textual.widgets import Button, Footer, Header, Label, Static
import heurams.kernel.particles as pt
from heurams.context import config_var, rootdir
import heurams.kernel.puzzles as pz
from heurams.context import config_var
from heurams.kernel.reactor import *
from heurams.services.favorite_service import favorite_manager
from heurams.services.logger import get_logger
from heurams.services.attic import Attic
from .. import shim
class AtomState(Enum):
FAILED = auto()
NORMAL = auto()
logger = get_logger(__name__)
class MemScreen(Screen):
BINDINGS = [
("q", "go_back_notif", "返回"),
("q", "go_back", "返回"),
("p", "prev", "查看上一个"),
("d", "toggle_dark", ""),
("v", "play_voice", "朗读"),
("*", "toggle_favorite", "收藏"),
("r", "resume_mark"),
("Q", "go_back"),
("n", "block_prompt"),
("s", "block_prompt"),
("z", "block_prompt"),
("0,1,2,3", "app.push_screen('about')", ""),
]
SUB_TITLE = "学习中"
CSS_PATH = rootdir / "interface" / "css" / "screens" / "memoqueue.tcss"
if config_var.get()["interface"]["global"]["quick_pass"]:
BINDINGS.append(("k", "quick_pass", "正确应答"))
BINDINGS.append(("f", "quick_fail", "错误应答"))
rating = reactive(-1)
def __init__(
self,
router: Router,
phaser: Phaser,
save_func: Callable,
repo=None,
name=None,
id=None,
classes=None,
) -> None:
super().__init__(name, id, classes)
self.router = router
self.phaser = phaser
self.save_func = save_func
self.repo = repo
self.update_state()
self.expander: Expander
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
self.fission: Fission
def compose(self) -> ComposeResult:
from heurams.services.attic import Attic
a = Attic("ana", {"openqueue": 0})
a.data["openqueue"] += 1
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
with ScrollableContainer(classes="memoqueue-container"):
yield Label(self._get_progress_text(), id="head_stat")
yield ScrollableContainer(id="puzzle_container")
yield Header(show_clock=True)
with ScrollableContainer():
yield Label(self._get_progress_text(), id="progress")
yield ScrollableContainer(id="puzzle-container")
yield Footer()
def update_state(self):
"""更新状态机"""
self.procession: Procession = self.router.current_procession() # type: ignore
self.procession: Procession = self.phaser.current_procession() # type: ignore
self.atom: pt.Atom = self.procession.current_atom # type: ignore
def on_mount(self):
self.expander = self.procession.get_expander()
from heurams.services.attic import Attic
import time
a = Attic("ana", {"last": time.time()})
a.data["last"] = time.time()
self.fission = self.procession.get_fission()
self.mount_puzzle()
self.update_display()
def puzzle_widget(self):
try:
puzzle = self.expander.get_current_puzzle_inf()
puzzle = self.fission.get_current_puzzle_inf()
return shim.puzzle2widget[puzzle["puzzle"]]( # type: ignore
atom=self.atom, alia=puzzle["alia"] # type: ignore
)
@@ -105,46 +87,60 @@ class MemScreen(Screen):
return Static(f"无法生成谜题 {e}")
def _get_progress_text(self):
s = ""
s = f"阶段: {self.procession.phase.name}\n"
# 收藏状态
if self.repo is not None:
fav_status = "已收藏" if self._is_current_atom_favorited() else "未收藏"
s += f"[{fav_status}] "
s += f"[{self.procession.process() + 1}/{self.procession.total_length()}] \[{self.procession.route.name}]\n"
if self.procession.cursor - 1 >= 0:
s += f"上一个: [d]{self.procession.atoms[self.procession.cursor - 1]['ident']}[/d]"
s += f"收藏: {fav_status}\n"
"""if config_var.get().get("debug_topline", 0):
try:
alia = self.fission.get_current_puzzle_inf()["alia"] # type: ignore
s += f"谜题: {alia}\n"
except:
pass
try:
stat = self.phaser.__repr__("simple", "")
s += f"{stat}\n"
except:
pass
try:
stat = self.procession.__repr__("simple", "")
s += f"{stat}\n"
except:
pass
try:
stat = self.fission.__repr__("simple", "")
s += f"{stat}\n"
except Exception as e:
s = str(e)"""
s += f"进度: {self.procession.process() + 1}/{self.procession.total_length()}"
return s
def update_display(self):
"""更新进度显示"""
progress_widget = self.query_one("#head_stat")
progress_widget = self.query_one("#progress")
progress_widget.update(self._get_progress_text()) # type: ignore
def mount_puzzle(self):
"""挂载当前谜题组件"""
if self.procession.route == RouterState.FINISHED:
if self.procession.phase == PhaserState.FINISHED:
self.mount_finished_widget()
return
container = self.query_one("#puzzle_container")
container = self.query_one("#puzzle-container")
for i in container.children:
i.remove()
container.mount(self.puzzle_widget())
def mount_finished_widget(self):
"""挂载已完成组件"""
a = Attic("ana", {"finished": 0})
a.data["finished"] += 1
container = self.query_one("#puzzle_container")
container = self.query_one("#puzzle-container")
for i in container.children:
i.remove()
from heurams.interface.widgets.finished import Finished
if config_var.get()["interface"]["global"]["persist_to_file"]:
self.repo.persist_to_repodir()
container.mount(
Finished(
is_saved=config_var.get()["interface"]["global"]["persist_to_file"]
)
)
self.save_func()
container.mount(Finished(is_saved=["interface"]["global"]["persist_to_file"]))
def on_button_pressed(self, event):
event.stop()
@@ -161,7 +157,6 @@ class MemScreen(Screen):
path = Path(config_var.get()["global"]["paths"]["data"]) / "cache" / "voice"
path = path / f"{get_md5(self.atom.registry['nucleon']["tts_text"])}.wav"
logger.debug(str(path))
if path.exists():
play_by_path(path)
else:
@@ -174,10 +169,10 @@ class MemScreen(Screen):
if new_rating == -1: # 安全值
return
self.update_state()
if self.procession.route == RouterState.FINISHED:
if self.procession.phase == PhaserState.FINISHED:
rating = -1
return
self.expander.report(new_rating)
self.fission.report(new_rating)
self.forward(new_rating)
self.rating = -1
@@ -185,19 +180,10 @@ class MemScreen(Screen):
self.update_state()
allow_forward = 1 if rating >= 4 else 0
if allow_forward:
self.expander.forward()
if self.expander.state == "retronly":
self.forward_atom(self.expander.get_quality())
self.fission.forward()
if self.fission.state == "retronly":
self.forward_atom(self.fission.get_quality())
self.update_state()
from heurams.services.attic import Attic
a = Attic("ana", {"openpuzzles": 0})
a = Attic("ana", {"totaltime": 0})
a.data["openpuzzles"] += 1
import time
a.data["totaltime"] += time.time() - a.data["last"]
a.data["last"] = time.time()
self.mount_puzzle()
self.update_display()
@@ -217,18 +203,11 @@ class MemScreen(Screen):
logger.debug(f"Quality: {quality}")
self.atom_reporter(quality)
if quality <= 3:
from heurams.services.attic import Attic
a = Attic("ana", {"puzzles_err": 0})
a.data["puzzles_err"] += 1
self.procession.append()
self.update_state() # 刷新状态
self.procession.forward(1)
self.update_state() # 刷新状态
self.expander = self.procession.get_expander()
def action_go_back_notif(self):
self.notify("确定吗? 按下大写 Q 以返回")
self.fission = self.procession.get_fission()
def action_go_back(self):
self.app.pop_screen()
@@ -240,17 +219,17 @@ class MemScreen(Screen):
self.rating = 3
def _get_repo_rel_path(self) -> str:
"""获取仓库相对路径 (相对于 data/repo) """
"""获取仓库相对路径相对于 data/repo"""
if self.repo is None:
return ""
# self.repo.source 是 Path 对象, 指向仓库目录
# self.repo.source 是 Path 对象指向仓库目录
repo_full_path = self.repo.source
data_repo_path = Path(config_var.get()["global"]["paths"]["data"]) / "repo"
try:
rel_path = repo_full_path.relative_to(data_repo_path)
return str(rel_path)
except ValueError:
# 如果不在 data/repo 下, 则返回完整路径 (字符串形式)
# 如果不在 data/repo 下则返回完整路径字符串形式
return str(repo_full_path)
def _is_current_atom_favorited(self) -> bool:
@@ -273,17 +252,5 @@ class MemScreen(Screen):
else:
favorite_manager.add(repo_path, ident)
self.app.notify(f"已收藏:{ident}", severity="information")
# 更新显示 (如果需要)
# 更新显示如果需要
self.update_display()
def action_block_prompt(self):
self.app.notify("功能在记忆界面中不可用, 完成或返回后再试", severity="error")
def action_resume_mark(self):
from heurams.services.attic import Attic
import time
a = Attic("ana")
l = a.data["last"]
a.data["last"] = time.time()
self.app.notify(f"时间恢复已修正: {l} -> {a.data['last']}")
+6 -4
View File
@@ -1,9 +1,11 @@
import webbrowser
from textual.app import ComposeResult
from textual.containers import Grid
from textual.containers import Grid, ScrollableContainer
from textual.screen import ModalScreen
from textual.widgets import Button, Label, ListItem, ListView, Static
from textual.widgets import Button, Footer, Header, Label, ListItem, ListView, Static
from heurams.context import *
from heurams.services.logger import get_logger
from .favmgr import FavoriteManagerScreen
@@ -34,7 +36,7 @@ class NavigatorScreen(ModalScreen):
OTHERS = [
("退出程序", "self.app.exit()"),
("项目主页", "webbrowser.open('https://ams.pluv27.top')"),
("项目主页", "webbrowser.open('https://ams.imwangzhiyu.xyz')"),
]
def compose(self) -> ComposeResult:
+11 -20
View File
@@ -8,18 +8,16 @@ from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, ProgressBar, Static
from textual.worker import get_current_worker
from textual import events, on
import heurams.kernel.particles as pt
import heurams.services.hasher as hasher
from heurams.context import *
# 兼容性缓存路径:优先使用 paths.cache, 否则使用 data/cache
# 兼容性缓存路径:优先使用 paths.cache否则使用 data/cache
paths = config_var.get()["global"]["paths"]
cache_dir = pathlib.Path(paths.get("cache", paths["data"] + "/cache")) / "voice"
def human_size(bytes_num: int) -> str:
def format_size(bytes_num: int) -> str:
"""将字节数格式化为人类可读的字符串"""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if bytes_num < 1024.0:
@@ -55,7 +53,7 @@ class PrecachingScreen(Screen):
self.precache_worker = None
self.cancel_flag = 0
self.desc = desc
# 不再需要缓存配置, 保留配置读取以兼容
# 不再需要缓存配置保留配置读取以兼容
self.cache_stats = {
"total_size": 0,
"file_count": 0,
@@ -78,16 +76,10 @@ class PrecachingScreen(Screen):
for repo in repos:
try:
total += len(repo.ident_index)
except (AttributeError, TypeError):
except:
continue
return total
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def _update_cache_stats(self) -> None:
"""更新缓存统计信息"""
total_size = 0
@@ -105,17 +97,13 @@ class PrecachingScreen(Screen):
self.cache_stats["total_size"] = total_size
self.cache_stats["file_count"] = file_count
self.cache_stats["human_size"] = human_size(total_size)
self.cache_stats["human_size"] = format_size(total_size)
self.cache_stats["cached_units"] = cached_units
self.cache_stats["total_units"] = total_units
self.cache_stats["cache_rate"] = cache_rate
def compose(self) -> ComposeResult:
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
yield Header(show_clock=True)
with ScrollableContainer(id="precache_container"):
yield Label("[b]音频预缓存[/b]", classes="title-label")
with Container():
@@ -202,6 +190,7 @@ class PrecachingScreen(Screen):
def precache_by_text(self, text: str):
"""预缓存单段文本的音频"""
from heurams.context import config_var, rootdir, workdir
cache_dir.mkdir(parents=True, exist_ok=True)
cache_file = cache_dir / f"{hasher.get_md5(text)}.wav"
@@ -260,7 +249,7 @@ class PrecachingScreen(Screen):
def precache_all_files(self):
"""预缓存所有文件"""
from heurams.context import config_var
from heurams.context import config_var, rootdir, workdir
from heurams.kernel.repolib import Repo
repo_path = pathlib.Path(config_var.get()["global"]["paths"]["data"]) / "repo"
@@ -278,7 +267,7 @@ class PrecachingScreen(Screen):
repo.nucleonic_data_lict.get_itemic_unit(i)
)
)
except (KeyError, TypeError, AttributeError):
except:
continue
self.total = len(nucleon_list)
return self.precache_by_list(nucleon_list)
@@ -316,6 +305,8 @@ class PrecachingScreen(Screen):
try:
import shutil
from heurams.context import config_var, rootdir, workdir
shutil.rmtree(cache_dir, ignore_errors=True)
self.update_status("已清空", "音频缓存已清空", 0)
self._update_cache_display() # 更新缓存统计显示
+34 -59
View File
@@ -1,8 +1,10 @@
"""记忆准备界面"""
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Horizontal
from textual.containers import ScrollableContainer
from textual.reactive import reactive
from textual.screen import Screen
from textual.widget import Widget
from textual.widgets import (
Button,
Footer,
@@ -10,17 +12,15 @@ from textual.widgets import (
Label,
Markdown,
Static,
Rule,
Sparkline,
)
from textual.lazy import Reveal
from textual import events, on
import heurams.kernel.particles as pt
import heurams.services.hasher as hasher
from heurams.context import *
from heurams.context import config_var
from heurams.kernel.repolib import *
from heurams.kernel.algorithms import algorithms
from heurams.services.logger import get_logger
logger = get_logger(__name__)
@@ -32,71 +32,48 @@ class PreparationScreen(Screen):
BINDINGS = [
("q", "go_back", "返回"),
("p", "precache", "缓存"),
("p", "precache", "缓存音频"),
("d", "toggle_dark", ""),
("0,1,2,3", "app.push_screen('about')", ""),
]
CSS_PATH = rootdir / "interface" / "css" / "screens" / "preparation.tcss"
scheduled_num = reactive(config_var.get()["interface"]["global"]["scheduled_num"])
def __init__(self, repo: Repo) -> None:
super().__init__(name=None, id=None, classes=None)
self.repo = repo
self.load_data()
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def compose(self) -> ComposeResult:
from heurams.services.attic import Attic
yield Header(show_clock=True)
with ScrollableContainer(id="vice_container"):
yield Label(f"准备就绪: [b]{self.repo.manifest['title']}[/b]\n")
yield Label(
f"[b]仓库路径: {self.repo.source}[/b]"
)
yield Label(f"\n单元数量: {len(self.repo)}\n")
yield Label(f"最小记忆分组: {self.scheduled_num}\n", id="schnum_label")
a = Attic("ana", {"openpre": 0})
a.data["openpre"] += 1
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
yield Button(
"开始记忆",
id="start_memorizing_button",
variant="primary",
classes="start-button",
)
with ScrollableContainer(id="main_container"):
yield Markdown(
f"**准备就绪**: `{self.repo.manifest['title']}`\n", id="title"
)
yield Label(f"单元集路径: {self.repo.source}")
yield Label(
f"学习完成度: {self.repo.progress['touched']}/{len(self.repo)} [d]\\[{round(self.repo.progress['touched']/self.repo.progress['total']*100, 1)}%][/d]"
)
yield Label(
f"调度算法: {self.repo.config["algorithm"]} {algorithms[self.repo.config["algorithm"]].desc}"
)
yield Label(
f"学习数量: {self.repo.preview['review'] + self.scheduled_num} = {self.repo.preview['review']} [d][复习][/d] + {self.scheduled_num} [d][新识记][/d]\n",
id="schnum_label",
)
yield Horizontal(
Button(
"开始记忆",
id="start_memorizing_button",
variant="primary",
classes="btn",
),
Button(
"管理缓存",
id="precache_button",
variant="success",
classes="btn",
),
id="operations",
yield Button(
"预缓存音频",
id="precache_button",
variant="success",
classes="precache-button",
)
yield Static()
yield Sparkline(self.spark_line_arr, summary_function=max)
yield Rule()
# yield Static(str(self.spark_line_arr))
with Reveal(ScrollableContainer(id="previewer_container")):
for i in self.content.splitlines():
yield Static(i, classes="unit-statline")
yield Static(f"单元状态预览:\n")
for i in self.content.splitlines():
yield Static(i, classes="full")
yield Footer()
# def watch_scheduled_num(self, old_scheduled_num, new_scheduled_num):
@@ -108,7 +85,6 @@ class PreparationScreen(Screen):
# pass
def load_data(self):
self.scheduled_num = self.repo.config["scheduled_num"]
content = ""
spark_line_arr = []
for i in self.repo.ident_index:
@@ -116,8 +92,7 @@ class PreparationScreen(Screen):
nucleonic_data=self.repo.nucleonic_data_lict.get_itemic_unit(i)
)
e = pt.Electron.from_data(
electronic_data=self.repo.electronic_data_lict.get_itemic_unit(i),
algo_name=self.repo.config["algorithm"],
electronic_data=self.repo.electronic_data_lict.get_itemic_unit(i)
)
statstr = ""
@@ -171,8 +146,7 @@ def launch(repo, app, scheduled_num):
nucleonic_data=repo.nucleonic_data_lict.get_itemic_unit(i)
)
e = pt.Electron.from_data(
electronic_data=repo.electronic_data_lict.get_itemic_unit(i),
algo_name=repo.config["algorithm"],
electronic_data=repo.electronic_data_lict.get_itemic_unit(i)
)
a = pt.Atom(n, e, repo.orbitic_data)
atoms.append(a)
@@ -192,6 +166,7 @@ def launch(repo, app, scheduled_num):
from .memoqueue import MemScreen
router = rt.Router(atoms_to_provide)
memscreen = MemScreen(router=router, repo=repo)
pheser = rt.Phaser(atoms_to_provide)
save_func = repo.persist_to_repodir
memscreen = MemScreen(pheser, save_func, repo=repo)
app.push_screen(memscreen)
+34 -39
View File
@@ -1,23 +1,35 @@
"""设置页面"""
from functools import reduce
import pathlib
from pathlib import Path
import os
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Horizontal
from textual.containers import ScrollableContainer, Container, Horizontal, Vertical
from textual.screen import Screen
from textual.widgets import (
Button,
Footer,
Header,
Label,
ListItem,
ListView,
Static,
Collapsible,
Input,
Switch,
Select,
)
from textual.layouts import horizontal
from textual import events, on
import heurams.kernel.particles as pt
import heurams.services.timer as timer
import heurams.services.version as version
from heurams.context import *
from heurams.kernel.particles import *
from heurams.kernel.repolib import *
from heurams.kernel.algorithms import algorithms
from heurams.services.logger import get_logger
from heurams.services.textproc import domize, undomize
from heurams.services.epath import epath
@@ -31,9 +43,7 @@ class SettingScreen(Screen):
SUB_TITLE = "设置"
BINDINGS = [
("q", "go_back", "返回"),
("s", "go_back", "设置"),
]
CSS_PATH = rootdir / "interface" / "css" / "screens" / "setting.tcss"
def __init__(
self,
@@ -43,18 +53,9 @@ class SettingScreen(Screen):
) -> None:
super().__init__(name, id, classes)
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def compose(self) -> ComposeResult:
"""组合界面组件"""
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
yield Header(show_clock=True)
with ScrollableContainer():
yield Label("[b]设置页面[/b]")
for i in config_var.get():
@@ -63,13 +64,8 @@ class SettingScreen(Screen):
a = self._get_subcfg(f"{i}")
if a:
yield Collapsible(
*a,
title=i + f'\n[d]{config_var.get().get(f"_{i}_desc", "")}[/d]',
*a, title=i + f'\n{config_var.get().get(f"_{i}_desc", "")}'
)
yield Label(
"退出页面时, 所作的更改会立即保存, 但仍建议重启软件以确保新的配置得到应用",
classes="foot",
)
yield Footer()
def _get_subcfg(self, parent_epath: str):
@@ -84,7 +80,7 @@ class SettingScreen(Screen):
if a:
lst.append(
Collapsible(
*a, title=i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'
*a, title=i + f'\n{parent.get(f"_{i}_desc", "")}'
)
)
return lst
@@ -100,87 +96,85 @@ class SettingScreen(Screen):
if a:
lst.append(
Collapsible(
*a, title=i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'
*a, title=i + f'\n{parent.get(f"_{i}_desc", "")}'
)
)
elif f"_{i}_candidate" in parent: # 选择框模式
if isinstance(parent[f"_{i}_candidate"], dict):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Select(
(
(f"{j}\n[d]{k}[/d]", j)
(f"{j} ({k})", j)
for j, k in parent[f"_{i}_candidate"].items()
),
prompt=f'{parent.get(f"{i}", "")}',
id=domize(f"{parent_epath}.{i}"),
),
classes="setting-item",
classes="container",
)
)
elif isinstance(parent[f"_{i}_candidate"], list):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Select(
((j, j) for j in parent[f"_{i}_candidate"]),
prompt=f'{parent.get(f"{i}", "")}',
id=domize(f"{parent_epath}.{i}"),
),
classes="setting-item",
classes="container",
)
)
else:
if isinstance(parent[i], float):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Input(
value=str(parent[i]),
placeholder="要求一个浮点数",
type="number",
id=domize(f"{parent_epath}.{i}"),
),
classes="setting-item",
classes="container",
)
)
elif isinstance(parent[i], str):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Input(
value=parent[i],
placeholder="要求一个字符串",
type="text",
id=domize(f"{parent_epath}.{i}"),
),
classes="setting-item",
classes="container",
)
)
elif isinstance(parent[i], bool):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Switch(
value=parent[i],
id=domize(f"{parent_epath}.{i}"),
classes="setting-switch",
value=parent[i], id=domize(f"{parent_epath}.{i}")
),
classes="setting-item",
classes="container",
)
)
elif isinstance(parent[i], int):
lst.append(
Horizontal(
Label(i + f'\n[d]{parent.get(f"_{i}_desc", "")}[/d]'),
Label(i + f'\n{parent.get(f"_{i}_desc", "")}'),
Input(
value=str(parent[i]),
placeholder="要求一个整数",
type="integer",
id=domize(f"{parent_epath}.{i}"),
),
classes="setting-item",
classes="container",
)
)
elif isinstance(parent[i], list):
@@ -192,6 +186,7 @@ class SettingScreen(Screen):
def on_mount(self) -> None:
"""挂载组件时初始化"""
pass
def action_go_back(self) -> None:
"""返回上一屏幕"""
+9 -19
View File
@@ -6,11 +6,11 @@ import time
from textual.app import ComposeResult
from textual.containers import Horizontal, ScrollableContainer
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, ProgressBar, Static
from textual.widgets import Button, Footer, Header, Label, ProgressBar, Static
from textual.worker import get_current_worker
from textual import events, on
import heurams.kernel.particles as pt
import heurams.services.hasher as hasher
from heurams.context import *
@@ -26,18 +26,8 @@ class SyncScreen(Screen):
self.log_messages = []
self.max_log_lines = 50
@on(events.ScreenResume)
def post_active(self, event):
from heurams.interface import shim
shim.set_term_title(f"{self.app.TITLE} - {self.SUB_TITLE}")
def compose(self) -> ComposeResult:
if config_var.get()["interface"]["global"]["show_header"]:
yield Header(
show_clock=config_var.get()["interface"]["global"]["clock_on_header"]
)
yield Header(show_clock=True)
with ScrollableContainer(id="sync_container"):
# 标题和连接状态
yield Static("同步工具", classes="title")
@@ -130,7 +120,7 @@ class SyncScreen(Screen):
log_widget = self.query_one("#log_output")
log_widget.update("\n".join(self.log_messages)) # type: ignore
except Exception:
pass # 如果组件未就绪, 忽略错误
pass # 如果组件未就绪忽略错误
def on_button_pressed(self, event: Button.Pressed) -> None:
"""处理按钮点击事件"""
@@ -150,7 +140,7 @@ class SyncScreen(Screen):
def test_connection(self):
"""测试 WebDAV 服务器连接"""
if not self.sync_service:
self.log_message("同步服务未初始化, 请检查配置", is_error=True)
self.log_message("同步服务未初始化请检查配置", is_error=True)
self.update_status("❌ 同步服务未初始化")
return
@@ -172,7 +162,7 @@ class SyncScreen(Screen):
def start_sync(self):
"""开始同步"""
if not self.sync_service:
self.log_message("同步服务未初始化, 无法开始同步", is_error=True)
self.log_message("同步服务未初始化无法开始同步", is_error=True)
return
if self.is_syncing:
@@ -190,7 +180,7 @@ class SyncScreen(Screen):
self.run_worker(self.perform_sync, thread=True)
def perform_sync(self):
"""执行同步任务 (在后台线程中运行) """
"""执行同步任务在后台线程中运行"""
worker = get_current_worker()
try:
@@ -234,7 +224,7 @@ class SyncScreen(Screen):
is_error=True,
)
# 同步 orbital 目录 (如果存在)
# 同步 orbital 目录如果存在
orbital_dir = pathlib.Path(paths.get("orbital_dir", "./data/orbital"))
if orbital_dir.exists():
self.log_message(f"同步 orbital 目录: {orbital_dir}")
-13
View File
@@ -2,9 +2,6 @@
import heurams.interface.widgets as pzw
import heurams.kernel.puzzles as pz
import platform
import os
from heurams.context import config_var
puzzle2widget = {
pz.RecognitionPuzzle: pzw.Recognition,
@@ -12,13 +9,3 @@ puzzle2widget = {
pz.MCQPuzzle: pzw.MCQPuzzle,
pz.BasePuzzle: pzw.BasePuzzleWidget,
}
def set_term_title(title):
if not config_var.get()["interface"]["global"]["change_window_title"]:
return
system = platform.system()
if system == "Windows":
os.system(f"title {title}")
else: # Linux, Mac, etc.
os.write(2, f"\033]2;{title}\007".encode("utf-8"))
@@ -1,5 +1,6 @@
from typing import Iterable
from textual.app import ComposeResult
from textual.widget import Widget
import heurams.kernel.particles as pt
+4 -27
View File
@@ -2,10 +2,10 @@ import copy
import random
from typing import TypedDict
from textual.containers import ScrollableContainer, Horizontal
from textual.containers import Container
from textual.message import Message
from textual.widget import Widget
from textual.widgets import Button, Label, Markdown
from textual.events import Key
import heurams.kernel.particles as pt
import heurams.kernel.puzzles as pz
@@ -51,7 +51,6 @@ class ClozePuzzle(BasePuzzleWidget):
self.hashtable = {}
self.alia = alia
self._load()
self.btn_shortcuts = {}
self.hashmap = dict()
def _load(self):
@@ -69,30 +68,15 @@ class ClozePuzzle(BasePuzzleWidget):
yield Label(self.puzzle.wording, id="sentence")
yield Markdown(f"> {self.listprint(self.inputlist)}", id="inputpreview")
# 渲染当前问题的选项
with ScrollableContainer(id="btn-container") as s:
c = 0
btns = []
with Container(id="btn-container"):
for i in self.ans:
h = str(hash(i))
if hash(i) in self.hashmap.keys():
continue
c += 1
self.hashmap[h] = i
btnid = f"sel000-{h}"
logger.debug(f"建立按钮 {btnid}")
self.btn_shortcuts[f"{c}"] = btnid
btns.append(Button(f"{i}", id=f"{btnid}", classes="cloze-option-btn"))
for i in range((len(btns) + 1) // 2):
if 2 * i + 1 + 1 <= len(btns):
yield Horizontal(btns[i], btns[len(btns) - 1 - i], classes="hori")
else:
yield btns[i]
s.focus()
yield Button(i, id=f"{btnid}")
yield Button("退格", id="delete")
self.btn_shortcuts[f"0"] = "delete"
self.btn_shortcuts[f"backspace"] = "delete"
self.btn_shortcuts[f"delete"] = "delete"
def listprint(self, lst):
s = ""
@@ -134,10 +118,3 @@ class ClozePuzzle(BasePuzzleWidget):
pass
else:
self.atom.minimize(rating)
def on_key(self, event: Key) -> None:
# self.notify(event.key)
if event.key in self.btn_shortcuts:
btn_id = self.btn_shortcuts.get(event.key)
btn_id = "#" + btn_id
self.query_one(btn_id, Button).press()
+1 -1
View File
@@ -28,7 +28,7 @@ class Finished(Widget):
def compose(self):
yield Label("本次记忆进程结束", id="finished_msg")
yield Label(f"算法数据{'已保存' if self.is_saved else "未能保存"}")
yield Button("返回上一级", flat=True, id="back-to-menu")
yield Button("返回上一级", id="back-to-menu")
def on_button_pressed(self, event):
button_id = event.button.id
+9 -32
View File
@@ -1,7 +1,7 @@
# 单项选择题
from typing import TypedDict
from textual.containers import ScrollableContainer
from textual.containers import Container, ScrollableContainer
from textual.widget import Widget
from textual.widgets import Button, Label
@@ -9,7 +9,7 @@ import heurams.kernel.particles as pt
import heurams.kernel.puzzles as pz
from heurams.services.hasher import hash
from heurams.services.logger import get_logger
from textual.events import Key
from .base_puzzle_widget import BasePuzzleWidget
logger = get_logger(__name__)
@@ -51,7 +51,6 @@ class MCQPuzzle(BasePuzzleWidget):
self.hashmap = dict()
self.cursor = 0
self.atom = atom
self.btn_shortcuts = {}
self._load()
def _load(self):
@@ -76,24 +75,14 @@ class MCQPuzzle(BasePuzzleWidget):
yield Label(f"当前输入: {self.inputlist}", id="inputpreview")
# 渲染当前问题的选项
c = 0
with ScrollableContainer(id="btn-container") as s:
with Container(id="btn-container"):
for i in current_options:
if i in [" ", ""]:
continue
c += 1
h = str(hash(i))
self.hashmap[h] = i
btnid = f"sel{str(self.cursor).zfill(3)}-{h}"
self.hashmap[str(hash(i))] = i
btnid = f"sel{str(self.cursor).zfill(3)}-{hash(i)}"
logger.debug(f"建立按钮 {btnid}")
self.btn_shortcuts[f"{c}"] = f"{btnid}"
yield Button(f"[{c}] " + i, id=f"{btnid}")
s.focus()
yield Button("退格", id="delete")
yield Button(i, id=f"{btnid}")
self.btn_shortcuts["0"] = f"delete"
self.btn_shortcuts["delete"] = f"delete"
self.btn_shortcuts["backspace"] = f"delete"
yield Button("退格", id="delete")
def update_display(self, error=0):
# 更新预览标签
@@ -151,25 +140,20 @@ class MCQPuzzle(BasePuzzleWidget):
for child in container.children
if hasattr(child, "id") and child.id and child.id.startswith("sel")
]
container.focus()
for button in buttons_to_remove:
logger.info(button)
container.remove_children("#" + button.id) # type: ignore
# 添加当前题目的选项按钮
c = 0
current_question_index = len(self.inputlist)
if current_question_index < len(self.puzzle.options):
current_options = self.puzzle.options[current_question_index]
for option in current_options:
if option in ["", " "]:
continue
c += 1
button_id = f"sel{str(self.cursor).zfill(3)}-{hash(option)}"
if button_id not in self.hashmap:
self.hashmap[button_id[7:]] = option
new_button = Button(f"[{c}] " + option, id=button_id)
self.btn_shortcuts[f"{c}"] = button_id
new_button = Button(option, id=button_id)
container.mount(new_button)
def handler(self, rating):
@@ -177,10 +161,3 @@ class MCQPuzzle(BasePuzzleWidget):
pass
else:
self.atom.minimize(rating)
def on_key(self, event: Key) -> None:
self.notify(event.key)
if event.key in self.btn_shortcuts:
btn_id = self.btn_shortcuts.get(event.key)
btn_id = "#" + btn_id
self.query_one(btn_id, Button).press()
+5 -4
View File
@@ -2,6 +2,8 @@ import re
from typing import Dict, List, TypedDict
from textual.containers import Center
from textual.message import Message
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Button, Label, Markdown, Static
@@ -49,7 +51,7 @@ class Recognition(BasePuzzleWidget):
def compose(self):
from heurams.context import config_var
autovoice = config_var.get()["interface"]["widgets"]["recognition"]["autovoice"]
autovoice = config_var.get()["interface"]["widgets"]["autovoice"]
if autovoice:
self.screen.action_play_voice() # type: ignore
cfg: RecognitionConfig = self.atom.registry["nucleon"]["puzzles"][self.alia]
@@ -96,9 +98,8 @@ class Recognition(BasePuzzleWidget):
if isinstance(item, str):
yield Markdown(item)
with Center() as c:
with Button("我已知晓", id="ok") as b:
b.focus()
with Center():
yield Button("我已知晓", id="ok")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "ok":
+1 -1
View File
@@ -1,3 +1,3 @@
# Kernel - HeurAMS 核心
包括记忆规划相关状态机, 算法, 仓库系统, 辅助库与数据结构, 可脱离业务层
记忆规划相关算法与数据结构, 可脱离业务层
+15 -16
View File
@@ -1,19 +1,18 @@
"""算法模块
自动发现并加载所有算法实现, 提供统一的算法注册表.
"""
import importlib
import pkgutil
from pathlib import Path
from .base import BaseAlgorithm
from .sm2 import SM2Algorithm
from .sm15m import SM15MAlgorithm
from .nsp0 import NSP0Algorithm
__path__ = [str(Path(__file__).parent)]
__all__ = [
"SM2Algorithm",
"BaseAlgorithm",
"SM15MAlgorithm",
"NSP0Algorithm",
]
for _finder, _name, _ispkg in pkgutil.iter_modules(__path__):
if _name == "base":
continue
importlib.import_module(f".{_name}", __package__)
algorithms = BaseAlgorithm.get_registry()
algorithms = {
"SM-2": SM2Algorithm,
"NSP-0": NSP0Algorithm,
"SM-15M": SM15MAlgorithm,
"Base": BaseAlgorithm,
}
+6 -68
View File
@@ -5,37 +5,11 @@ from heurams.services.logger import get_logger
logger = get_logger(__name__)
_registry: dict[str, type["BaseAlgorithm"]] = {}
class BaseAlgorithm:
"""间隔重复算法基类
定义所有调度算法必须实现的接口. 子类通过继承此类并设置 algo_name
自动注册到全局算法注册表.
Attributes:
algo_name: 算法的唯一标识名称, 用于注册和查找
desc: 算法的简短描述
defaults: 算法数据字典的默认值模板
"""
algo_name = "BaseAlgorithm"
desc = "算法基类"
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
_registry[cls.algo_name] = cls
@classmethod
def get_registry(cls) -> dict[str, type["BaseAlgorithm"]]:
"""获取所有已注册算法的字典
Returns:
键为 algo_name, 值为算法类的字典
"""
return dict(_registry)
class AlgodataDict(TypedDict):
real_rept: int
rept: int
@@ -59,32 +33,18 @@ class BaseAlgorithm:
def revisor(
cls, algodata: dict, feedback: int = 5, is_new_activation: bool = False
) -> None:
"""迭代记忆数据
根据用户反馈更新算法状态, 计算下一次复习时间.
Args:
algodata: 算法数据字典, 包含该算法的所有状态参数
feedback: 用户反馈评分 (0-5), -1 表示跳过更新
is_new_activation: 是否为首次激活, 首次激活时重置部分参数
"""
"""迭代记忆数据"""
logger.debug(
"BaseAlgorithm.revisor 被调用, algodata keys: %s, feedback: %d, is_new_activation: %s",
list(algodata.keys()) if algodata else [],
feedback,
is_new_activation,
)
pass
@classmethod
def is_due(cls, algodata) -> int:
"""判断是否应该复习
Args:
algodata: 算法数据字典
Returns:
1 表示应该复习, 0 表示不需要
"""
"""是否应该复习"""
logger.debug(
"BaseAlgorithm.is_due 被调用, algodata keys: %s",
list(algodata.keys()) if algodata else [],
@@ -93,14 +53,7 @@ class BaseAlgorithm:
@classmethod
def get_rating(cls, algodata) -> str:
"""获取当前记忆状态的评分信息
Args:
algodata: 算法数据字典
Returns:
评分的字符串表示, 如 efactor 值
"""
"""获取评分信息"""
logger.debug(
"BaseAlgorithm.rate 被调用, algodata keys: %s",
list(algodata.keys()) if algodata else [],
@@ -109,14 +62,7 @@ class BaseAlgorithm:
@classmethod
def nextdate(cls, algodata) -> int:
"""获取下一次复习的时间戳
Args:
algodata: 算法数据字典
Returns:
下次复习的日期戳 (天数), -1 表示无计划
"""
"""获取下一次记忆时间戳"""
logger.debug(
"BaseAlgorithm.nextdate 被调用, algodata keys: %s",
list(algodata.keys()) if algodata else [],
@@ -125,16 +71,8 @@ class BaseAlgorithm:
@classmethod
def check_integrity(cls, algodata):
"""校验算法数据完整性
Args:
algodata: 算法数据字典
Returns:
1 表示数据完整, 0 表示数据缺失或格式错误
"""
try:
cls.AlgodataDict(**algodata[cls.algo_name])
return 1
except (KeyError, TypeError, ValueError):
except:
return 0
+2 -238
View File
@@ -1,242 +1,6 @@
"""
FSRS 算法模块 — 基于 py-fsrs 的现代间隔重复调度器
基于: https://github.com/open-spaced-repetition/py-fsrs
"""
import os
import pathlib
from datetime import datetime, timezone, timedelta
from typing import TypedDict
from fsrs import Scheduler, Card, Rating
from heurams.context import config_var
# FSRS 算法模块, 尚未就绪
from heurams.services.logger import get_logger
from heurams.services.timer import get_daystamp, get_timestamp
from .base import BaseAlgorithm
logger = get_logger(__name__)
# 全局 Scheduler 状态文件路径
_SCHEDULER_STATE_FILE = (
pathlib.Path(config_var.get()["global"]["paths"]["misc"])
/ "fsrs_scheduler_state.json"
)
def _get_global_scheduler():
"""获取全局 FSRS Scheduler 实例, 从文件加载或创建新的"""
if os.path.exists(_SCHEDULER_STATE_FILE):
try:
with open(_SCHEDULER_STATE_FILE, "r", encoding="utf-8") as f:
return Scheduler.from_json(f.read())
except Exception:
logger.warning("FSRS Scheduler 状态文件加载失败, 创建新实例")
return Scheduler()
def _save_global_scheduler(scheduler):
"""保存全局 FSRS Scheduler 实例到文件"""
try:
_SCHEDULER_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
data = scheduler.to_json()
with open(_SCHEDULER_STATE_FILE, "w", encoding="utf-8") as f:
f.write(data)
except Exception:
logger.exception("FSRS Scheduler 状态保存失败")
def _feedback_to_rating(feedback: int) -> Rating:
"""将 SM-2 风格 feedback (0-5) 映射为 FSRS Rating (1-4)"""
if feedback <= 2:
return Rating.Again
elif feedback == 3:
return Rating.Hard
elif feedback == 4:
return Rating.Good
else:
return Rating.Easy
def _datetime_to_daystamp(dt: datetime) -> int:
"""将 datetime 转换为天数戳 (从 1970-01-01) """
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
delta = dt - epoch
return delta.days
def _daystamp_to_datetime(daystamp: int) -> datetime:
"""将天数戳转换为 UTC datetime"""
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
return epoch + timedelta(days=daystamp)
class FSRSAlgorithm(BaseAlgorithm):
algo_name = "FSRS"
desc = "基于 py-fsrs 的现代间隔重复调度器"
class AlgodataDict(TypedDict):
# FSRS 特有字段
fsrs_state: int # State 枚举值: 1=Learning, 2=Review, 3=Relearning
fsrs_step: int # 当前学习步进索引, -1 表示 None (Review 状态)
fsrs_stability: float # 稳定性 (秒) , 0.0 表示尚未计算
fsrs_difficulty: float # 难度 [1.0, 10.0], 0.0 表示尚未计算
# 标准 BaseAlgorithm 兼容字段
real_rept: int
rept: int
interval: int
last_date: int
next_date: int
is_activated: int
last_modify: float
defaults = {
"fsrs_state": 1, # State.Learning
"fsrs_step": 0,
"fsrs_stability": 0.0,
"fsrs_difficulty": 0.0,
"real_rept": 0,
"rept": 0,
"interval": 0,
"last_date": 0,
"next_date": 0,
"is_activated": 0,
"last_modify": get_timestamp(),
}
@classmethod
def _algodata_to_card(cls, algodata):
"""从 algodata 恢复 Card 实例"""
data = algodata.get(cls.algo_name, cls.defaults.copy())
card = Card()
# State: int → IntEnum
card.state = data.get("fsrs_state", 1)
# Step: -1 表示 None (Review 状态下的 card.step 为 None)
step = data.get("fsrs_step", -1)
card.step = None if step == -1 else step
# Stability: 0.0 表示尚未计算 (新卡片)
stability = data.get("fsrs_stability", 0.0)
card.stability = None if stability == 0.0 else stability
# Difficulty: 0.0 表示尚未计算
difficulty = data.get("fsrs_difficulty", 0.0)
card.difficulty = None if difficulty == 0.0 else difficulty
# due: 新卡片(next_date ≤ 0)设为当前时间
next_date = data.get("next_date", 0)
if next_date <= 0:
card.due = datetime.now(timezone.utc)
else:
card.due = _daystamp_to_datetime(next_date)
# last_review
last_date = data.get("last_date", 0)
card.last_review = _daystamp_to_datetime(last_date) if last_date > 0 else None
return card
@classmethod
def _card_to_algodata(cls, card, algodata):
"""将 Card 实例状态写回 algodata"""
if cls.algo_name not in algodata:
algodata[cls.algo_name] = cls.defaults.copy()
data = algodata[cls.algo_name]
data["fsrs_state"] = int(card.state)
data["fsrs_step"] = card.step if card.step is not None else -1
data["fsrs_stability"] = card.stability if card.stability is not None else 0.0
data["fsrs_difficulty"] = (
card.difficulty if card.difficulty is not None else 0.0
)
data["last_date"] = (
_datetime_to_daystamp(card.last_review)
if card.last_review
else data.get("last_date", 0)
)
data["next_date"] = _datetime_to_daystamp(card.due) if card.due else 0
data["interval"] = max(0, data["next_date"] - data["last_date"])
data["last_modify"] = get_timestamp()
return algodata
@classmethod
def revisor(
cls, algodata: dict, feedback: int = 5, is_new_activation: bool = False
):
"""FSRS 算法迭代决策机制实现
将 feedback (0-5) 映射为 FSRS Rating 后交由 py-fsrs 调度器处理.
Args:
feedback (int): 0-5 的记忆保留率量化参数
is_new_activation: 是否为全新激活 (重置为初始状态)
"""
logger.debug(
"FSRS.revisor 开始, feedback: %d, is_new_activation: %s",
feedback,
is_new_activation,
)
if feedback == -1:
logger.debug("feedback 为 -1, 跳过更新")
return
scheduler = _get_global_scheduler()
rating = _feedback_to_rating(feedback)
if is_new_activation:
card = Card()
logger.debug("新激活, 创建新 Card")
else:
card = cls._algodata_to_card(algodata)
card, review_log = scheduler.review_card(card, rating)
_save_global_scheduler(scheduler)
cls._card_to_algodata(card, algodata)
# real_rept: 总复习次数
algodata[cls.algo_name]["real_rept"] += 1
# rept: 成功回忆次数 (feedback ≥ 3 视为成功)
if feedback >= 3:
algodata[cls.algo_name]["rept"] += 1
logger.debug(
"FSRS.revisor 完成: stability=%s, difficulty=%s, state=%s, " "next_date=%d",
card.stability,
card.difficulty,
card.state,
algodata[cls.algo_name]["next_date"],
)
@classmethod
def is_due(cls, algodata):
data = algodata.get(cls.algo_name, cls.defaults.copy())
next_date = data.get("next_date", 0)
current = get_daystamp()
result = next_date <= current
logger.debug(
"FSRS.is_due: next_date=%d, current=%d, result=%s",
next_date,
current,
result,
)
return result
@classmethod
def get_rating(cls, algodata):
data = algodata.get(cls.algo_name, cls.defaults.copy())
difficulty = data.get("fsrs_difficulty", 0.0)
logger.debug("FSRS.get_rating: difficulty=%f", difficulty)
return str(difficulty)
@classmethod
def nextdate(cls, algodata) -> int:
data = algodata.get(cls.algo_name, cls.defaults.copy())
next_date = data.get("next_date", 0)
logger.debug("FSRS.nextdate: %d", next_date)
return next_date
logger.info("FSRS算法模块尚未实现")

Some files were not shown because too many files have changed in this diff Show More