perf: 用 autoflake 删除无用依赖

没想到居然能意外地大幅提升启动速度
This commit is contained in:
2026-04-22 06:44:59 +08:00
parent 093034828b
commit b9d88383f9
38 changed files with 184 additions and 703 deletions

View File

@@ -2,9 +2,9 @@ from time import sleep, perf_counter
print("欢迎使用基本用户界面!")
print("加载配置与上下文... ", end="", flush=True)
_start1 = perf_counter()
_start = perf_counter()
from heurams.context import *
_start_all = perf_counter()
_start = _start_all
from heurams.context import rootdir, workdir, config_var
_end = perf_counter()
print(f"已完成! (耗时: {round(1000 * (_end - _start))}ms)")
@@ -32,14 +32,13 @@ print(f"已完成! (耗时: {round(1000 * (_end - _start))}ms)")
print(f"组件目录: {rootdir}")
print(f"工作目录: {workdir}")
_end1 = perf_counter()
print(f"前置工作共计耗时: {round(1000 * (_end1 - _start1))}ms")
_end_all = perf_counter()
print(f"前置工作共计耗时: {round(1000 * (_end_all - _start_all))}ms")
class HeurAMSApp(App):
TITLE = "潜进"
CSS_PATH = "css/main.tcss"
css_dir = pathlib.Path("css").resolve()
CSS_PATH = rootdir / "interface" / "css" / "main.tcss"
SUB_TITLE = "启发式辅助记忆调度器"
BINDINGS = [
("q", "go_back", "退出"),
@@ -63,24 +62,26 @@ class HeurAMSApp(App):
def on_mount(self) -> None:
self.push_screen("dashboard")
def on_button_pressed(self, event: Button.Pressed) -> None:
pass
# self.exit(event.button.id)
def action_go_back(self) -> None:
quit()
self.exit() # go_back 在最顶层是退出, Screen 会再次定义为返回, 键位都是 q, 免得不一样
def action_do_nothing(self):
self.refresh()
def action_do_nothing(self) -> None: # 用来给没使用/禁用的快捷键占位, 因为 Binding 删除不了
pass
# 移除烦人的 "rich traceback"
# Textual 官方不会管这破事, 写 Rich 写入脑了导致的
# 不知道哪来的自信改标准库的 traceback
# https://github.com/Textualize/textual/discussions/6255
# NOTE: 进行 textual 版本升级时, 确保查看过上游代码, 尤其是 App 的 _exception
# 如果行为变了就把下面的删了 (虽然有 fallback)
def _fatal_error(self):
self._close_messages_no_wait()
raise self._exception
if hasattr(self, "_exception"):
self._close_messages_no_wait()
raise self._exception
super()._fatal_error() # fallback
def panic(self, *args):
self._close_messages_no_wait()
raise self._exception
if hasattr("_exception"):
self._close_messages_no_wait()
raise self._exception
super().panic(*args) # ditto

View File

@@ -3,7 +3,7 @@
from textual.app import ComposeResult
from textual.containers import ScrollableContainer
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, Markdown, Static
from textual.widgets import Button, Footer, Header, Label, Markdown
from textual import events, on

View File

@@ -1,15 +1,12 @@
"""仪表盘界面"""
from functools import reduce
import pathlib
from pathlib import Path
import os
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Container, Horizontal, Vertical
from textual.containers import ScrollableContainer, Horizontal, Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, ListItem, ListView, Static
from textual.layouts import horizontal
from textual import events, on
from textual.reactive import reactive
@@ -19,10 +16,8 @@ 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
@@ -40,7 +35,7 @@ class DashboardScreen(Screen):
CSS_PATH = rootdir / "interface" / "css" / "screens" / "dashboard.tcss"
repolink = reactive({})
def __init__(
self,
name: str | None = None,
@@ -59,7 +54,7 @@ class DashboardScreen(Screen):
Vertical(
Label(f"当前日时间戳: {timer.get_daystamp()}"),
Label(
f"应用时区修正: UTC+{str(config_var.get()['services']['timer']['timezone_offset'] / 3600).rstrip('.0')}"
f"应用时区修正: UTC+{str(config_var.get()['services']['timer']['timezone_offset'] / 3600).removesuffix('.0')}"
),
Label(
f"默认算法设置: {config_var.get()['interface']['global']['algorithm']}",
@@ -112,21 +107,21 @@ class DashboardScreen(Screen):
repo.progress = {
"total": repo.data_length,
"touched": 0,
"have_activated_ever": 0,
"have_activated_ever": False,
}
repo.preview = {
"review": 0,
"new": repo.config["scheduled_num"],
"new": repo.config["scheduled_num"], # TODO: 考虑之后在这里加点运算避免 SM-2 积压, 但现在需要的是直观!
}
initial_time = float("inf")
for i in range(repo.data_length):
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])
# n = pt.Nucleon.from_data(repo.nucleonic_data_lict[i])
if e.is_activated():
repo.progress["have_activated_ever"] = 1
repo.progress["have_activated_ever"] = True # 被激活过~
repo.progress["touched"] += 1
repo.nearest_review_time = min(repo.nearest_review_time, e.nextdate())
if timer.get_daystamp() >= e.nextdate():
@@ -145,9 +140,9 @@ 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(
@@ -163,18 +158,19 @@ class DashboardScreen(Screen):
return
for r in self.repos:
self.repolink[str(id(r))] = r # 用于规避 ctype id 对象还原
self.repolink[str(r.manifest['package'])] = r # 用于规避 ctype id 对象还原
# NOTE: 上一行不要使用 id(), id 可能被重用!
list_item = ListItem(
*[Label(line) for line in r.prompt.splitlines()],
Button(
f"开始学习",
flat=True,
variant="primary",
id=f"slaunch_repo_{id(r)}",
id=f"slaunch_repo_{r.manifest['package']}",
classes="repo-list-item-shortcut",
),
classes="repo-list-item",
id=f"launch_repo_{id(r)}",
id=f"launch_repo_{r.manifest['package']}",
)
repo_list_widget.append(list_item)
@@ -187,7 +183,7 @@ class DashboardScreen(Screen):
return
# 还原对象
selected_repo = self.repolink[event.item.id.lstrip("launch_repo_")]
selected_repo = self.repolink[event.item.id.removeprefix("launch_repo_")]
# 跳转到准备屏幕
self.app.push_screen(PreparationScreen(selected_repo))

View File

@@ -1,25 +1,21 @@
"""队列式记忆工作界面"""
from enum import Enum, auto
from pathlib import Path
from typing import Callable
from textual.app import ComposeResult
from textual.containers import Center, ScrollableContainer, Container
from textual.containers import ScrollableContainer
from textual.reactive import reactive
from textual.screen import Screen
from textual.widgets import Button, Footer, Header, Label, Static
from textual.widgets import Footer, Header, Label, Static
from textual import events, on
import heurams.kernel.particles as pt
import heurams.kernel.puzzles as pz
from heurams.context import config_var, rootdir
from heurams.kernel.reactor import *
from heurams.services.favorite_service import favorite_manager
from heurams.services.logger import get_logger
import pickle
from .. import shim

View File

@@ -1,13 +1,10 @@
import webbrowser
from textual.app import ComposeResult
from textual.containers import Grid, ScrollableContainer
from textual.containers import Grid
from textual.screen import ModalScreen
from textual.widgets import Button, Footer, Header, Label, ListItem, ListView, Static
from textual.widgets import Button, Label, ListItem, ListView, Static
from textual import events, on
from heurams.context import *
from heurams.services.logger import get_logger
from .favmgr import FavoriteManagerScreen

View File

@@ -200,7 +200,6 @@ 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"
@@ -259,7 +258,7 @@ class PrecachingScreen(Screen):
def precache_all_files(self):
"""预缓存所有文件"""
from heurams.context import config_var, rootdir, workdir
from heurams.context import config_var
from heurams.kernel.repolib import Repo
repo_path = pathlib.Path(config_var.get()["global"]["paths"]["data"]) / "repo"
@@ -315,7 +314,6 @@ 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)

View File

@@ -1,10 +1,8 @@
"""记忆准备界面"""
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Container, Horizontal
from textual.reactive import reactive
from textual.containers import ScrollableContainer, Horizontal
from textual.screen import Screen
from textual.widget import Widget
from textual.widgets import (
Button,
Footer,
@@ -12,15 +10,13 @@ from textual.widgets import (
Label,
Markdown,
Static,
Rule,
Sparkline,
)
from textual.lazy import Reveal, Lazy
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 *

View File

@@ -1,37 +1,24 @@
"""设置页面"""
from functools import reduce
import pathlib
from pathlib import Path
import os
from textual.app import ComposeResult
from textual.containers import ScrollableContainer, Container, Horizontal, Vertical
from textual.containers import ScrollableContainer, Horizontal
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
@@ -194,7 +181,6 @@ class SettingScreen(Screen):
def on_mount(self) -> None:
"""挂载组件时初始化"""
pass
def action_go_back(self) -> None:
"""返回上一屏幕"""

View File

@@ -6,13 +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, Label, ProgressBar, Static
from textual.widgets import Button, Footer, Header, 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 *

View File

@@ -2,7 +2,8 @@
import heurams.interface.widgets as pzw
import heurams.kernel.puzzles as pz
import platform, os, sys
import platform
import os
from heurams.context import config_var
puzzle2widget = {

View File

@@ -1,6 +1,5 @@
from typing import Iterable
from textual.app import ComposeResult
from textual.widget import Widget
import heurams.kernel.particles as pt

View File

@@ -2,8 +2,7 @@ import copy
import random
from typing import TypedDict
from textual.containers import Container, ScrollableContainer
from textual.message import Message
from textual.containers import ScrollableContainer
from textual.widget import Widget
from textual.widgets import Button, Label, Markdown

View File

@@ -1,7 +1,7 @@
# 单项选择题
from typing import TypedDict
from textual.containers import Container, ScrollableContainer
from textual.containers import ScrollableContainer
from textual.widget import Widget
from textual.widgets import Button, Label

View File

@@ -2,8 +2,6 @@ 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

View File

@@ -40,7 +40,6 @@ class BaseAlgorithm:
feedback,
is_new_activation,
)
pass
@classmethod
def is_due(cls, algodata) -> int:

View File

@@ -17,11 +17,7 @@ from heurams.context import config_var
from heurams.kernel.algorithms.sm15m_calc import (
MAX_AF,
MIN_AF,
NOTCH_AF,
RANGE_AF,
RANGE_REPETITION,
SM,
THRESHOLD_RECALL,
Item,
)

View File

@@ -39,7 +39,6 @@ import datetime
import json
import math
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple
# ============================================================================
# Global Constants

View File

@@ -1,5 +1,5 @@
from collections.abc import MutableSequence
from typing import Any, Iterator, Optional
from typing import Any, Optional
class Lict(MutableSequence):

View File

@@ -1,11 +1,9 @@
from copy import deepcopy
from typing import TypedDict
import heurams.kernel.algorithms as algolib
import heurams.services.timer as timer
from heurams.kernel.algorithms import algorithms
from heurams.services.logger import get_logger
from heurams.context import config_var
logger = get_logger(__name__)

View File

@@ -1,5 +1,4 @@
from copy import deepcopy
from logging import config
from heurams.context import config_var
from heurams.services.logger import get_logger

View File

@@ -1,4 +1,3 @@
from heurams.kernel.particles import orbital
from .atom import Atom
from .electron import Electron

View File

@@ -1,4 +1,3 @@
import random
from heurams.services.logger import get_logger

View File

@@ -1,5 +1,4 @@
# mcq.py
import random
from heurams.services.logger import get_logger
@@ -17,4 +16,3 @@ class RecognitionPuzzle(BasePuzzle):
def refresh(self):
logger.debug("RecognitionPuzzle.refresh(空实现)")
pass

View File

@@ -136,7 +136,6 @@ class Router(Machine):
def __repr__(self, style="pipe", ends="\n"):
from tabulate import tabulate as tabu
from heurams.services.textproc import truncate
lst = [
{

View File

@@ -1,4 +1,4 @@
from enum import Enum, auto
from enum import Enum
from heurams.services.logger import get_logger

View File

@@ -1,11 +1,9 @@
import json
from functools import reduce
from pathlib import Path
from typing import TypedDict
import toml
import heurams.kernel.particles as pt
from heurams.context import config_var
from heurams.kernel.auxiliary.lict import Lict

View File

@@ -3,7 +3,6 @@
注意: 在未配置 pulseaudio 的 termux 不可用
"""
import os
import pathlib
import playsound

View File

@@ -1,7 +1,7 @@
"""LLM 提供者基类"""
import asyncio
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List
from heurams.services.logger import get_logger

View File

@@ -1,7 +1,6 @@
"""OpenAI 兼容 LLM 提供者"""
import asyncio
from typing import Any, AsyncGenerator, Dict, List, Optional
from typing import Any, AsyncGenerator, Dict, List
from heurams.services.logger import get_logger

View File

@@ -1,9 +1,7 @@
import pathlib
import typing
import toml
from collections import UserDict
import atexit
from heurams.services.logger import get_logger
from heurams.services.exceptions import WTFException

View File

@@ -1,4 +1,3 @@
from heurams.services.logger import get_logger
class WTFException(Exception):

View File

@@ -1,10 +1,9 @@
# 收藏服务
import json
import shutil
import time
from dataclasses import asdict, dataclass
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from typing import List
from heurams.context import config_var
from heurams.services.logger import get_logger

View File

@@ -6,7 +6,6 @@ HeurAMS 日志服务模块
import logging
import logging.handlers
import pathlib
import sys
from typing import Optional, Union
# 默认配置

View File

@@ -68,7 +68,6 @@ meaning = "狗发出的声音"
import csv
import sys
import os
import random
import argparse
from pathlib import Path

View File

@@ -1,6 +1,5 @@
import zmq
import pickle
import readline
import sys