上下文管理器与进一步移植
This commit is contained in:
213
.gitignore
vendored
213
.gitignore
vendored
@@ -1,8 +1,215 @@
|
||||
# Project specific additions
|
||||
.devflag
|
||||
.vscode
|
||||
.vscode/
|
||||
.directory
|
||||
__pycache__/
|
||||
.idea
|
||||
cache
|
||||
.idea/
|
||||
cache/
|
||||
nucleon/test.toml
|
||||
electron/test.toml
|
||||
*.egg-info/
|
||||
build/
|
||||
dist/
|
||||
|
||||
# Project specific directories
|
||||
config/
|
||||
data/cache/
|
||||
data/electrion/
|
||||
data/nucleon/
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.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/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# 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
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# 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
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Windows
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# Linux
|
||||
*~
|
||||
|
||||
# VSCode
|
||||
.vscode/
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.temp
|
@@ -1,20 +0,0 @@
|
||||
# 贡献指南
|
||||
## 使用 Nuitka 静态编译
|
||||
运行
|
||||
|
||||
```bash
|
||||
nuitka --clang --jobs=6 --standalone --onefile main.py
|
||||
```
|
||||
|
||||
## 打开调试日志
|
||||
|
||||
分别运行
|
||||
|
||||
```shell
|
||||
textual console -x SYSTEM -x EVENT -x DEBUG -x INFO
|
||||
```
|
||||
|
||||
```shell
|
||||
textual run --dev main.py
|
||||
```
|
||||
|
232
legacy/LICENSE
232
legacy/LICENSE
@@ -1,232 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 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 General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is 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. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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 “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. Use with the GNU Affero General Public License.
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU 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 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 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 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.
|
||||
|
||||
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
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
HeurAMS Copyright (C) 2025 Wang Zhiyu
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||
|
||||
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 GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
@@ -1,61 +0,0 @@
|
||||
# 实用技巧
|
||||
|
||||
## 用于数据组织的 prompt
|
||||
|
||||
```` markdown
|
||||
1. 我应该先给你一个文件范例
|
||||
```
|
||||
# 散列表的键翻译
|
||||
["keydata"]
|
||||
note = "笔记"
|
||||
keyword_note = "关键词翻译"
|
||||
translation = "语句翻译"
|
||||
|
||||
# 测试项目元数据
|
||||
["testdata"]
|
||||
# 记忆时显示的额外信息
|
||||
additional_inf = ["translation","keyword_note", "note"]
|
||||
# 填空测试, content 指代键名
|
||||
fill_blank_test = {"from"=["content"], "hint"=["translation"]}
|
||||
# 选择题测试
|
||||
draw_card_test = {"from"=["keyword_note"]}
|
||||
|
||||
["臣/密/言: /臣/以/险衅/, 夙/遭/闵凶./"] # 键名应该使用"/"基于意思断句(填空生成需要, 避免分离单个标点), 句末应该有断句, 不要断得太碎
|
||||
note = []
|
||||
translation = "臣子李密陈言: 我因命运不好, 小时候遭遇到了不幸"
|
||||
keyword_note = {"险衅"="凶险祸患(这里指命运不好)", "夙"="早时, 这里指年幼的时候", "闵"="通'悯', 指可忧患的事", "凶"="不幸, 指丧父"}
|
||||
|
||||
["生孩/六月/, 慈父/见背/; /行年/四岁/, 舅/夺/母志./"]
|
||||
note = []
|
||||
translation = "刚出生六个月, 我慈爱的父亲就不幸去世了。经过了四年, 舅父逼母亲改嫁"
|
||||
keyword_note = {"见背"="死的委婉说法", "行年"="经历的年岁", "母志"="母亲守节之志(改嫁的委婉说法)"}
|
||||
|
||||
["祖母/刘/愍/臣/孤弱/, 躬亲/抚养./"]
|
||||
note = []
|
||||
translation = "我的祖母刘氏, 怜悯我从小丧父, 便亲自对我加以抚养"
|
||||
keyword_note = {"愍"="怜悯", "躬亲"="亲身"}
|
||||
|
||||
["臣/少/多/疾病/, 九岁/不行/, 零丁/孤苦/, 至于/成立./"]
|
||||
note = []
|
||||
translation = "臣小的时候经常生病, 九岁时还不会行走。孤独无靠, 一直到成人自立"
|
||||
keyword_note = {"成立"="成人自立"}
|
||||
|
||||
["既/无/伯叔/, 终/鲜/兄弟/, 门/衰/祚/薄/, 晚/有/儿息./"]
|
||||
note = []
|
||||
translation = "既没有叔叔伯伯, 又没什么兄弟, 门庭衰微而福分浅薄, 很晚才有儿子"
|
||||
keyword_note = {"鲜"="少, 这里指'无'", "祚薄"="福分浅薄", "儿息"="亲生子女"}
|
||||
|
||||
["外/无/期功/强近/之亲/, 内/无/应门/五尺/之僮/, 茕茕/孑立/, 形影/相吊./"]
|
||||
note = []
|
||||
translation = "在外面没有比较亲近的亲戚, 在家里又没有照应门户的童仆。生活孤单没有依靠, 每天只有自己的身体和影子相互安慰"
|
||||
keyword_note = {"期功"="指关系较近的亲属", "茕茕孑立"="孤单无依靠的样子", "吊"="安慰"}
|
||||
|
||||
...# 还有重复
|
||||
```
|
||||
2. 这是新的信息
|
||||
```
|
||||
{源数据}
|
||||
```
|
||||
生成新的"{文件名}.toml"
|
||||
````
|
||||
|
@@ -1,95 +0,0 @@
|
||||
# 潜进 (HeurAMS) - 启发式辅助记忆程序
|
||||
> 惟算法之可恃兮, **筹来者于未央**
|
||||
> 扶大厦之将倾兮, **挽狂澜于既倒**
|
||||
|
||||
## 概述
|
||||
"潜进" (HeurAMS: Heuristic Auxiliary Memorizing Scheduler, 启发式记忆辅助调度器) 是为习题册, 古诗词, 及其他问答/记忆/理解型知识设计的辅助记忆软件, 提供动态规划的优化记忆方案
|
||||
|
||||
## 关于此仓库
|
||||
"潜进" 软件组项目包含多个子项目:
|
||||
- 此仓库包含了 "潜进" 项目的核心和基于 Textual 的基本用户界面的实现
|
||||
- 关于基于 Flutter 的现代用户界面, 请参阅 "潜进-F" (HeurAMS-F) 仓库
|
||||
- 关于数据同步实现, 请参阅 "潜进-S" (HeurSync) 仓库
|
||||
- 关于云端文档源实现, 请参阅 "潜进-R" (HeurRepo) 仓库
|
||||
|
||||
## 开发计划
|
||||
0.1.x: 简易调度器实现与最小原型
|
||||
0.2.x: 使用 Textual 构建 TUI, 项目可行性验证与采用 SM-2 原始算法用户自评估的原型
|
||||
0.3.x (当前): 基本数据结构, 基于 SM-2 改进算法的自动复习测评评估与遵从 IoC 设计的功能实现, 重点设计古诗文记忆理解功能, 以及 TUI 界面实现, 简单的语言模型集成
|
||||
0.4.x: 更新文件格式, 引入动态数据结构(自动内容生成), 深度语言模型集成
|
||||
0.5.x: 引入云同步与文档源
|
||||
0.6.x: 引入其他算法接口, 与跨语言库引入, 使用 Flutter 构建跨平台现代客户端
|
||||
|
||||
## 技术集成与特性
|
||||
|
||||
### 间隔迭代算法
|
||||
> 许多出版物都广泛讨论了不同重复间隔对学习效果的影响。特别是,间隔效应被认为是一种普遍现象。间隔效应是指,如果重复的间隔是分散/稀疏的,而不是集中重复,那么学习任务的表现会更好。因此,有观点提出,学习中使用的最佳重复间隔是**最长的、但不会导致遗忘的间隔**。
|
||||
- 采用经实证的 SM-2 间隔迭代算法, 此算法亦用作 Anki 闪卡记忆软件的默认闪卡调度器
|
||||
> 计划: 将添加 FSRS 算法 (Anki 的新可选闪卡调度器) 与一种 SM-15 变体算法作为后续替代
|
||||
> 参考 https://github.com/slaypni/SM-15
|
||||
> 使用 SM-15 的变体:
|
||||
> SM-2 后续算法并非完全开放, 故使用一种基于 SM-15 描述实现的变体算法
|
||||
- 动态规划每个记忆单元的记忆间隔时间表
|
||||
- 动态跟踪记忆反馈数据,优化长期记忆保留率与稳定性
|
||||
|
||||
### 学习进程优化
|
||||
- 逐字解析:支持逐字详细释义解析
|
||||
- 语法分析:接入生成式人工智能, 支持古文结构交互式解析
|
||||
- 自然语音:集成微软神经网络文本转语音 (TTS) 技术
|
||||
|
||||
### 实用用户界面
|
||||
|
||||
- 响应式 Textual 框架构建的跨平台 TUI 界面
|
||||
- 支持触屏/鼠标/键盘多操作模式
|
||||
- 简洁直观的复习流程设计
|
||||
|
||||
## 屏幕截图 (基本用户界面)
|
||||
|
||||
> 单击图片以放大
|
||||
|
||||
<img src="./readme_src/img1.png" alt="img1" style="zoom: 33%;" />
|
||||
<img src="./readme_src/img2.png" alt="img2" style="zoom:33%;" />
|
||||
<img src="./readme_src/img3.png" alt="img3" style="zoom:33%;" />
|
||||
<img src="./readme_src/img4.png" alt="img4" style="zoom:33%;" />
|
||||
|
||||
## 技术架构
|
||||
|
||||
> 有关技术与实现的细节, 请参阅 CONTRIBUTING.md
|
||||
> 提交拉取请求以参与到此开放源代码项目
|
||||
|
||||
``` mermaid
|
||||
graph TD
|
||||
subgraph 后端
|
||||
A[SM-2 算法] --> B[间隔迭代算法]
|
||||
B --> C[迭代记忆参数]
|
||||
end
|
||||
|
||||
subgraph 用户界面
|
||||
D[展示模块] --> E[用户界面]
|
||||
E --> F[进度追踪面板]
|
||||
end
|
||||
|
||||
subgraph 外部服务
|
||||
G[LLM]
|
||||
H[TTS]
|
||||
end
|
||||
|
||||
C --> D
|
||||
F -->|用户数据| C
|
||||
D --> G
|
||||
D --> H
|
||||
```
|
||||
|
||||
## 系统与平台要求
|
||||
|
||||
- 依赖组件: Python 3.7+ (与 PIP), Git (半自动更新 & 安装需要), requirements.txt 中依赖包
|
||||
- 可选依赖: curl (首次下载需要)
|
||||
- 平台支持:Windows / macOS / Linux / Android (需要 Termux 或 Linux) (终端或浏览器)
|
||||
- 网络连接:可预缓存语音文件, 需联网使用大模型服务功能
|
||||
|
||||
运行此命令以在具备以上前置条件的计算机上快速安装/保留数据更新:
|
||||
```
|
||||
curl -O https://gitea.imwangzhiyu.xyz/ajax/HeurAMS/raw/branch/main/tweak.py
|
||||
|
||||
python3 tweak.py
|
||||
```
|
@@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
|
||||
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="554.4pt" height="554.4pt" viewBox="0 0 554.4 554.4" xmlns="http://www.w3.org/2000/svg" version="1.1">
|
||||
<defs>
|
||||
<style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
|
||||
</defs>
|
||||
<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.1 KiB |
@@ -1,68 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import time
|
||||
import pathlib
|
||||
import toml
|
||||
import typing
|
||||
from playsound import playsound
|
||||
import threading
|
||||
import hashlib
|
||||
import edge_tts as tts
|
||||
|
||||
class ConfigFile:
|
||||
def __init__(self, path: str):
|
||||
self.path = pathlib.Path(path)
|
||||
if not self.path.exists():
|
||||
self.path.touch()
|
||||
self.data = dict()
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
"""从文件加载配置数据"""
|
||||
with open(self.path, 'r') as f:
|
||||
try:
|
||||
self.data = toml.load(f)
|
||||
except toml.TomlDecodeError:
|
||||
self.data = {}
|
||||
|
||||
def modify(self, key: str, value: typing.Any):
|
||||
"""修改配置值并保存"""
|
||||
self.data[key] = value
|
||||
self.save()
|
||||
|
||||
def save(self, path: typing.Union[str, pathlib.Path] = ""):
|
||||
"""保存配置到文件"""
|
||||
save_path = pathlib.Path(path) if path else self.path
|
||||
with open(save_path, 'w') as f:
|
||||
toml.dump(self.data, f)
|
||||
|
||||
def get(self, key: str, default: typing.Any = None) -> typing.Any:
|
||||
"""获取配置值,如果不存在返回默认值"""
|
||||
return self.data.get(key, default)
|
||||
|
||||
def action_play_voice(content):
|
||||
config = ConfigFile("config.toml")
|
||||
if config.get("auto_voice", False):
|
||||
return
|
||||
def play():
|
||||
communicate = tts.Communicate(
|
||||
content,
|
||||
"zh-CN-YunjianNeural",
|
||||
)
|
||||
communicate.save_sync(
|
||||
f"./cache/voice/{content}.wav"
|
||||
)
|
||||
playsound(f"./cache/voice/{content}.wav")
|
||||
threading.Thread(target=play).start()
|
||||
|
||||
def get_daystamp() -> int:
|
||||
"""获取当前日戳(以天为单位的整数时间戳)"""
|
||||
config = ConfigFile("config.toml")
|
||||
time_override = config.get("time_override", -1)
|
||||
|
||||
if time_override != -1:
|
||||
return int(time_override)
|
||||
|
||||
return int((time.time()+config.get("timezone_offset")) // (24 * 3600))
|
||||
|
||||
def get_md5(text):
|
||||
return hashlib.md5(text.encode('utf-8')).hexdigest()
|
@@ -1,302 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.events import Event
|
||||
from textual.widgets import (
|
||||
Collapsible,
|
||||
Header,
|
||||
Footer,
|
||||
Markdown,
|
||||
ListView,
|
||||
ListItem,
|
||||
Label,
|
||||
Static,
|
||||
Button,
|
||||
)
|
||||
from textual.containers import Container, Horizontal, Center
|
||||
from textual.screen import Screen
|
||||
from textual.widget import Widget
|
||||
import uuid
|
||||
from typing import Tuple, Dict
|
||||
import particles as pt
|
||||
import puzzles as pz
|
||||
import re
|
||||
import random
|
||||
import copy
|
||||
|
||||
|
||||
class Composition:
|
||||
def __init__(
|
||||
self,
|
||||
screen: Screen,
|
||||
reactor,
|
||||
atom: Tuple[pt.Electron, pt.Nucleon, Dict] = pt.Atom.placeholder(),
|
||||
extra = {}
|
||||
):
|
||||
self.screen = screen
|
||||
self.atom = atom
|
||||
from reactor import Reactor
|
||||
|
||||
self.reactor: Reactor = reactor
|
||||
self.reg = dict()
|
||||
|
||||
def regid(self, id_):
|
||||
self.reg[id_] = id_ + str(uuid.uuid4())
|
||||
return self.reg[id_]
|
||||
|
||||
def getid(self, id_):
|
||||
if id_ not in self.reg.keys():
|
||||
return "None"
|
||||
return self.reg[id_]
|
||||
|
||||
def recid(self, id_):
|
||||
return id_[:-36]
|
||||
|
||||
def compose(self):
|
||||
yield Label("示例标签", id="testlabel")
|
||||
yield Button("示例按钮", id="testbtn")
|
||||
|
||||
def handler(self, event, type_):
|
||||
return 1
|
||||
|
||||
|
||||
class Finished(Composition):
|
||||
def __init__(self, screen: Screen, reactor, atom: Tuple[pt.Electron, pt.Nucleon, Dict], extra = {}):
|
||||
super().__init__(screen, reactor, atom)
|
||||
|
||||
def compose(self):
|
||||
yield Label("本次记忆进程结束", id=self.regid("msg"))
|
||||
|
||||
|
||||
class Placeholder(Composition):
|
||||
def __init__(self, screen: Screen, extra = {}):
|
||||
self.screen = screen
|
||||
|
||||
def compose(self):
|
||||
yield Label("示例标签", id="testlabel")
|
||||
yield Button("示例按钮", id="testbtn", classes="choice")
|
||||
|
||||
def handler(self, event, type_):
|
||||
self.screen.query_one("#testlabel", Label).update("hi")
|
||||
|
||||
|
||||
class Recognition(Composition):
|
||||
def __init__(self, screen: Screen, reactor, atom: Tuple[pt.Electron, pt.Nucleon, Dict], extra = {}):
|
||||
super().__init__(screen, reactor, atom)
|
||||
|
||||
def compose(self):
|
||||
with Center():
|
||||
yield Static(f"[dim]{self.atom[1]['translation']}[/]")
|
||||
yield Label(f"")
|
||||
s = str(self.atom[1]["content"])
|
||||
replace_dict = {
|
||||
", ": ",",
|
||||
". ": ".",
|
||||
"; ": ";",
|
||||
": ": ":",
|
||||
"/,": ",",
|
||||
"./": ".",
|
||||
"/;": ";",
|
||||
";/": ";",
|
||||
":/": ":",
|
||||
}
|
||||
for old, new in replace_dict.items():
|
||||
s = s.replace(old, new)
|
||||
result = re.split(r"(?<=[,;:|])", s.replace("/", " "))
|
||||
for i in result:
|
||||
with Center():
|
||||
yield Label(
|
||||
f"[b][b]{i.replace('/', ' ')}[/][/]",
|
||||
id=self.regid("sentence" + str(hash(i))),
|
||||
)
|
||||
for i in self.atom[2]["testdata"]["additional_inf"]:
|
||||
if self.atom[1][i]:
|
||||
if isinstance(self.atom[1][i], list):
|
||||
for j in self.atom[1][i]:
|
||||
yield Markdown(f"### {self.atom[2]['keydata'][i]}: {j}")
|
||||
continue
|
||||
if isinstance(self.atom[1][i], Dict):
|
||||
t = ""
|
||||
for j, k in self.atom[1][i].items(): # type: ignore
|
||||
# 弱智的 Pylance 类型推导
|
||||
t += f"> **{j}**: {k} \n"
|
||||
yield Markdown(t, id=self.regid("tran"))
|
||||
with Center():
|
||||
yield Button("我已知晓", id=self.regid("ok"))
|
||||
|
||||
def handler(self, event, type_):
|
||||
if type_ == "button":
|
||||
if event.button.id == self.getid("ok"):
|
||||
self.reactor.report(self.atom, 5)
|
||||
return 0
|
||||
return -1
|
||||
|
||||
|
||||
class BasicEvaluation(Composition):
|
||||
def __init__(self, screen: Screen, reactor, atom: Tuple[pt.Electron, pt.Nucleon, Dict], extra = {}):
|
||||
super().__init__(screen, reactor, atom)
|
||||
|
||||
def compose(self):
|
||||
yield Label(self.atom[1]["content"], id="sentence")
|
||||
with Container(id="button_container"):
|
||||
btn = {}
|
||||
btn["5"] = Button(
|
||||
"完美回想", variant="success", id=self.regid("feedback5"), classes="choice"
|
||||
)
|
||||
btn["4"] = Button(
|
||||
"犹豫后正确", variant="success", id=self.regid("feedback4"), classes="choice"
|
||||
)
|
||||
btn["3"] = Button(
|
||||
"困难地正确", variant="warning", id=self.regid("feedback3"), classes="choice"
|
||||
)
|
||||
btn["2"] = Button(
|
||||
"错误但熟悉", variant="warning", id=self.regid("feedback2"), classes="choice"
|
||||
)
|
||||
btn["1"] = Button(
|
||||
"错误且不熟", variant="error", id=self.regid("feedback1"), classes="choice"
|
||||
)
|
||||
btn["0"] = Button(
|
||||
"完全空白", variant="error", id=self.regid("feedback0"), classes="choice"
|
||||
)
|
||||
yield Horizontal(btn["5"], btn["4"])
|
||||
yield Horizontal(btn["3"], btn["2"])
|
||||
yield Horizontal(btn["1"], btn["0"])
|
||||
|
||||
def handler(self, event, type_):
|
||||
if "feedback" in event.button.id:
|
||||
assess = int(self.recid(event.button.id)[8:9])
|
||||
ret = self.reactor.report(self.atom, assess)
|
||||
return ret
|
||||
|
||||
|
||||
class FillBlank(Composition):
|
||||
def __init__(self, screen: Screen, reactor, atom: Tuple[pt.Electron, pt.Nucleon, Dict], extra:Dict = {}):
|
||||
super().__init__(screen, reactor, atom)
|
||||
self.extra = extra
|
||||
self.inputlist = []
|
||||
self.hashtable = {}
|
||||
self._work()
|
||||
|
||||
def _work(self):
|
||||
self.puzzle = pz.BlankPuzzle(self.atom[1]["content"], 2)
|
||||
self.puzzle.refresh()
|
||||
self.ans = copy.copy(self.puzzle.answer)
|
||||
random.shuffle(self.ans)
|
||||
|
||||
def compose(self):
|
||||
if self.extra.get("feedback_msg"):
|
||||
yield Label("反馈提示:" + self.extra["feedback_msg"])
|
||||
yield Label(self.puzzle.wording, id=self.regid("sentence"))
|
||||
yield Label(f"当前输入: {self.inputlist}", id=self.regid("inputpreview"))
|
||||
for i in self.ans:
|
||||
self.hashtable[str(hash(i))] = i
|
||||
yield Button(i, id=self.regid(f"select{hash(i)}"))
|
||||
yield Button("退格", id=self.regid(f"delete"))
|
||||
|
||||
def handler(self, event, type_):
|
||||
# TODO: 改动:在线错误纠正
|
||||
if type_ == "button":
|
||||
if self.recid(event.button.id) == "delete":
|
||||
if len(self.inputlist) > 0:
|
||||
self.inputlist.pop()
|
||||
else:
|
||||
return 1
|
||||
else:
|
||||
self.inputlist.append(self.hashtable[self.recid(event.button.id)[6:]])
|
||||
if len(self.inputlist) < len(self.puzzle.answer):
|
||||
return 1
|
||||
else:
|
||||
if self.inputlist == self.puzzle.answer:
|
||||
self.reactor.report(self.atom, 4)
|
||||
return 0
|
||||
else:
|
||||
self.inputlist = []
|
||||
self.reactor.report(self.atom, 2)
|
||||
return 2
|
||||
|
||||
|
||||
class DrawCard(Composition):
|
||||
def __init__(self, screen: Screen, reactor, atom: Tuple[pt.Electron, pt.Nucleon, Dict], extra = {}):
|
||||
super().__init__(screen, reactor, atom)
|
||||
self.inputlist = []
|
||||
self.hashtable = {}
|
||||
self._work()
|
||||
|
||||
def _work(self):
|
||||
self.puzzle = pz.SelectionPuzzle(self.atom[1]["keyword_note"], [], 2, "选择正确词义: ") # type: ignore
|
||||
self.puzzle.refresh()
|
||||
|
||||
def compose(self):
|
||||
yield Label(self.atom[1].content.replace("/",""), id=self.regid("sentence"))
|
||||
yield Label(self.puzzle.wording[len(self.inputlist)], id=self.regid("puzzle"))
|
||||
yield Label(f"当前输入: {self.inputlist}", id=self.regid("inputpreview"))
|
||||
for i in self.puzzle.options[len(self.inputlist)]:
|
||||
self.hashtable[str(hash(i))] = i
|
||||
yield Button(i, id=self.regid(f"select{hash(i)}"))
|
||||
yield Button("退格", id=self.regid(f"delete"))
|
||||
|
||||
def handler(self, event, type_):
|
||||
if type_ == "button":
|
||||
if self.recid(event.button.id) == "delete":
|
||||
if len(self.inputlist) > 0:
|
||||
self.inputlist.pop()
|
||||
else:
|
||||
return 1
|
||||
else:
|
||||
self.inputlist.append(self.hashtable[self.recid(event.button.id)[6:]])
|
||||
if len(self.inputlist) < len(self.puzzle.answer):
|
||||
return 1
|
||||
else:
|
||||
if self.inputlist == self.puzzle.answer:
|
||||
self.reactor.report(self.atom, 4)
|
||||
return 0
|
||||
else:
|
||||
self.inputlist = []
|
||||
self.reactor.report(self.atom, 2)
|
||||
return 2
|
||||
|
||||
|
||||
registry = {
|
||||
"sample": Composition,
|
||||
"recognition": Recognition,
|
||||
"fill_blank_test": FillBlank,
|
||||
"draw_card_test": DrawCard,
|
||||
"basic_evaluation": BasicEvaluation,
|
||||
}
|
||||
|
||||
|
||||
class TestScreen(Screen):
|
||||
def __init__(self):
|
||||
super().__init__(name=None, id=None, classes=None)
|
||||
self.comp = Recognition(self, None, pt.Atom.advanced_placeholder())
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
yield from self.comp.compose()
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self) -> None:
|
||||
pass
|
||||
|
||||
def on_button_pressed(self, event: Event) -> None:
|
||||
self.comp.handler(event, "button")
|
||||
|
||||
def action_quit_app(self) -> None:
|
||||
self.app.exit()
|
||||
|
||||
|
||||
class AppLauncher(App):
|
||||
CSS_PATH = "styles.css"
|
||||
TITLE = "测试布局"
|
||||
BINDINGS = [("escape", "quit", "退出"), ("d", "toggle_dark", "改变色调")]
|
||||
SCREENS = {
|
||||
"testscreen": TestScreen,
|
||||
}
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.action_toggle_dark()
|
||||
self.push_screen("testscreen")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = AppLauncher()
|
||||
app.run()
|
@@ -1,10 +0,0 @@
|
||||
# [调试] 将更改保存到文件
|
||||
save = 1
|
||||
# [调试] 覆写时间, 设为 -1 以禁用
|
||||
time_override = -1
|
||||
# [调试] 一键通过
|
||||
quick_pass = 0
|
||||
# 对于每个项目的新记忆核子数量
|
||||
tasked_number = 8
|
||||
# UTC 时间戳修正 用于 UNIX 日时间戳的生成修正, 单位为秒
|
||||
timezone_offset = +28800 # 中国标准时间 (UTC+8)
|
@@ -1,67 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# 模拟规划完成所有记忆单元集文件的最小时间
|
||||
import os
|
||||
import particles as pt
|
||||
import datetime
|
||||
import pathlib
|
||||
import math
|
||||
import time
|
||||
|
||||
MINIMAL_REPEATATION = 2
|
||||
FILTER = "ALL"
|
||||
WORST_EF = 5
|
||||
PAYLOAD = 16
|
||||
|
||||
print("SM-2 任务预规划实用程序")
|
||||
print(f"运行时刻: {datetime.datetime.now()}")
|
||||
print(f" > 筛选器模式: {FILTER}")
|
||||
print(f" > 最小重复次数设置: {MINIMAL_REPEATATION}")
|
||||
print(f" > 最坏难度系数: {WORST_EF}")
|
||||
print(f" > 单日单元负荷: {PAYLOAD}")
|
||||
|
||||
print("--------")
|
||||
|
||||
filelist = []
|
||||
|
||||
if FILTER == "ALL":
|
||||
for i in os.listdir('./nucleon'):
|
||||
if "toml" in i:
|
||||
print("扫描到记忆单元集: " + i)
|
||||
filelist.append(i)
|
||||
print(f"共需记忆 {len(filelist)} 个记忆单元集")
|
||||
else:
|
||||
filelist = [FILTER]
|
||||
|
||||
print("--------")
|
||||
time_counter = 0
|
||||
text_counter = 0
|
||||
content_counter = 0
|
||||
for i in filelist:
|
||||
print(f"处理: {i}")
|
||||
nucu = pt.NucleonUnion(pathlib.Path("./nucleon/" + i))
|
||||
print(f"记忆单元数: {len(nucu.nucleons)}")
|
||||
content_cnt = 0
|
||||
metadata_trsl_cnt = 0
|
||||
metadata_note_cnt = 0
|
||||
metadata_kwrd_cnt = 0
|
||||
for i in nucu.nucleons:
|
||||
if i.content[-1] != "/":
|
||||
print('检测到不规范字符串')
|
||||
print(i.content)
|
||||
content_cnt += len(i.content)
|
||||
metadata_trsl_cnt += len(str(i.metadata["translation"]))
|
||||
metadata_kwrd_cnt += len(str(i.metadata["keyword_note"]))
|
||||
metadata_note_cnt += len(str(i.metadata["note"]))
|
||||
print(" - 原文文字数: " + str(content_cnt))
|
||||
metadata_cnt = metadata_kwrd_cnt + metadata_note_cnt + metadata_trsl_cnt
|
||||
print(" - 元数据字数: " + str(metadata_cnt) + f"\n = {metadata_trsl_cnt}[翻译] + {metadata_kwrd_cnt}[关键词] + {metadata_note_cnt}[笔记]")
|
||||
print(f" - 总文字数: {content_cnt + metadata_cnt}")
|
||||
print(f"独占记忆时间: {len(nucu.nucleons) / PAYLOAD} -> {math.ceil(len(nucu.nucleons) / PAYLOAD)}")
|
||||
#time.sleep(0.1)
|
||||
text_counter += (content_cnt + metadata_cnt)
|
||||
content_counter += content_cnt
|
||||
time_counter += math.ceil(len(nucu.nucleons) / PAYLOAD)
|
||||
print("--------")
|
||||
for i in range(MINIMAL_REPEATATION):
|
||||
print(f"若按计划进行, 最长需要 {time_counter + (i + 1) * 6} 天完成全部内容的第 {i + 1} 次记忆")
|
||||
print(f"规划包含 {content_counter} 字, 附加了 {text_counter - content_counter} 字的元数据内容, 共计 {text_counter} 字")
|
@@ -1,40 +0,0 @@
|
||||
@echo off
|
||||
echo "HeurAMS 环境安装脚本"
|
||||
echo "正在检测系统中是否安装 Python 3.x..."
|
||||
|
||||
rem 检查 Python 3 是否存在
|
||||
where python >nul 2>nul
|
||||
if %errorlevel% neq 0 (
|
||||
echo "错误: 未检测到 Python. 请确保 Python 已添加到系统 PATH 中,然后再次运行此脚本。"
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
rem 检查 Python 版本是否为 3.x
|
||||
for /f "tokens=*" %%i in ('python -c "import sys; print(f'{sys.version_info.major}')"') do set PYTHON_MAJOR_VERSION=%%i
|
||||
if "%PYTHON_MAJOR_VERSION%"=="3" (
|
||||
for /f "tokens=*" %%i in ('python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"') do set PYTHON_VERSION=%%i
|
||||
echo "检测到 Python 3 已安装, 版本为: %PYTHON_VERSION%"
|
||||
) else (
|
||||
echo "错误: 未检测到 Python 3. 请先安装 Python 3, 然后再次运行此脚本."
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo "---"
|
||||
echo "正在安装 requirements.txt 中的依赖..."
|
||||
|
||||
rem 检查 requirements.txt 文件是否存在
|
||||
if exist "requirements.txt" (
|
||||
python -m pip install -r requirements.txt
|
||||
if %errorlevel% equ 0 (
|
||||
echo "依赖安装成功."
|
||||
) else (
|
||||
echo "错误: 依赖安装失败. 请检查 requirements.txt 文件或网络连接."
|
||||
exit /b 1
|
||||
)
|
||||
) else (
|
||||
echo "警告: 未找到 requirements.txt 文件. 跳过依赖安装."
|
||||
)
|
||||
|
||||
echo "---"
|
||||
echo "HeurAMS 的环境依赖已安装"
|
||||
pause
|
@@ -1,28 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "HeurAMS 环境安装脚本"
|
||||
echo "正在检测系统中是否安装 Python 3.x..."
|
||||
if command -v python3 &>/dev/null; then
|
||||
PYTHON_VERSION=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
|
||||
echo "检测到 Python 3 已安装, 版本为: ${PYTHON_VERSION}"
|
||||
else
|
||||
echo "错误: 未检测到 Python 3. 请先安装 Python 3, 然后再次运行此脚本. "
|
||||
exit 1 # 退出脚本, 因为 Python 3 是必需的
|
||||
fi
|
||||
|
||||
echo "---"
|
||||
echo "正在安装 requirements.txt 中的依赖..."
|
||||
if [ -f "requirements.txt" ]; then
|
||||
python3 -m pip install -r requirements.txt
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "依赖安装成功. "
|
||||
else
|
||||
echo "错误: 依赖安装失败. 请检查 requirements.txt 文件或网络连接. "
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "警告: 未找到 requirements.txt 文件. 跳过依赖安装. "
|
||||
fi
|
||||
|
||||
echo "---"
|
||||
echo "HeurAMS 的环境依赖已安装"
|
@@ -1 +0,0 @@
|
||||
# 语言模型接入
|
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from textual.app import App
|
||||
import screens
|
||||
import os
|
||||
|
||||
class AppLauncher(App):
|
||||
CSS_PATH = "styles.css"
|
||||
TITLE = "潜进 - 辅助记忆调度器"
|
||||
BINDINGS = [("escape", "quit", "退出"), ("d", "toggle_dark", "改变色调")]
|
||||
SCREENS = {
|
||||
"dashboard": screens.DashboardScreen,
|
||||
}
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.push_screen("dashboard")
|
||||
|
||||
if __name__ == "__main__":
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
os.chdir(script_dir)
|
||||
os.makedirs("electron", exist_ok=True)
|
||||
os.makedirs("nucleon", exist_ok=True)
|
||||
os.makedirs("cache/voice", exist_ok=True)
|
||||
app = AppLauncher()
|
||||
app.run()
|
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
ver = "0.3.8"
|
||||
stage = "production"
|
@@ -1,154 +0,0 @@
|
||||
# 散列表的键翻译
|
||||
["keydata"]
|
||||
note = "笔记"
|
||||
keyword_note = "关键词翻译"
|
||||
translation = "语句翻译"
|
||||
|
||||
# 测试项目元数据
|
||||
["testdata"]
|
||||
# 记忆时显示的额外信息
|
||||
additional_inf = []
|
||||
# 填空测试, content 指代键名
|
||||
fill_blank_test = {"from"=["content"], "hint"=["translation"]}
|
||||
# 选择题测试
|
||||
draw_card_test = {"from"=["keyword_note"]}
|
||||
|
||||
["古之/学者/必有/师./"]
|
||||
note = ["学者:求学的人"]
|
||||
translation = "古代求学的人一定有老师"
|
||||
keyword_note = {"学者"="求学的人"}
|
||||
|
||||
["师者/, 所以/传道/受业/解惑/也./"]
|
||||
note = ["受:通'授',传授,讲授"]
|
||||
translation = "老师是传授道理,教授学业,解决疑难问题的人"
|
||||
keyword_note = {"传道"="传授道理", "受业"="教授学业", "解惑"="解决疑难问题", "受"="通'授',传授"}
|
||||
|
||||
["人非/生而/知之/者/, 孰能/无惑/?/"]
|
||||
note = []
|
||||
translation = "人不是生下来就懂得道理的,谁能没有疑惑"
|
||||
keyword_note = {"孰能"="谁能"}
|
||||
|
||||
["惑而/不从/师/, 其/为惑/也/, 终/不解/矣./"]
|
||||
note = []
|
||||
translation = "有疑惑却不跟从老师学习,他所存在的疑惑,就始终不能解决"
|
||||
keyword_note = {"终"="始终"}
|
||||
|
||||
["生乎/吾前/, 其/闻道/也/固/先乎/吾/, 吾/从而/师之/;/"]
|
||||
note = []
|
||||
translation = "在我之前出生的人,他懂得道理本来就比我早,我跟从他,拜他为师"
|
||||
keyword_note = {"闻道"="懂得道理", "固"="本来", "师之"="以他为师"}
|
||||
|
||||
["生乎/吾后/, 其/闻道/也/亦/先乎/吾/, 吾/从而/师之/./"]
|
||||
note = []
|
||||
translation = "在我之后出生的人,他懂得道理如果也比我早,我也跟从他学习,把他当作老师"
|
||||
keyword_note = {"亦"="也"}
|
||||
|
||||
["吾/师道/也/, 夫/庸知/其年/之/先后/生于/吾乎/?/"]
|
||||
note = []
|
||||
translation = "我学习的是道理,哪里管他的年龄比我大还是比我小呢"
|
||||
keyword_note = {"师道"="学习道理", "庸知"="哪里管"}
|
||||
|
||||
["是故/无贵/无贱/, 无长/无少/, 道之/所存/, 师之/所存/也./"]
|
||||
note = []
|
||||
translation = "因此,不论地位显贵还是地位低下,不论年长年少,道理存在的地方,就是老师存在的地方"
|
||||
keyword_note = {"是故"="因此", "所存"="存在的地方"}
|
||||
|
||||
["嗟乎!/ 师道/之/不传/也/久矣!/ 欲人/之/无惑/也/难矣!/"]
|
||||
note = []
|
||||
translation = "唉!从师学习的风尚没有流传已经很久了,想要人们没有疑惑很难呐"
|
||||
keyword_note = {"嗟乎"="感叹词,唉", "师道"="从师学习的风尚"}
|
||||
|
||||
["古之/圣人/, 其/出人/也/远矣/, 犹且/从师/而问/焉/;/"]
|
||||
note = []
|
||||
translation = "古代的圣人,他们超过一般人很远了,尚且跟从老师向老师请教"
|
||||
keyword_note = {"出人"="超出一般人", "犹且"="尚且"}
|
||||
|
||||
["今之/众人/, 其/下/圣人/也/亦/远矣/, 而/耻学/于师/./"]
|
||||
note = []
|
||||
translation = "现在的一般人,他们跟圣人相比相差很远了,却以向老师学为羞耻"
|
||||
keyword_note = {"众人"="一般人", "下"="低于,不如", "耻学于师"="以向老师学习为耻"}
|
||||
|
||||
["是故/圣/益圣/, 愚/益愚/./"]
|
||||
note = []
|
||||
translation = "所以圣人就更加圣明,愚人就更加愚昧"
|
||||
keyword_note = {"益"="更加"}
|
||||
|
||||
["圣人/之/所以/为圣/, 愚人/之/所以/为愚/, 其/皆/出于/此乎!/"]
|
||||
note = []
|
||||
translation = "圣人之所以成为圣人,愚人之所以成为愚人,大概都是这个原因引起的吧"
|
||||
keyword_note = {"所以"="...的原因", "其"="大概"}
|
||||
|
||||
["爱/其子/, 择师/而教/之/;/ 于/其身/也/, 则/耻师/焉/, 惑矣/./"]
|
||||
note = []
|
||||
translation = "众人喜爱他们的孩子,选择老师教育孩子;他们自己呢,却以从师学习为耻,这真是糊涂啊"
|
||||
keyword_note = {"其身"="他们自己", "耻师"="以从师为耻", "惑"="糊涂"}
|
||||
|
||||
["彼/童子/之师/, 授之/书/而习/其/句读/者/, 非/吾/所谓/传其道/解其惑/者也/./"]
|
||||
note = ["句读:也叫句逗。古代称文辞意尽处为句,语意未尽而须停顿处为读"]
|
||||
translation = "那孩子的老师,教他们读书,学习书中的文句,并不是我所说的给人传授道理,给人解释疑惑的老师"
|
||||
keyword_note = {"句读"="文句停顿", "所谓"="所说的"}
|
||||
|
||||
["句读/之/不知/, 惑之/不解/, 或/师焉/, 或/不焉/, 小学/而/大遗/, 吾/未见/其明/也/./"]
|
||||
note = ["不:通'否',表否定"]
|
||||
translation = "不理解文句,疑惑得不到解决,有的向老师学习,有的却不向老师求教,小的方面学习,大的方面却放弃了,我看不出他们有什么明智的呢"
|
||||
keyword_note = {"或"="有的", "不"="通'否'", "小学"="小的方面学习", "大遗"="大的方面放弃"}
|
||||
|
||||
["巫医/乐师/百工/之人/, 不耻/相师/./"]
|
||||
note = ["巫医:古代用祝祷、占卜等迷信方法或兼用药物医治疾病为业的人", "百工:泛指手工业者"]
|
||||
translation = "医生,乐师及各种工匠,不以互相学习为耻"
|
||||
keyword_note = {"巫医"="医生", "乐师"="音乐师", "百工"="各种工匠", "不耻相师"="不以互相学习为耻"}
|
||||
|
||||
["士大夫/之族/, 曰师/曰弟子/云者/, 则/群聚/而笑/之/./"]
|
||||
note = []
|
||||
translation = "士大夫这类人中,如有人称人家为老师,称自己为学生,这些人就聚集在一起嘲笑他"
|
||||
keyword_note = {"族"="类", "云者"="如此说"}
|
||||
|
||||
["问之/, 则曰/:/“彼与/彼年/相若/也/, 道/相似/也/./"]
|
||||
note = []
|
||||
translation = "问那些嘲笑者,他们就说:那个人与某人年龄相近,修养和学业也差不多"
|
||||
keyword_note = {"相若"="相近", "相似"="差不多"}
|
||||
|
||||
["位卑/则/足羞/, 官盛/则/近谀/.”/"]
|
||||
note = []
|
||||
translation = "以地位低的人为师,足以感到羞愧,称官位高的人为师就近于谄媚"
|
||||
keyword_note = {"位卑"="地位低", "足羞"="足以羞愧", "官盛"="官位高", "近谀"="近于谄媚"}
|
||||
|
||||
["呜呼!/ 师道/之/不复/, 可知/矣/./"]
|
||||
note = []
|
||||
translation = "啊!从师学习的风尚不能恢复,由此就可以知道了"
|
||||
keyword_note = {"不复"="不能恢复"}
|
||||
|
||||
["巫医/乐师/百工/之人/, 君子/不齿/, 今/其智/乃/反不能/及/, 其/可怪/也欤!/"]
|
||||
note = ["不齿:不屑与之同列,表示鄙视"]
|
||||
translation = "医生、乐师及各种工匠,士大夫之类的人是不屑与他们为伍的,现在士大夫们的智慧反而不如他们。难道值得奇怪吗"
|
||||
keyword_note = {"君子"="士大夫", "不齿"="不屑为伍", "乃"="反而", "及"="如"}
|
||||
|
||||
["圣人/无常/师/./ 孔子/师/郯子/、/苌弘/、/师襄/、/老聃/./"]
|
||||
note = ["郯子:春秋时郯国国君", "苌弘:周敬王大夫", "师襄:鲁国乐官", "老聃:即老子"]
|
||||
translation = "圣人没有固定的老师,孔子曾经以郯子、苌弘、师襄、老聃为师"
|
||||
keyword_note = {"常师"="固定的老师"}
|
||||
|
||||
["郯子/之徒/, 其/贤/不及/孔子/./"]
|
||||
note = []
|
||||
translation = "郯子这一类人,他们的道德才能不如孔子"
|
||||
keyword_note = {"之徒"="这一类人", "贤"="道德才能", "不及"="不如"}
|
||||
|
||||
["孔子/曰/:/三人/行/, 则/必有/我师/./"]
|
||||
note = []
|
||||
translation = "孔子说:几个人走在一起,其中就一定有我的老师"
|
||||
keyword_note = {"三人行"="几个人一起走"}
|
||||
|
||||
["是故/弟子/不必/不如/师/, 师/不必/贤于/弟子/, 闻道/有/先后/, 术业/有/专攻/, 如是/而已/./"]
|
||||
note = []
|
||||
translation = "因此学生不一定不如老师,老师也不一定比弟子强,听闻道理有先有后,学问和技艺上各有各的主攻方向,像这样罢了"
|
||||
keyword_note = {"不必"="不一定", "贤于"="比...强", "术业"="学问技艺", "专攻"="专门研究", "而已"="罢了"}
|
||||
|
||||
["李氏/子蟠/, 年/十七/, 好/古文/, 六艺/经传/皆/通习/之/, 不拘/于时/, 学/于余/./"]
|
||||
note = ["六艺经传:六经的经文和传文"]
|
||||
translation = "李蟠,十七岁,爱好古文,六经的经文和传文都普遍学习了,不被世俗的限制,向我学习"
|
||||
keyword_note = {"好"="爱好", "古文"="先秦文章", "六艺经传"="六经的经文和传文", "通习"="普遍学习", "不拘于时"="不被时俗限制"}
|
||||
|
||||
["余/嘉/其/能行/古道/, 作/《师说》/以/贻之/./"]
|
||||
note = []
|
||||
translation = "我赞许他能遵行古人从师学习的风尚,特别写了这篇《师说》来赠给他"
|
||||
keyword_note = {"嘉"="赞许", "古道"="古人风尚", "贻"="赠送"}
|
@@ -1,278 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import toml
|
||||
import time
|
||||
import auxiliary as aux
|
||||
from typing import List
|
||||
|
||||
class Electron:
|
||||
"""电子: 记忆分析元数据及算法"""
|
||||
algorithm = "SM-2" # 暂时使用 SM-2 算法进行记忆拟合, 考虑 SM-15 替代
|
||||
|
||||
def __init__(self, content: str, metadata: dict):
|
||||
self.content = content
|
||||
self.metadata = metadata
|
||||
if metadata == {}:
|
||||
# print("NULL")
|
||||
self._default_init()
|
||||
|
||||
def _default_init(self):
|
||||
defaults = {
|
||||
'efactor': 2.5, # 易度系数, 越大越简单, 最大为5
|
||||
'real_rept': 0, # (实际)重复次数
|
||||
'rept': 0, # (有效)重复次数
|
||||
'interval': 0, # 最佳间隔
|
||||
'last_date': 0, # 上一次复习的时间戳
|
||||
'next_date': 0, # 将要复习的时间戳
|
||||
'is_activated': 0, # 激活状态
|
||||
# *NOTE: 此处"时间戳"是以天为单位的整数, 即 UNIX 时间戳除以一天的秒数取整
|
||||
'last_modify': time.time() # 最后修改时间戳(此处是UNIX时间戳)
|
||||
}
|
||||
self.metadata = defaults
|
||||
|
||||
def activate(self):
|
||||
self.metadata['is_activated'] = 1
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def modify(self, var: str, value):
|
||||
if var in self.metadata:
|
||||
self.metadata[var] = value
|
||||
self.metadata['last_modify'] = time.time()
|
||||
else:
|
||||
print(f"警告: '{var}' 非已知元数据字段")
|
||||
|
||||
def revisor(self, quality: int = 5, is_new_activation: bool = False):
|
||||
"""SM-2 算法迭代决策机制实现
|
||||
根据 quality(0 ~ 5) 进行参数迭代最佳间隔
|
||||
quality 由主程序评估
|
||||
|
||||
Args:
|
||||
quality (int): 记忆保留率量化参数
|
||||
"""
|
||||
print(f"REVISOR: {quality}, {is_new_activation}")
|
||||
if quality == -1:
|
||||
return -1
|
||||
|
||||
self.metadata['efactor'] = self.metadata['efactor'] + (
|
||||
0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02)
|
||||
)
|
||||
self.metadata['efactor'] = max(1.3, self.metadata['efactor'])
|
||||
|
||||
if quality < 3:
|
||||
# 若保留率低于 3,重置重复次数
|
||||
self.metadata['rept'] = 0
|
||||
self.metadata['interval'] = 0 # 设为0,以便下面重新计算 I(1)
|
||||
else:
|
||||
self.metadata['rept'] += 1
|
||||
|
||||
self.metadata['real_rept'] += 1
|
||||
|
||||
if is_new_activation: # 初次激活
|
||||
self.metadata['rept'] = 0
|
||||
self.metadata['efactor'] = 2.5
|
||||
|
||||
if self.metadata['rept'] == 0: # 刚被重置或初次激活后复习
|
||||
self.metadata['interval'] = 1 # I(1)
|
||||
elif self.metadata['rept'] == 1:
|
||||
self.metadata['interval'] = 6 # I(2) 经验公式
|
||||
else:
|
||||
self.metadata['interval'] = round(
|
||||
self.metadata['interval'] * self.metadata['efactor']
|
||||
)
|
||||
|
||||
self.metadata['last_date'] = aux.get_daystamp()
|
||||
self.metadata['next_date'] = aux.get_daystamp() + self.metadata['interval']
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def __str__(self):
|
||||
return (
|
||||
f"记忆单元预览 \n"
|
||||
f"内容: '{self.content}' \n"
|
||||
f"易度系数: {self.metadata['efactor']:.2f} \n"
|
||||
f"已经重复的次数: {self.metadata['rept']} \n"
|
||||
f"下次间隔: {self.metadata['interval']} 天 \n"
|
||||
f"下次复习日期时间戳: {self.metadata['next_date']}"
|
||||
)
|
||||
|
||||
def __eq__(self, other):
|
||||
if self.content == other.content:
|
||||
return True
|
||||
return False
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.content)
|
||||
|
||||
def __getitem__(self, key):
|
||||
if key == "content":
|
||||
return self.content
|
||||
if key in self.metadata:
|
||||
return self.metadata[key]
|
||||
else:
|
||||
raise KeyError(f"Key '{key}' not found in metadata.")
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key == "content":
|
||||
raise AttributeError("content 应为只读")
|
||||
self.metadata[key] = value
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.metadata.keys()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.metadata)
|
||||
|
||||
@staticmethod
|
||||
def placeholder():
|
||||
return Electron("电子对象样例内容", {})
|
||||
|
||||
|
||||
class Nucleon:
|
||||
"""核子: 材料元数据"""
|
||||
|
||||
def __init__(self, content: str, data: dict):
|
||||
self.metadata = data
|
||||
self.content = content
|
||||
|
||||
def __getitem__(self, key):
|
||||
if key == "content":
|
||||
return self.content
|
||||
if key in self.metadata:
|
||||
return self.metadata[key]
|
||||
else:
|
||||
raise KeyError(f"Key '{key}' not found in metadata.")
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.metadata.keys()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.metadata)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.content)
|
||||
|
||||
@staticmethod
|
||||
def placeholder():
|
||||
return Nucleon("核子对象样例内容", {})
|
||||
|
||||
|
||||
class NucleonUnion():
|
||||
"""
|
||||
替代原有 NucleonFile 类, 支持复杂逻辑
|
||||
|
||||
Attributes:
|
||||
path (Path): 对应于 NucleonUnion 实例的文件路径。
|
||||
name (str): 核联对象的显示名称,从文件名中派生。
|
||||
nucleons (list): 内部核子对象的列表。
|
||||
nucleons_dict (dict): 内部核子对象的字典,以核子内容作为键。
|
||||
keydata (dict): 核子对象字典键名的翻译。
|
||||
testdata (dict): 记忆测试项目的元数据。
|
||||
|
||||
Parameters:
|
||||
path (Path): 包含核子数据的文件路径。
|
||||
"""
|
||||
|
||||
def __init__(self, path: pathlib.Path):
|
||||
self.path = path
|
||||
self.name = path.name.replace(path.suffix, "")
|
||||
with open(path, 'r') as f:
|
||||
all = toml.load(f)
|
||||
lst = list()
|
||||
for i in all.keys():
|
||||
if "attr" in i:
|
||||
continue
|
||||
if "data" in i:
|
||||
continue
|
||||
lst.append(Nucleon(i, all[i]))
|
||||
self.keydata = all["keydata"]
|
||||
self.testdata = all["testdata"]
|
||||
self.nucleons: List[Nucleon] = lst
|
||||
self.nucleons_dict = {i.content: i for i in lst}
|
||||
|
||||
def __len__(self):
|
||||
return len(self.nucleons)
|
||||
|
||||
def linked_electron_union(self):
|
||||
if (self.path.parent / '..' / 'electron' / self.path.name).exists():
|
||||
return ElectronUnion(self.path.parent / '..' / 'electron' / self.path.name)
|
||||
else:
|
||||
return 0
|
||||
|
||||
def save(self):
|
||||
with open(self.path, 'w') as f:
|
||||
tmp = {i.content: i.metadata for i in self.nucleons}
|
||||
toml.dump(tmp, f)
|
||||
|
||||
|
||||
class ElectronUnion:
|
||||
"""取代原有 ElectronFile 类, 以支持复杂逻辑"""
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
print(path)
|
||||
self.name = path.name.replace(path.suffix, "")
|
||||
with open(path, 'r') as f:
|
||||
all = toml.load(f)
|
||||
lst = list()
|
||||
for i in all.keys():
|
||||
if i != "total":
|
||||
lst.append(Electron(i, all[i]))
|
||||
self.total = all.get("total", {"last_date": 0})
|
||||
self.electrons = lst
|
||||
self.electrons_dict = {i.content: i for i in lst}
|
||||
|
||||
def sync(self):
|
||||
"""同步 electrons_dict 中新增对到 electrons 中, 仅用于缺省初始化不存在映射时调用"""
|
||||
self.electrons = self.electrons_dict.values()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.electrons)
|
||||
|
||||
def linked_nucleon_union(self):
|
||||
return NucleonUnion(self.path.parent / '..' / 'nucleon' / self.path.name)
|
||||
|
||||
def save(self):
|
||||
# print(1)
|
||||
self.total["last_date"] = aux.get_daystamp()
|
||||
with open(self.path, 'w') as f:
|
||||
tmp = {i.content: i.metadata for i in self.electrons}
|
||||
tmp["total"] = self.total
|
||||
# print(tmp)
|
||||
toml.dump(tmp, f)
|
||||
|
||||
|
||||
class Atom:
|
||||
@staticmethod
|
||||
def placeholder():
|
||||
return (Electron.placeholder(), Nucleon.placeholder(), {})
|
||||
|
||||
@staticmethod
|
||||
def advanced_placeholder():
|
||||
return (
|
||||
Electron("两只黄鹤鸣翠柳", {}),
|
||||
Nucleon(
|
||||
"两只黄鹤鸣翠柳",
|
||||
{
|
||||
"note": [],
|
||||
"translation": "臣子李密陈言:我因命运不好,小时候遭遇到了不幸",
|
||||
"keyword_note": {
|
||||
"险衅": "凶险祸患(这里指命运不好)",
|
||||
"夙": "早时,这里指年幼的时候",
|
||||
"闵": "通'悯',指可忧患的事",
|
||||
"凶": "不幸,指丧父"
|
||||
}
|
||||
}
|
||||
),
|
||||
{
|
||||
"keydata": {
|
||||
"note": "笔记",
|
||||
"keyword_note": "关键词翻译",
|
||||
"translation": "语句翻译"
|
||||
},
|
||||
"testdata": {
|
||||
"additional_inf": ["translation", "note", "keyword_note"],
|
||||
"fill_blank_test": ["translation"],
|
||||
"draw_card_test": ["keyword_note"]
|
||||
},
|
||||
"is_new_activation": 0
|
||||
}
|
||||
)
|
@@ -1 +0,0 @@
|
||||
# HeurSync 同步器
|
@@ -1,58 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# 音频预缓存实用程序(旧版), 独立于主程序之外, 但依赖其他组件
|
||||
import particles as pt
|
||||
import auxiliary as aux
|
||||
import edge_tts as tts
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import time
|
||||
|
||||
|
||||
def precache(text: str):
|
||||
"""预缓存单个文本的音频"""
|
||||
cache_dir = Path("./cache/voice/")
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache = cache_dir / f"{aux.get_md5(text)}.wav"
|
||||
if not cache.exists():
|
||||
communicate = tts.Communicate(text, "zh-CN-XiaoxiaoNeural")
|
||||
communicate.save_sync(f"./cache/voice/{aux.get_md5(text)}.wav")
|
||||
|
||||
|
||||
def proc_file(path: Path):
|
||||
"""处理单个文件"""
|
||||
nu = pt.NucleonUnion(path)
|
||||
c = 0
|
||||
for i in nu.nucleons:
|
||||
c += 1
|
||||
print(f"预缓存 [{nu.name}] ({c}/{len(nu)}): {i['content'].replace('/', '')}")
|
||||
precache(i['content'].replace('/', ''))
|
||||
|
||||
|
||||
def walk(path_str: str):
|
||||
"""遍历目录处理所有文件"""
|
||||
path = Path(path_str)
|
||||
print(f"正在遍历目录: {path}")
|
||||
try:
|
||||
for item in path.iterdir():
|
||||
if item.is_file() and item.suffix == ".toml":
|
||||
print(f"正预缓存文件: {item.name}")
|
||||
proc_file(item)
|
||||
elif item.is_dir():
|
||||
print(f"进入目录: {item.name}")
|
||||
except:
|
||||
print("发生一个异常, 于 5 秒后自动重新下载")
|
||||
time.sleep(5)
|
||||
walk(path_str)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("音频预缓存实用程序(旧版)")
|
||||
print("A: 全部缓存")
|
||||
print("C: 清空缓存")
|
||||
|
||||
choice = input("输入选项 $ ").upper()
|
||||
|
||||
if choice == "A":
|
||||
walk("./nucleon")
|
||||
elif choice == "C":
|
||||
shutil.rmtree("./cache/voice", ignore_errors=True)
|
||||
print("缓存已清空")
|
@@ -1,122 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import random
|
||||
|
||||
|
||||
class BasePuzzle:
|
||||
pass
|
||||
|
||||
|
||||
class BlankPuzzle(BasePuzzle):
|
||||
"""填空题谜题生成器
|
||||
|
||||
Args:
|
||||
text: 原始字符串(需要 "/" 分割句子, 末尾应有 "/")
|
||||
min_denominator: 最小概率倒数(如占所有可生成填空数的 1/7 中的 7, 若期望值小于 1, 则取 1)
|
||||
"""
|
||||
|
||||
def __init__(self, text: str, min_denominator: int):
|
||||
self.text = text
|
||||
self.min_denominator = min_denominator
|
||||
self.wording = "填空题 - 尚未刷新谜题"
|
||||
self.answer = ["填空题 - 尚未刷新谜题"]
|
||||
|
||||
def refresh(self): # 刷新谜题
|
||||
placeholder = "___SLASH___"
|
||||
tmp_text = self.text.replace("/", placeholder)
|
||||
words = tmp_text.split(placeholder)
|
||||
if not words:
|
||||
return
|
||||
words = [word for word in words if word]
|
||||
num_blanks = min(max(1, len(words) // self.min_denominator), len(words))
|
||||
indices_to_blank = random.sample(range(len(words)), num_blanks)
|
||||
indices_to_blank.sort()
|
||||
blanked_words = list(words)
|
||||
answer = list()
|
||||
for index in indices_to_blank:
|
||||
blanked_words[index] = "__" * len(words[index])
|
||||
answer.append(words[index])
|
||||
self.answer = answer
|
||||
self.wording = "".join(blanked_words)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.wording}\n{str(self.answer)}"
|
||||
|
||||
|
||||
class SelectionPuzzle(BasePuzzle):
|
||||
"""选择题谜题生成器
|
||||
|
||||
Args:
|
||||
mapping: 正确选项映射 {问题: 答案}
|
||||
jammer: 干扰项列表
|
||||
max_riddles_num: 最大生成谜题数 (默认2个)
|
||||
prefix: 问题前缀
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
mapping: dict,
|
||||
jammer: list,
|
||||
max_riddles_num: int = 2,
|
||||
prefix: str = ""
|
||||
):
|
||||
self.prefix = prefix
|
||||
self.mapping = mapping
|
||||
self.jammer = list(set(jammer + list(mapping.values())))
|
||||
while len(self.jammer) < 4:
|
||||
self.jammer.append(" ")
|
||||
self.max_riddles_num = max(1, min(max_riddles_num, 5))
|
||||
self.wording = "选择题 - 尚未刷新谜题"
|
||||
self.answer = ["选择题 - 尚未刷新谜题"]
|
||||
self.options = []
|
||||
|
||||
def refresh(self):
|
||||
"""刷新谜题,根据题目数量生成适当数量的谜题"""
|
||||
if not self.mapping:
|
||||
self.wording = "无可用题目"
|
||||
self.answer = ["无答案"]
|
||||
self.options = []
|
||||
return
|
||||
|
||||
num_questions = min(self.max_riddles_num, len(self.mapping))
|
||||
questions = random.sample(list(self.mapping.items()), num_questions)
|
||||
puzzles = []
|
||||
answers = []
|
||||
all_options = []
|
||||
|
||||
for question, correct_answer in questions:
|
||||
options = [correct_answer]
|
||||
available_jammers = [
|
||||
j for j in self.jammer if j != correct_answer
|
||||
]
|
||||
if len(available_jammers) >= 3:
|
||||
selected_jammers = random.sample(available_jammers, 3)
|
||||
else:
|
||||
selected_jammers = random.choices(available_jammers, k=3)
|
||||
options.extend(selected_jammers)
|
||||
random.shuffle(options)
|
||||
puzzles.append(question)
|
||||
answers.append(correct_answer)
|
||||
all_options.append(options)
|
||||
|
||||
question_texts = []
|
||||
for i, puzzle in enumerate(puzzles):
|
||||
question_texts.append(f"{self.prefix}:\n {i+1}. {puzzle}")
|
||||
|
||||
self.wording = question_texts
|
||||
self.answer = answers
|
||||
self.options = all_options
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.wording}\n正确答案: {', '.join(self.answer)}"
|
||||
|
||||
if __name__ == "__main__":
|
||||
puz = SelectionPuzzle(
|
||||
{"1+1": "2", "1+2": "3", "1+3": "4"},
|
||||
["2", "5", "0"],
|
||||
3,
|
||||
'求值: '
|
||||
)
|
||||
puz.refresh()
|
||||
print(puz.wording)
|
||||
print(puz.answer)
|
||||
print(puz.options)
|
@@ -1,198 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import typing
|
||||
import particles as pt
|
||||
import pathlib
|
||||
import auxiliary as aux
|
||||
import compositions as comps
|
||||
import random
|
||||
#from pprint import pprint as print # debug
|
||||
|
||||
class Glimpse():
|
||||
"""轻量级只读, 用于状态指示"""
|
||||
def __init__(self, nucleon_union: pt.NucleonUnion):
|
||||
self.name = nucleon_union.name
|
||||
self.nuc_u = nucleon_union
|
||||
self.elt_u = self.nuc_u.linked_electron_union()
|
||||
self.lastest_date = -1
|
||||
self.next_date = 0x3f3f3f3f
|
||||
self.avg_efactor = 0
|
||||
self.total_num = 0
|
||||
self.activated_num = 0
|
||||
self.is_initialized = 0
|
||||
if self.elt_u != 0:
|
||||
self.is_initialized = 1
|
||||
self.total_num = len(self.elt_u.electrons)
|
||||
for i in self.elt_u.electrons:
|
||||
if i['next_date'] > 0:
|
||||
self.next_date = min(self.next_date, i['next_date'])
|
||||
self.lastest_date = max(self.lastest_date, i['last_date'])
|
||||
if i['is_activated']:
|
||||
self.avg_efactor += i['efactor']
|
||||
self.activated_num += 1
|
||||
if self.next_date == 0x3f3f3f3f:
|
||||
self.next_date = -1
|
||||
self.is_initialized = 0
|
||||
if self.activated_num == 0:
|
||||
return
|
||||
self.avg_efactor = round(self.avg_efactor / self.activated_num, 2)
|
||||
if self.next_date == 0x3f3f3f3f:
|
||||
self.next_date = -1
|
||||
return
|
||||
|
||||
class Apparatus():
|
||||
"""反应器对象, 决策一个原子的不同记忆方式, 并反馈到布局"""
|
||||
def __init__(self, screen, reactor, atom, is_review = 0):
|
||||
self.electron: pt.Electron = atom[0]
|
||||
self.nucleon: pt.Nucleon = atom[1]
|
||||
self.positron: dict = atom[2]
|
||||
self.testdata = self.positron["testdata"]
|
||||
self.procession: typing.List[comps.Composition] = list()
|
||||
if self.positron["is_new_activation"] == 1:
|
||||
self.positron["is_new_activation"] = 0
|
||||
self.procession.append(comps.registry["recognition"](screen, reactor, atom))
|
||||
return
|
||||
for i in self.positron["testdata"].keys():
|
||||
if i == "additional_inf":
|
||||
continue
|
||||
if i == "fill_blank_test": # 加深
|
||||
self.procession.append(comps.registry[i](screen, reactor, atom))
|
||||
# self.procession.append(comps.registry[i](screen, reactor, atom))
|
||||
self.procession.append(comps.registry[i](screen, reactor, atom))
|
||||
# self.procession.reverse()
|
||||
random.shuffle(self.procession)
|
||||
if self.positron["is_new_activation"] == 0:
|
||||
self.procession.append(comps.registry['recognition'](screen, reactor, atom))
|
||||
if is_review == 1:
|
||||
self.procession = [self.procession[-2], self.procession[-1]]
|
||||
def iterator(self):
|
||||
yield from self.procession
|
||||
|
||||
|
||||
class Reactor():
|
||||
"""反应堆对象, 处理和分配一次文件记忆流程的资源与策略"""
|
||||
def __init__(self, nucleon_file: pt.NucleonUnion, electron_file: pt.ElectronUnion, screen, tasked_num):
|
||||
# 导入原子对象
|
||||
self.stage = 0
|
||||
self.nucleon_file = nucleon_file
|
||||
self.electron_file = electron_file
|
||||
self.tasked_num = tasked_num
|
||||
self.atoms_new = list()
|
||||
self.atoms_review = list()
|
||||
counter = self.tasked_num
|
||||
self.screen = screen
|
||||
self.electron_dict = electron_file.electrons_dict
|
||||
self.quality_dict = {}
|
||||
|
||||
def electron_dict_get_fallback(key) -> pt.Electron:
|
||||
value = self.electron_dict.get(key)
|
||||
# 如果值不存在,则设置默认值
|
||||
if value is None:
|
||||
value = pt.Electron(key, {}) # 获取默认值
|
||||
self.electron_dict[key] = value # 将默认值存入字典
|
||||
electron_file.sync()
|
||||
return value # 返回获取的值(可能是默认值)
|
||||
|
||||
for nucleon in nucleon_file.nucleons:
|
||||
# atom = (Electron, Nucleon, Positron) 即 (记忆元数据, 内容元数据, 运行时数据)
|
||||
atom = (electron_dict_get_fallback(nucleon.content), nucleon, {}) # 使用 "Positron" 代称 atom[2]
|
||||
atom[2]["testdata"] = nucleon_file.testdata
|
||||
atom[2]["keydata"] = nucleon_file.keydata
|
||||
if atom[0]["is_activated"] == 0:
|
||||
if counter > 0:
|
||||
atom[2]["is_new_activation"] = 1
|
||||
atom[0]["is_activated"] = 1
|
||||
self.atoms_new.append(atom)
|
||||
counter -= 1
|
||||
else:
|
||||
atom[2]["is_new_activation"] = 0
|
||||
if int(atom[0]["next_date"]) <= aux.get_daystamp():
|
||||
atom[0]["last_date"] = aux.get_daystamp()
|
||||
self.atoms_review.append(atom)
|
||||
# 设置运行时
|
||||
self.index: int
|
||||
self.procession: list
|
||||
self.failed: list
|
||||
self.round_title: str
|
||||
self.current_atom: typing.Tuple[pt.Electron, pt.Nucleon, dict]
|
||||
self.round_set = 0
|
||||
self.current_atom = pt.Atom.placeholder()
|
||||
#print(self.atoms_new)
|
||||
|
||||
def set_round(self, title, procession):
|
||||
self.round_set = 1
|
||||
self.round_title = title
|
||||
self.procession = procession
|
||||
self.failed = list()
|
||||
self.index = -1
|
||||
|
||||
def set_round_templated(self, stage):
|
||||
titles = {
|
||||
1: "复习模式",
|
||||
2: "新记忆模式",
|
||||
3: "总复习模式"
|
||||
}
|
||||
processions = {
|
||||
1: self.atoms_review,
|
||||
2: self.atoms_new,
|
||||
3: (self.atoms_new + self.atoms_review)
|
||||
}
|
||||
self.stage = stage
|
||||
ret = 1
|
||||
if stage == 1 and len(processions[1]) == 0:
|
||||
stage = 2
|
||||
ret = 2
|
||||
if stage == 1 and len(processions[2]) == 0:
|
||||
stage = 3
|
||||
ret = 3
|
||||
self.set_round(title=titles[stage], procession=processions[stage])
|
||||
return ret
|
||||
|
||||
def forward(self, step = 1):
|
||||
"""
|
||||
返回值规则:
|
||||
1: 重定向至 failed
|
||||
-1: 此轮已完成
|
||||
0: 下一个记忆单元
|
||||
"""
|
||||
if self.index + step >= len(self.procession):
|
||||
if len(self.failed) > 0:
|
||||
self.procession = self.failed
|
||||
self.index = -1
|
||||
self.forward(step)
|
||||
if "- 额外复习" not in self.round_title:
|
||||
self.round_title += " - 额外复习"
|
||||
self.failed = list()
|
||||
return 1 # 自动重定向到 failed
|
||||
else:
|
||||
self.round_set = 0
|
||||
return -1 # 此轮已完成
|
||||
self.index += step
|
||||
self.current_atom = self.procession[self.index]
|
||||
self.current_appar = Apparatus(self.screen, self, self.current_atom, (self.stage == 1)).iterator()
|
||||
return 0
|
||||
|
||||
def save(self):
|
||||
self._deploy_report()
|
||||
print("Progress saved")
|
||||
# self.nucleon_file.save()
|
||||
if self.electron_file.total["last_date"] < aux.get_daystamp():
|
||||
self.electron_file.save()
|
||||
|
||||
def _deploy_report(self):
|
||||
"部署所有 _report"
|
||||
for e, q in self.quality_dict.items():
|
||||
if q == -1:
|
||||
e.revisor(5, True)
|
||||
continue
|
||||
e.revisor(q)
|
||||
|
||||
def report(self, atom, quality):
|
||||
"向反应器和最低质量记录汇报"
|
||||
if atom in self.atoms_new:
|
||||
self.quality_dict[atom[0]] = -1
|
||||
print(self.quality_dict)
|
||||
return
|
||||
self.quality_dict[atom[0]] = min(quality, self.quality_dict.get(atom[0], 5))
|
||||
if quality <= 3:
|
||||
self.failed.append(atom)
|
||||
print(self.quality_dict)
|
@@ -1,77 +0,0 @@
|
||||
# reactor.py 设计改进型 尚未完成功能重构
|
||||
import particles as pt
|
||||
import auxiliary as aux
|
||||
import time
|
||||
from typing import List
|
||||
|
||||
class BaseScheduler():
|
||||
"调度器接口"
|
||||
|
||||
def revisor(self, electron: pt.Electron, quality: int):
|
||||
"""由 quality 更新电子的记忆参数"""
|
||||
pass
|
||||
|
||||
def get_atoms_for_review(self, electron_file: pt.ElectronUnion):
|
||||
"""从电子文件中筛选出当前需要复习的所有原子"""
|
||||
pass
|
||||
|
||||
def get_atoms_for_learning(self, nucleon_file: pt.NucleonUnion, limit: int):
|
||||
"""从核子文件中获取待学习的新原子"""
|
||||
pass
|
||||
|
||||
class SM2Scheduler(BaseScheduler):
|
||||
"基于 SM-2 的调度器实现"
|
||||
def revisor(self, electron: pt.Electron, quality: int, is_new_activation):
|
||||
print(f"REVISOR: {quality}, {is_new_activation}")
|
||||
if quality == -1:
|
||||
return -1
|
||||
|
||||
electron.metadata['efactor'] = electron.metadata['efactor'] + (
|
||||
0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02)
|
||||
)
|
||||
electron.metadata['efactor'] = max(1.3, electron.metadata['efactor'])
|
||||
|
||||
if quality < 3:
|
||||
# 若保留率低于 3,重置重复次数
|
||||
electron.metadata['rept'] = 0
|
||||
electron.metadata['interval'] = 0 # 设为0,以便下面重新计算 I(1)
|
||||
else:
|
||||
electron.metadata['rept'] += 1
|
||||
|
||||
electron.metadata['real_rept'] += 1
|
||||
|
||||
if is_new_activation: # 初次激活
|
||||
electron.metadata['rept'] = 0
|
||||
electron.metadata['efactor'] = 2.5
|
||||
|
||||
if electron.metadata['rept'] == 0: # 刚被重置或初次激活后复习
|
||||
electron.metadata['interval'] = 1 # I(1)
|
||||
elif electron.metadata['rept'] == 1:
|
||||
electron.metadata['interval'] = 6 # I(2) 经验公式
|
||||
else:
|
||||
electron.metadata['interval'] = round(
|
||||
electron.metadata['interval'] * electron.metadata['efactor']
|
||||
)
|
||||
|
||||
electron.metadata['last_date'] = aux.get_daystamp()
|
||||
electron.metadata['next_date'] = aux.get_daystamp() + electron.metadata['interval']
|
||||
electron.metadata['last_modify'] = time.time()
|
||||
|
||||
def get_atoms_for_learning(self, nucleon_file: pt.NucleonUnion, limit: int):
|
||||
def electron_dict_get_fallback(key) -> pt.Electron:
|
||||
value = self.electron_dict.get(key)
|
||||
# 如果值不存在,则设置默认值
|
||||
if value is None:
|
||||
value = pt.Electron(key, {}) # 获取默认值
|
||||
self.electron_dict[key] = value # 将默认值存入字典
|
||||
electron_file.sync()
|
||||
return value # 返回获取的值(可能是默认值)
|
||||
|
||||
for i in nucleon_file.nucleons:
|
||||
if i.metadata
|
||||
|
||||
def get_atoms_for_review(self, electron_file: pt.ElectronUnion):
|
||||
return super().get_atoms_for_review(electron_file)
|
||||
|
||||
class FSRSScheduler():
|
||||
"基于 FSRS 的调度器实现"
|
Binary file not shown.
Before Width: | Height: | Size: 120 KiB |
Binary file not shown.
Before Width: | Height: | Size: 559 KiB |
Binary file not shown.
Before Width: | Height: | Size: 177 KiB |
Binary file not shown.
Before Width: | Height: | Size: 161 KiB |
@@ -1,8 +0,0 @@
|
||||
aiohttp==3.12.13
|
||||
aiohttp_jinja2==1.6
|
||||
edge_tts==7.0.2
|
||||
Jinja2==3.1.6
|
||||
playsound==1.2.2
|
||||
rich==14.1.0
|
||||
textual==5.0.1
|
||||
toml==0.10.2
|
@@ -1,552 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.widgets import (
|
||||
Header,
|
||||
Footer,
|
||||
Input,
|
||||
ListView,
|
||||
ProgressBar,
|
||||
DirectoryTree,
|
||||
ListItem,
|
||||
Label,
|
||||
Markdown,
|
||||
Static,
|
||||
Button,
|
||||
Select,
|
||||
)
|
||||
from textual.containers import Container, Horizontal, Center
|
||||
from textual.screen import Screen
|
||||
from textual.worker import Worker, get_current_worker
|
||||
import pathlib
|
||||
import threading
|
||||
from playsound import playsound
|
||||
import particles as pt
|
||||
from reactor import Reactor, Apparatus, Glimpse
|
||||
import auxiliary as aux
|
||||
import compositions as compo
|
||||
import builtins
|
||||
import metadata
|
||||
import time
|
||||
import shutil
|
||||
|
||||
config = aux.ConfigFile("config.toml")
|
||||
|
||||
class PrecachingScreen(Screen):
|
||||
"""预缓存音频文件屏幕"""
|
||||
BINDINGS = [("q", "go_back", "返回"), ("escape", "quit_app", "退出")]
|
||||
|
||||
def __init__(self, nucleon_file = None):
|
||||
super().__init__(name=None, id=None, classes=None)
|
||||
self.nucleon_file = nucleon_file
|
||||
self.is_precaching = False
|
||||
self.current_file = ""
|
||||
self.current_item = ""
|
||||
self.progress = 0
|
||||
self.total = 0
|
||||
self.processed = 0
|
||||
self.precache_worker = None
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
with Container(id="precache_container"):
|
||||
yield Label("[b]音频预缓存[/b]", classes="title-label")
|
||||
|
||||
if self.nucleon_file:
|
||||
yield Static(f"目标单元集: [b]{self.nucleon_file.name}[/b]", classes="target-info")
|
||||
yield Static(f"单元数量: {len(self.nucleon_file.nucleons)}", classes="target-info")
|
||||
else:
|
||||
yield Static("目标: 所有单元集", classes="target-info")
|
||||
|
||||
yield Static(id="status", classes="status-info")
|
||||
yield Static(id="current_item", classes="current-item")
|
||||
yield ProgressBar(total=100, show_eta=False, id="progress_bar")
|
||||
|
||||
with Horizontal(classes="button-group"):
|
||||
if not self.is_precaching:
|
||||
yield Button("开始预缓存", id="start_precache", variant="primary")
|
||||
else:
|
||||
yield Button("取消预缓存", id="cancel_precache", variant="error")
|
||||
yield Button("清空缓存", id="clear_cache", variant="warning")
|
||||
yield Button("返回", id="go_back", variant="default")
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self):
|
||||
"""挂载时初始化状态"""
|
||||
self.update_status("就绪", "等待开始...")
|
||||
|
||||
def update_status(self, status, current_item="", progress=None):
|
||||
"""更新状态显示"""
|
||||
status_widget = self.query_one("#status", Static)
|
||||
item_widget = self.query_one("#current_item", Static)
|
||||
progress_bar = self.query_one("#progress_bar", ProgressBar)
|
||||
|
||||
status_widget.update(f"状态: {status}")
|
||||
item_widget.update(f"当前项目: {current_item}" if current_item else "")
|
||||
|
||||
if progress is not None:
|
||||
progress_bar.progress = progress
|
||||
progress_bar.advance(0) # 刷新显示
|
||||
|
||||
def precache_single_text(self, text: str):
|
||||
"""预缓存单个文本的音频"""
|
||||
cache_dir = pathlib.Path("./cache/voice/")
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache = cache_dir / f"{aux.get_md5(text)}.wav"
|
||||
if not cache.exists():
|
||||
try:
|
||||
import edge_tts as tts
|
||||
communicate = tts.Communicate(text, "zh-CN-XiaoxiaoNeural")
|
||||
communicate.save_sync(str(cache))
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"预缓存失败 '{text}': {e}")
|
||||
return False
|
||||
return True
|
||||
|
||||
def precache_file(self, nucleon_union: pt.NucleonUnion):
|
||||
"""预缓存单个文件的所有内容"""
|
||||
self.current_file = nucleon_union.name
|
||||
total_items = len(nucleon_union.nucleons)
|
||||
|
||||
for idx, nucleon in enumerate(nucleon_union.nucleons):
|
||||
# 检查是否被取消
|
||||
worker = get_current_worker()
|
||||
if worker and worker.is_cancelled:
|
||||
return False
|
||||
|
||||
text = nucleon['content'].replace('/', '')
|
||||
self.current_item = text[:50] + "..." if len(text) > 50 else text
|
||||
self.processed += 1
|
||||
|
||||
# 更新进度
|
||||
progress = int((self.processed / self.total) * 100) if self.total > 0 else 0
|
||||
self.update_status(
|
||||
f"处理中: {nucleon_union.name} ({idx+1}/{total_items})",
|
||||
self.current_item,
|
||||
progress
|
||||
)
|
||||
|
||||
# 预缓存音频
|
||||
success = self.precache_single_text(text)
|
||||
if not success:
|
||||
self.update_status("错误", f"处理失败: {self.current_item}")
|
||||
time.sleep(1) # 短暂暂停以便用户看到错误信息
|
||||
|
||||
return True
|
||||
|
||||
def precache_all_files(self):
|
||||
"""预缓存所有文件"""
|
||||
nucleon_path = pathlib.Path("./nucleon")
|
||||
nucleon_files = [f for f in nucleon_path.iterdir() if f.suffix == ".toml"]
|
||||
|
||||
# 计算总项目数
|
||||
self.total = 0
|
||||
for file in nucleon_files:
|
||||
try:
|
||||
nu = pt.NucleonUnion(file)
|
||||
self.total += len(nu.nucleons)
|
||||
except:
|
||||
continue
|
||||
|
||||
self.processed = 0
|
||||
self.is_precaching = True
|
||||
|
||||
for file in nucleon_files:
|
||||
try:
|
||||
nu = pt.NucleonUnion(file)
|
||||
if not self.precache_file(nu):
|
||||
break # 用户取消
|
||||
except Exception as e:
|
||||
print(f"处理文件失败 {file}: {e}")
|
||||
continue
|
||||
|
||||
self.is_precaching = False
|
||||
self.update_status("完成", "所有音频文件已预缓存", 100)
|
||||
|
||||
def precache_single_file(self):
|
||||
"""预缓存单个文件"""
|
||||
if not self.nucleon_file:
|
||||
return
|
||||
|
||||
self.total = len(self.nucleon_file.nucleons)
|
||||
self.processed = 0
|
||||
self.is_precaching = True
|
||||
|
||||
success = self.precache_file(self.nucleon_file)
|
||||
|
||||
self.is_precaching = False
|
||||
if success:
|
||||
self.update_status("完成", f"'{self.nucleon_file.name}' 音频文件已预缓存", 100)
|
||||
else:
|
||||
self.update_status("已取消", "预缓存操作被用户取消", 0)
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
if event.button.id == "start_precache" and not self.is_precaching:
|
||||
# 开始预缓存
|
||||
if self.nucleon_file:
|
||||
self.precache_worker = self.run_worker(self.precache_single_file, thread=True)
|
||||
else:
|
||||
self.precache_worker = self.run_worker(self.precache_all_files, thread=True)
|
||||
|
||||
elif event.button.id == "cancel_precache" and self.is_precaching:
|
||||
# 取消预缓存
|
||||
if self.precache_worker:
|
||||
self.precache_worker.cancel()
|
||||
self.is_precaching = False
|
||||
self.update_status("已取消", "预缓存操作被用户取消", 0)
|
||||
|
||||
elif event.button.id == "clear_cache":
|
||||
# 清空缓存
|
||||
try:
|
||||
shutil.rmtree("./cache/voice", ignore_errors=True)
|
||||
self.update_status("已清空", "音频缓存已清空", 0)
|
||||
except Exception as e:
|
||||
self.update_status("错误", f"清空缓存失败: {e}")
|
||||
|
||||
elif event.button.id == "go_back":
|
||||
self.action_go_back()
|
||||
|
||||
def action_go_back(self):
|
||||
if self.is_precaching and self.precache_worker:
|
||||
self.precache_worker.cancel()
|
||||
self.app.pop_screen()
|
||||
|
||||
def action_quit_app(self):
|
||||
if self.is_precaching and self.precache_worker:
|
||||
self.precache_worker.cancel()
|
||||
self.app.exit()
|
||||
|
||||
class MemScreen(Screen):
|
||||
BINDINGS = [
|
||||
("d", "toggle_dark", "改变色调"),
|
||||
("q", "pop_screen", "返回主菜单"),
|
||||
("v", "play_voice", "朗读"),
|
||||
# ("p", "precache_current", "预缓存当前单元集"), # 新增预缓存快捷键
|
||||
]
|
||||
if config.get("quick_pass"):
|
||||
BINDINGS.append(("k", "quick_pass", "快速通过[调试]"))
|
||||
btn = dict()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
nucleon_file: pt.NucleonUnion,
|
||||
electron_file: pt.ElectronUnion,
|
||||
tasked_num,
|
||||
):
|
||||
super().__init__(name=None, id=None, classes=None)
|
||||
self.nucleon_file = nucleon_file
|
||||
self.electron_file = electron_file
|
||||
self.reactor = Reactor(nucleon_file, electron_file, self, tasked_num)
|
||||
self.stage = 1
|
||||
self.stage += self.reactor.set_round_templated(self.stage)
|
||||
first_forward = self.reactor.forward()
|
||||
print(first_forward)
|
||||
if first_forward == -1:
|
||||
self.stage = 3
|
||||
self.reactor.set_round_templated(3)
|
||||
print(self.reactor.forward())
|
||||
#self._forward_judge(first_forward)
|
||||
self.compo = next(self.reactor.current_appar)
|
||||
self.feedback_state = 0 # 默认状态
|
||||
self.feedback_state_map = {
|
||||
0: "",
|
||||
255: "回答有误, 请重试. 或者重新学习此单元",
|
||||
}
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
if type(self.compo).__name__ == "Recognition":
|
||||
self.action_play_voice()
|
||||
yield Header(show_clock=True)
|
||||
with Center():
|
||||
yield Static(
|
||||
f"当前进度: {len(self.reactor.procession) - self.reactor.index}/{len(self.reactor.procession)}"
|
||||
)
|
||||
yield Label(self.feedback_state_map[self.feedback_state])
|
||||
yield from self.compo.compose()
|
||||
if self.feedback_state == 255:
|
||||
yield Button("重新学习此单元", id="re-recognize", variant="warning")
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self):
|
||||
pass
|
||||
|
||||
def on_button_pressed(self, event):
|
||||
try:
|
||||
if event.button.id == "re-recognize":
|
||||
return
|
||||
except:
|
||||
pass
|
||||
ret = self.compo.handler(event, "button")
|
||||
self._forward_judge(ret)
|
||||
def _forward_judge(self, ret):
|
||||
self.feedback_state = 0
|
||||
if ret == -1:
|
||||
return
|
||||
if ret == 0:
|
||||
try:
|
||||
self.compo = next(self.reactor.current_appar)
|
||||
self.refresh_ui()
|
||||
except StopIteration:
|
||||
nxt = self.reactor.forward(1)
|
||||
try:
|
||||
self.compo = next(self.reactor.current_appar)
|
||||
except:
|
||||
pass
|
||||
if nxt == -1:
|
||||
if self.reactor.round_set == 0:
|
||||
if self.stage == 4:
|
||||
if config.get("save"):
|
||||
self.reactor.save()
|
||||
self.compo = compo.Finished(
|
||||
self, None, pt.Atom.placeholder()
|
||||
)
|
||||
self.refresh_ui()
|
||||
else:
|
||||
self.reactor.set_round_templated(self.stage)
|
||||
self.reactor.forward(1)
|
||||
self.stage += 1
|
||||
self.compo = next(self.reactor.current_appar)
|
||||
self.refresh_ui()
|
||||
return
|
||||
return
|
||||
else:
|
||||
self.refresh_ui()
|
||||
return
|
||||
if ret >= 1:
|
||||
if ret == 2:
|
||||
self.feedback_state = 255 # 表示错误
|
||||
else:
|
||||
self.feedback_state = 0
|
||||
self.refresh_ui()
|
||||
return
|
||||
|
||||
def refresh_ui(self):
|
||||
self.call_later(self.recompose)
|
||||
print(type(self.compo).__name__)
|
||||
|
||||
def action_play_voice(self):
|
||||
def play():
|
||||
cache_dir = pathlib.Path(f"./cache/voice/")
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache = cache_dir / f"{aux.get_md5(self.reactor.current_atom[1].content.replace('/',''))}.wav"
|
||||
if not cache.exists():
|
||||
import edge_tts as tts
|
||||
communicate = tts.Communicate(
|
||||
self.reactor.current_atom[1].content.replace("/", ""),
|
||||
"zh-CN-XiaoxiaoNeural",
|
||||
)
|
||||
communicate.save_sync(
|
||||
f"./cache/voice/{aux.get_md5(self.reactor.current_atom[1].content.replace('/',''))}.wav"
|
||||
)
|
||||
playsound(str(cache))
|
||||
|
||||
threading.Thread(target=play).start()
|
||||
|
||||
def action_precache_current(self):
|
||||
"""预缓存当前单元集的音频"""
|
||||
precache_screen = PrecachingScreen(self.nucleon_file)
|
||||
self.app.push_screen(precache_screen)
|
||||
|
||||
def action_quick_pass(self):
|
||||
self.reactor.report(self.reactor.current_atom, 5)
|
||||
self._forward_judge(0)
|
||||
def action_toggle_dark(self):
|
||||
self.app.action_toggle_dark()
|
||||
|
||||
def action_pop_screen(self):
|
||||
self.app.pop_screen()
|
||||
|
||||
class PreparationScreen(Screen):
|
||||
BINDINGS = [
|
||||
("q", "go_back", "返回"),
|
||||
("escape", "quit_app", "退出"),
|
||||
("p", "precache", "预缓存音频"), # 新增预缓存快捷键
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self, nucleon_file: pt.NucleonUnion, electron_file: pt.ElectronUnion
|
||||
) -> None:
|
||||
super().__init__(name=None, id=None, classes=None)
|
||||
self.nucleon_file = nucleon_file
|
||||
self.electron_file = electron_file
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
with Container(id="vice_container"):
|
||||
yield Label(f"准备就绪: [b]{self.nucleon_file.name}[/b]\n")
|
||||
yield Label(f"内容源文件对象: ./nucleon/[b]{self.nucleon_file.name}[/b].toml")
|
||||
yield Label(f"元数据文件对象: ./electron/[b]{self.electron_file.name}[/b].toml")
|
||||
yield Label(f"\n单元数量:{len(self.nucleon_file)}\n")
|
||||
|
||||
yield Button(
|
||||
"开始记忆",
|
||||
id="start_memorizing_button",
|
||||
variant="primary",
|
||||
classes="start-button",
|
||||
)
|
||||
yield Button(
|
||||
"预缓存音频",
|
||||
id="precache_button",
|
||||
variant="success",
|
||||
classes="precache-button",
|
||||
)
|
||||
|
||||
yield Static(f"\n单元预览:\n")
|
||||
yield Markdown(self._get_full_content().replace("/", ""), classes="full")
|
||||
yield Footer()
|
||||
|
||||
def _get_full_content(self):
|
||||
content = ""
|
||||
for i in self.nucleon_file.nucleons:
|
||||
content += " - " + i["content"] + " \n"
|
||||
return content
|
||||
|
||||
def action_go_back(self):
|
||||
self.app.pop_screen()
|
||||
|
||||
def action_precache(self):
|
||||
"""预缓存当前单元集的音频"""
|
||||
precache_screen = PrecachingScreen(self.nucleon_file)
|
||||
self.app.push_screen(precache_screen)
|
||||
|
||||
def action_quit_app(self):
|
||||
self.app.exit()
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
if event.button.id == "start_memorizing_button":
|
||||
newscr = MemScreen(
|
||||
self.nucleon_file, self.electron_file, config.get("tasked_number", 6)
|
||||
)
|
||||
self.app.push_screen(newscr)
|
||||
elif event.button.id == "precache_button":
|
||||
self.action_precache()
|
||||
|
||||
class NewNucleonScreen(Screen):
|
||||
BINDINGS = [("q", "go_back", "返回"), ("escape", "quit_app", "退出")]
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(name=None, id=None, classes=None)
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
with Container(id="vice_container"):
|
||||
yield Label(f"[b]新建空的单元集\n")
|
||||
yield Markdown("1. 键入单元集名称")
|
||||
yield Input(placeholder="单元集名称")
|
||||
yield Markdown("> 单元集名称不应与现有单元集重复, 新的单元集文件将创建在 ./nucleon/你输入的名称.toml")
|
||||
yield Label(f"\n")
|
||||
yield Markdown("2. 选择单元集类型")
|
||||
LINES = """
|
||||
单一字符串
|
||||
主字符串(带有附加属性)
|
||||
动态单元集(使用宏)
|
||||
""".splitlines()
|
||||
yield Select.from_values(LINES, prompt="选择类型")
|
||||
yield Label(f"\n")
|
||||
yield Markdown("3. 输入附加元数据 (可选)")
|
||||
yield Input(placeholder="作者")
|
||||
yield Input(placeholder="内容描述")
|
||||
yield Button(
|
||||
"新建空单元集",
|
||||
id="submit_button",
|
||||
variant="primary",
|
||||
classes="start-button",
|
||||
)
|
||||
yield Footer()
|
||||
|
||||
def action_go_back(self):
|
||||
self.app.pop_screen()
|
||||
|
||||
def action_quit_app(self):
|
||||
self.app.exit()
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
pass
|
||||
|
||||
class DashboardScreen(Screen):
|
||||
#BINDINGS = [("p", "precache_all", "预缓存所有音频")] # 新增全局预缓存快捷键
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
yield Container(
|
||||
Label(f'欢迎使用 "潜进" 启发式辅助记忆调度器, 版本 {metadata.ver}, 使用 {pt.Electron.algorithm} 调度算法', classes="title-label"),
|
||||
Label(f"当前的 UNIX 日时间戳: {aux.get_daystamp()}"),
|
||||
Label(f'包含时间戳修正: UTC+{config.get("timezone_offset")/3600}'),
|
||||
Label("选择待学习或待修改的记忆单元集:", classes="title-label"),
|
||||
ListView(id="file-list", classes="file-list-view"),
|
||||
#Button("新建空的单元集", id="new_nucleon_button"),
|
||||
Button("音频预缓存实用程序", id="precache_all_button"),
|
||||
Label(f"\"潜进\" 开放源代码软件项目 | 版本 {metadata.ver} {metadata.stage.capitalize()} | Wang Zhiyu 2025"),
|
||||
)
|
||||
yield Footer()
|
||||
|
||||
def item_desc_generator(self, path) -> dict:
|
||||
gmp = Glimpse(pt.NucleonUnion(path))
|
||||
res = dict()
|
||||
res[0] = f"{gmp.name}.toml\0"
|
||||
res[1] = f""
|
||||
if gmp.is_initialized:
|
||||
res[1] += f" 已激活单元: {gmp.activated_num}/{gmp.total_num}\n"
|
||||
res[1] += f" 下一次复习: {gmp.next_date} (最后复习于 {gmp.lastest_date})\n"
|
||||
res[1] += f" 系数均值: {gmp.avg_efactor}"
|
||||
else:
|
||||
res[1] = " 尚未激活"
|
||||
return res
|
||||
|
||||
def on_mount(self) -> None:
|
||||
file_list_widget = self.query_one("#file-list", ListView)
|
||||
nucleon_path = pathlib.Path("./nucleon")
|
||||
nucleon_files = sorted(
|
||||
[f for f in nucleon_path.iterdir() if f.suffix == ".toml"],
|
||||
key=lambda f: Glimpse(pt.NucleonUnion(f)).next_date,
|
||||
reverse=True
|
||||
)
|
||||
|
||||
if nucleon_files:
|
||||
for file in nucleon_files:
|
||||
text = self.item_desc_generator(pathlib.Path(file))
|
||||
file_list_widget.append(ListItem(
|
||||
Label(text[0] + '\n' + text[1]),
|
||||
))
|
||||
else:
|
||||
file_list_widget.append(
|
||||
ListItem(Static("在 ./nucleon/ 中未找到任何内容源数据文件.\n请放置文件后重启应用.\n或者新建空的单元集."))
|
||||
)
|
||||
file_list_widget.disabled = True
|
||||
|
||||
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
||||
if not isinstance(event.item, ListItem):
|
||||
return
|
||||
|
||||
selected_label = event.item.query_one(Label)
|
||||
if "未找到任何 .toml 文件" in str(selected_label.renderable):
|
||||
return
|
||||
|
||||
selected_filename = str(selected_label.renderable).partition('\0')[0].replace('*', "")
|
||||
nucleon_file = pt.NucleonUnion(
|
||||
pathlib.Path("./nucleon") / selected_filename
|
||||
)
|
||||
electron_file_path = pathlib.Path("./electron") / selected_filename
|
||||
if electron_file_path.exists():
|
||||
pass
|
||||
else:
|
||||
electron_file_path.touch()
|
||||
electron_file = pt.ElectronUnion(
|
||||
pathlib.Path("./electron") / selected_filename
|
||||
)
|
||||
self.app.push_screen(PreparationScreen(nucleon_file, electron_file))
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
if event.button.id == "new_nucleon_button":
|
||||
newscr = NewNucleonScreen()
|
||||
self.app.push_screen(newscr)
|
||||
elif event.button.id == "precache_all_button":
|
||||
self.action_precache_all()
|
||||
|
||||
def action_precache_all(self):
|
||||
"""预缓存所有单元集的音频"""
|
||||
precache_screen = PrecachingScreen()
|
||||
self.app.push_screen(precache_screen)
|
||||
|
||||
def action_quit_app(self) -> None:
|
||||
self.app.exit()
|
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from webshare import server
|
||||
server = server.Server("python3 main.py", title="辅助记忆程序", host="0.0.0.0")
|
||||
server.serve()
|
@@ -1,62 +0,0 @@
|
||||
Screen {
|
||||
align: center bottom;
|
||||
|
||||
}
|
||||
|
||||
#main_container {
|
||||
align: center middle;
|
||||
width: 95%;
|
||||
height: auto;
|
||||
border: thick $primary-lighten-2;
|
||||
padding: 1;
|
||||
}
|
||||
|
||||
#vice_container {
|
||||
align: center middle;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
padding: 1;
|
||||
}
|
||||
|
||||
#sentence {
|
||||
content-align: center middle;
|
||||
width: 100%;
|
||||
height: 5;
|
||||
margin-bottom: 2;
|
||||
text-style: bold;
|
||||
}
|
||||
|
||||
#progress {
|
||||
width: 100%;
|
||||
content-align: center middle;
|
||||
margin-bottom: 1;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Button {
|
||||
align-horizontal: center;
|
||||
width: 50%;
|
||||
margin: 0 0;
|
||||
}
|
||||
.choice {
|
||||
align-horizontal: center;
|
||||
width: 50%;
|
||||
margin: 0 0;
|
||||
height: auto;
|
||||
}
|
||||
/* no_margin.tcss */
|
||||
|
||||
#button_container {
|
||||
align-horizontal: center;
|
||||
height: 9;
|
||||
}
|
||||
|
||||
/* 选中 #button_container 下所有的 Horizontal 子元素 */
|
||||
#button_container > Horizontal {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
align-horizontal: center;
|
||||
width: 40%;
|
||||
}
|
@@ -1 +0,0 @@
|
||||
# 同步工具 原型
|
@@ -1,45 +0,0 @@
|
||||
import random
|
||||
|
||||
class BlankPuzzle():
|
||||
"""填空题谜题生成器
|
||||
|
||||
Args:
|
||||
text: 原始字符串(需要 "/" 分割句子, 末尾应有 "/")
|
||||
min_denominator: 最小概率倒数(如占所有可生成填空数的 1/7 中的 7, 若期望值小于 1, 则取 1)
|
||||
"""
|
||||
def __init__(self, text, min_denominator):
|
||||
self.text = text
|
||||
self.min_denominator = min_denominator
|
||||
self.wording = "填空题 - 尚未刷新谜题"
|
||||
self.answer = ["填空题 - 尚未刷新谜题"]
|
||||
|
||||
def refresh(self): # 刷新谜题
|
||||
placeholder = "___SLASH___"
|
||||
tmp_text = self.text.replace("/", placeholder)
|
||||
words = tmp_text.split(placeholder)
|
||||
if not words:
|
||||
return ""
|
||||
words = [word for word in words if word]
|
||||
num_blanks = min(max(1, len(words) // self.min_denominator), len(words))
|
||||
indices_to_blank = random.sample(range(len(words)), num_blanks)
|
||||
indices_to_blank.sort()
|
||||
blanked_words = list(words)
|
||||
answer = list()
|
||||
for index in indices_to_blank:
|
||||
blanked_words[index] = "__" * len(words[index])
|
||||
answer.append(words[index])
|
||||
result = []
|
||||
for word in blanked_words:
|
||||
result.append(word)
|
||||
self.answer = answer
|
||||
self.wording = "".join(result)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.wording}\n{str(self.answer)}"
|
||||
|
||||
# demo
|
||||
text = """我联合国人民/同兹/决心/: /欲免/后世/再遭/今代人类/两度/身历/惨不堪言/之战祸/.../"""
|
||||
riddle = BlankPuzzle(text, 3)
|
||||
print(riddle)
|
||||
riddle.refresh()
|
||||
print(riddle)
|
@@ -1,45 +0,0 @@
|
||||
import random
|
||||
|
||||
class SelectionPuzzle():
|
||||
"""选择题谜题生成器
|
||||
|
||||
Args:
|
||||
text: 原始字符串(需要 "/" 分割句子, 末尾应有 "/")
|
||||
min_denominator: 最小概率倒数(如占所有可生成填空数的 1/7 中的 7, 若期望值小于 1, 则取 1)
|
||||
"""
|
||||
def __init__(self, prefix_text, origin_dict, min_denominator):
|
||||
self.text = text
|
||||
self.min_denominator = min_denominator
|
||||
self.wording = "填空题 - 尚未刷新谜题"
|
||||
self.answer = ["填空题 - 尚未刷新谜题"]
|
||||
|
||||
def refresh(self): # 刷新谜题
|
||||
placeholder = "___SLASH___"
|
||||
tmp_text = self.text.replace("/", placeholder)
|
||||
words = tmp_text.split(placeholder)
|
||||
if not words:
|
||||
return ""
|
||||
words = [word for word in words if word]
|
||||
num_blanks = min(max(1, len(words) // self.min_denominator), len(words))
|
||||
indices_to_blank = random.sample(range(len(words)), num_blanks)
|
||||
indices_to_blank.sort()
|
||||
blanked_words = list(words)
|
||||
answer = list()
|
||||
for index in indices_to_blank:
|
||||
blanked_words[index] = "__" * len(words[index])
|
||||
answer.append(words[index])
|
||||
result = []
|
||||
for word in blanked_words:
|
||||
result.append(word)
|
||||
self.answer = answer
|
||||
self.wording = "".join(result)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.wording}\n{str(self.answer)}"
|
||||
|
||||
# demo
|
||||
text = """我联合国人民/同兹/决心/: /欲免/后世/再遭/今代人类/两度/身历/惨不堪言/之战祸/.../"""
|
||||
riddle = BlankPuzzle(text, 3)
|
||||
print(riddle)
|
||||
riddle.refresh()
|
||||
print(riddle)
|
248
legacy/tweak.py
248
legacy/tweak.py
@@ -1,248 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def check_dev_flag():
|
||||
"""检查是否存在开发标志文件,如果存在则退出程序"""
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
dev_flag_path = os.path.join(script_dir, '.devflag')
|
||||
|
||||
if os.path.exists(dev_flag_path):
|
||||
print("检测到开发标志文件 (.devflag),不得运行此程序")
|
||||
sys.exit(0)
|
||||
|
||||
def main():
|
||||
# 检查开发标志文件
|
||||
check_dev_flag()
|
||||
|
||||
# 输出标题
|
||||
print("HeurAMS 更新 & 数据管理工具")
|
||||
print("君欲何为?")
|
||||
print("\nR: 全新安装 HeurAMS (删除 nucleon 与 electron 的用户数据, 并从上游同步软件更新)")
|
||||
print("F: 翻新 HeurAMS (保留 nucleon 与 electron 的用户数据, 并从上游同步软件更新)")
|
||||
print("U: 卸载 HeurAMS (删除 HeurAMS 程序文件, 保留用户数据)")
|
||||
print("P: 应用 Termux 音频补丁")
|
||||
|
||||
# 获取用户输入
|
||||
choice = input("\n请输入选择 (R/F/U/P): ").strip().lower()
|
||||
|
||||
# 获取脚本所在目录
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
os.chdir(script_dir)
|
||||
|
||||
if choice == 'r':
|
||||
# 检查开发标志文件(再次检查,防止在运行时创建)
|
||||
check_dev_flag()
|
||||
|
||||
# 全新安装 - 删除所有文件和文件夹(包括.git)
|
||||
print("正在执行全新安装...")
|
||||
|
||||
# 遍历当前目录下的所有文件和文件夹
|
||||
for item in os.listdir('.'):
|
||||
# 跳过脚本自身(如果存在)和开发标志文件
|
||||
if item == os.path.basename(__file__) or item == '.devflag':
|
||||
continue
|
||||
|
||||
item_path = os.path.join(script_dir, item)
|
||||
|
||||
try:
|
||||
if os.path.isfile(item_path) or os.path.islink(item_path):
|
||||
os.remove(item_path)
|
||||
elif os.path.isdir(item_path):
|
||||
shutil.rmtree(item_path)
|
||||
except Exception as e:
|
||||
print(f"删除 {item} 时出错: {e}")
|
||||
|
||||
# 执行git clone到临时目录,然后移动文件
|
||||
try:
|
||||
temp_dir = os.path.join(script_dir, 'temp_clone')
|
||||
subprocess.run(['git', 'clone', 'https://gitea.imwangzhiyu.xyz/ajax/HeurAMS', temp_dir], check=True)
|
||||
|
||||
# 移动所有文件到当前目录(除了.git目录)
|
||||
for item in os.listdir(temp_dir):
|
||||
if item != '.git':
|
||||
src = os.path.join(temp_dir, item)
|
||||
dst = os.path.join(script_dir, item)
|
||||
if os.path.exists(dst):
|
||||
if os.path.isdir(dst):
|
||||
shutil.rmtree(dst)
|
||||
else:
|
||||
os.remove(dst)
|
||||
shutil.move(src, dst)
|
||||
|
||||
# 删除临时目录
|
||||
shutil.rmtree(temp_dir)
|
||||
print("全新安装完成!")
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Git clone 失败: {e}")
|
||||
except Exception as e:
|
||||
print(f"文件操作失败: {e}")
|
||||
|
||||
elif choice == 'f':
|
||||
# 检查开发标志文件(再次检查,防止在运行时创建)
|
||||
check_dev_flag()
|
||||
|
||||
# 翻新安装 - 保留特定目录
|
||||
print("正在执行翻新安装...")
|
||||
|
||||
# 需要保留的目录列表
|
||||
preserve_dirs = ['nucleon', 'electron', 'cache']
|
||||
|
||||
# 备份需要保留的目录到临时位置
|
||||
backup_dir = os.path.join(script_dir, 'temp_backup')
|
||||
os.makedirs(backup_dir, exist_ok=True)
|
||||
|
||||
for dir_name in preserve_dirs:
|
||||
dir_path = os.path.join(script_dir, dir_name)
|
||||
if os.path.exists(dir_path):
|
||||
backup_path = os.path.join(backup_dir, dir_name)
|
||||
if os.path.exists(backup_path):
|
||||
shutil.rmtree(backup_path)
|
||||
shutil.copytree(dir_path, backup_path)
|
||||
|
||||
# 删除所有文件和文件夹(包括.git)
|
||||
for item in os.listdir('.'):
|
||||
# 跳过脚本自身、备份目录和开发标志文件
|
||||
if item == os.path.basename(__file__) or item == 'temp_backup' or item == '.devflag':
|
||||
continue
|
||||
|
||||
item_path = os.path.join(script_dir, item)
|
||||
|
||||
try:
|
||||
if os.path.isfile(item_path) or os.path.islink(item_path):
|
||||
os.remove(item_path)
|
||||
elif os.path.isdir(item_path):
|
||||
shutil.rmtree(item_path)
|
||||
except Exception as e:
|
||||
print(f"删除 {item} 时出错: {e}")
|
||||
|
||||
# 执行git clone到当前目录
|
||||
try:
|
||||
temp_dir = os.path.join(script_dir, 'temp_clone')
|
||||
subprocess.run(['git', 'clone', 'https://gitea.imwangzhiyu.xyz/ajax/HeurAMS', temp_dir], check=True)
|
||||
|
||||
# 移动所有文件到当前目录(除了.git目录)
|
||||
for item in os.listdir(temp_dir):
|
||||
if item != '.git':
|
||||
src = os.path.join(temp_dir, item)
|
||||
dst = os.path.join(script_dir, item)
|
||||
if os.path.exists(dst):
|
||||
if os.path.isdir(dst):
|
||||
shutil.rmtree(dst)
|
||||
else:
|
||||
os.remove(dst)
|
||||
shutil.move(src, dst)
|
||||
|
||||
# 删除临时克隆目录
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
# 恢复保留的目录(覆盖git仓库中的同名目录)
|
||||
for dir_name in preserve_dirs:
|
||||
backup_path = os.path.join(backup_dir, dir_name)
|
||||
if os.path.exists(backup_path):
|
||||
target_path = os.path.join(script_dir, dir_name)
|
||||
if os.path.exists(target_path):
|
||||
shutil.rmtree(target_path)
|
||||
shutil.copytree(backup_path, target_path)
|
||||
|
||||
# 删除备份目录
|
||||
shutil.rmtree(backup_dir)
|
||||
print("翻新安装完成!")
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Git clone 失败: {e}")
|
||||
except Exception as e:
|
||||
print(f"文件操作失败: {e}")
|
||||
|
||||
elif choice == 'u':
|
||||
# 检查开发标志文件(再次检查,防止在运行时创建)
|
||||
check_dev_flag()
|
||||
|
||||
# 卸载 HeurAMS - 删除程序文件,保留用户数据
|
||||
print("正在卸载 HeurAMS,保留用户数据...")
|
||||
|
||||
# 需要保留的用户数据目录列表
|
||||
preserve_dirs = ['nucleon', 'electron', 'cache']
|
||||
|
||||
# 备份需要保留的目录到临时位置
|
||||
backup_dir = os.path.join(script_dir, 'temp_backup')
|
||||
os.makedirs(backup_dir, exist_ok=True)
|
||||
|
||||
for dir_name in preserve_dirs:
|
||||
dir_path = os.path.join(script_dir, dir_name)
|
||||
if os.path.exists(dir_path):
|
||||
backup_path = os.path.join(backup_dir, dir_name)
|
||||
if os.path.exists(backup_path):
|
||||
shutil.rmtree(backup_path)
|
||||
shutil.copytree(dir_path, backup_path)
|
||||
print(f"已备份用户数据: {dir_name}")
|
||||
|
||||
# 删除所有文件和文件夹(除了脚本自身、备份目录和开发标志文件)
|
||||
for item in os.listdir('.'):
|
||||
# 跳过脚本自身、备份目录和开发标志文件
|
||||
if item == os.path.basename(__file__) or item == 'temp_backup' or item == '.devflag':
|
||||
continue
|
||||
|
||||
item_path = os.path.join(script_dir, item)
|
||||
|
||||
try:
|
||||
if os.path.isfile(item_path) or os.path.islink(item_path):
|
||||
os.remove(item_path)
|
||||
print(f"已删除文件: {item}")
|
||||
elif os.path.isdir(item_path):
|
||||
shutil.rmtree(item_path)
|
||||
print(f"已删除目录: {item}")
|
||||
except Exception as e:
|
||||
print(f"删除 {item} 时出错: {e}")
|
||||
|
||||
# 恢复保留的用户数据目录
|
||||
for dir_name in preserve_dirs:
|
||||
backup_path = os.path.join(backup_dir, dir_name)
|
||||
if os.path.exists(backup_path):
|
||||
target_path = os.path.join(script_dir, dir_name)
|
||||
if os.path.exists(target_path):
|
||||
shutil.rmtree(target_path)
|
||||
shutil.copytree(backup_path, target_path)
|
||||
print(f"已恢复用户数据: {dir_name}")
|
||||
|
||||
# 删除备份目录
|
||||
shutil.rmtree(backup_dir)
|
||||
print("卸载完成!HeurAMS 程序文件已删除,用户数据已保留。")
|
||||
|
||||
elif choice == 'p':
|
||||
# 应用 Termux 音频补丁
|
||||
print("应用 Termux 音频补丁")
|
||||
|
||||
# 询问用户是否使用安卓Termux环境
|
||||
termux_choice = input("是否使用安卓Termux环境? (y/n): ").strip().lower()
|
||||
|
||||
if termux_choice in ['y', 'yes']:
|
||||
# 创建playsound.py文件
|
||||
playsound_content = '''import os
|
||||
def playsound(path):
|
||||
os.system(f"play-audio '{path}'")
|
||||
'''
|
||||
|
||||
playsound_path = os.path.join(script_dir, 'playsound.py')
|
||||
|
||||
try:
|
||||
with open(playsound_path, 'w', encoding='utf-8') as f:
|
||||
f.write(playsound_content)
|
||||
print("已创建 playsound.py 文件")
|
||||
print("Termux 音频补丁应用成功!")
|
||||
print("现在可以使用 play-audio 命令播放音频了。")
|
||||
|
||||
except Exception as e:
|
||||
print(f"创建 playsound.py 文件时出错: {e}")
|
||||
else:
|
||||
print("已取消应用 Termux 音频补丁。")
|
||||
|
||||
else:
|
||||
print("无效的选择,请输入 R、F、U 或 P。")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@@ -1,325 +0,0 @@
|
||||
"""
|
||||
An encoding / decoding format suitable for serializing data structures to binary.
|
||||
|
||||
This is based on https://en.wikipedia.org/wiki/Bencode with some extensions.
|
||||
|
||||
The following data types may be encoded:
|
||||
|
||||
- None
|
||||
- int
|
||||
- bool
|
||||
- bytes
|
||||
- str
|
||||
- list
|
||||
- tuple
|
||||
- dict
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
class DecodeError(Exception):
|
||||
"""A problem decoding data."""
|
||||
|
||||
|
||||
def dump(data: object) -> bytes:
|
||||
"""Encodes a data structure in to bytes.
|
||||
|
||||
Args:
|
||||
data: Data structure
|
||||
|
||||
Returns:
|
||||
A byte string encoding the data.
|
||||
"""
|
||||
|
||||
def encode_none(_datum: None) -> bytes:
|
||||
"""
|
||||
Encodes a None value.
|
||||
|
||||
Args:
|
||||
datum: Always None.
|
||||
|
||||
Returns:
|
||||
None encoded.
|
||||
"""
|
||||
return b"N"
|
||||
|
||||
def encode_bool(datum: bool) -> bytes:
|
||||
"""
|
||||
Encode a boolean value.
|
||||
|
||||
Args:
|
||||
datum: The boolean value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"T" if datum else b"F"
|
||||
|
||||
def encode_int(datum: int) -> bytes:
|
||||
"""
|
||||
Encode an integer value.
|
||||
|
||||
Args:
|
||||
datum: The integer value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"i%ie" % datum
|
||||
|
||||
def encode_bytes(datum: bytes) -> bytes:
|
||||
"""
|
||||
Encode a bytes value.
|
||||
|
||||
Args:
|
||||
datum: The bytes value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"%i:%s" % (len(datum), datum)
|
||||
|
||||
def encode_string(datum: str) -> bytes:
|
||||
"""
|
||||
Encode a string value.
|
||||
|
||||
Args:
|
||||
datum: The string value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
encoded_data = datum.encode("utf-8")
|
||||
return b"s%i:%s" % (len(encoded_data), encoded_data)
|
||||
|
||||
def encode_list(datum: list) -> bytes:
|
||||
"""
|
||||
Encode a list value.
|
||||
|
||||
Args:
|
||||
datum: The list value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"l%se" % b"".join(encode(element) for element in datum)
|
||||
|
||||
def encode_tuple(datum: tuple) -> bytes:
|
||||
"""
|
||||
Encode a tuple value.
|
||||
|
||||
Args:
|
||||
datum: The tuple value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"t%se" % b"".join(encode(element) for element in datum)
|
||||
|
||||
def encode_dict(datum: dict) -> bytes:
|
||||
"""
|
||||
Encode a dictionary value.
|
||||
|
||||
Args:
|
||||
datum: The dictionary value to encode.
|
||||
|
||||
Returns:
|
||||
The encoded bytes.
|
||||
"""
|
||||
return b"d%se" % b"".join(
|
||||
b"%s%s" % (encode(key), encode(value)) for key, value in datum.items()
|
||||
)
|
||||
|
||||
ENCODERS: dict[type, Callable[[Any], Any]] = {
|
||||
type(None): encode_none,
|
||||
bool: encode_bool,
|
||||
int: encode_int,
|
||||
bytes: encode_bytes,
|
||||
str: encode_string,
|
||||
list: encode_list,
|
||||
tuple: encode_tuple,
|
||||
dict: encode_dict,
|
||||
}
|
||||
|
||||
def encode(datum: object) -> bytes:
|
||||
"""Recursively encode data.
|
||||
|
||||
Args:
|
||||
datum: Data suitable for encoding.
|
||||
|
||||
Raises:
|
||||
TypeError: If `datum` is not one of the supported types.
|
||||
|
||||
Returns:
|
||||
Encoded data bytes.
|
||||
"""
|
||||
try:
|
||||
decoder = ENCODERS[type(datum)]
|
||||
except KeyError:
|
||||
raise TypeError("Can't encode {datum!r}") from None
|
||||
return decoder(datum)
|
||||
|
||||
return encode(data)
|
||||
|
||||
|
||||
def load(encoded: bytes) -> object:
|
||||
"""Load an encoded data structure from bytes.
|
||||
|
||||
Args:
|
||||
encoded: Encoded data in bytes.
|
||||
|
||||
Raises:
|
||||
DecodeError: If an error was encountered decoding the string.
|
||||
|
||||
Returns:
|
||||
Decoded data.
|
||||
"""
|
||||
if not isinstance(encoded, bytes):
|
||||
raise TypeError("must be bytes")
|
||||
max_position = len(encoded)
|
||||
position = 0
|
||||
|
||||
def get_byte() -> bytes:
|
||||
"""Get an encoded byte and advance position.
|
||||
|
||||
Raises:
|
||||
DecodeError: If the end of the data was reached
|
||||
|
||||
Returns:
|
||||
A bytes object with a single byte.
|
||||
"""
|
||||
nonlocal position
|
||||
if position >= max_position:
|
||||
raise DecodeError("More data expected")
|
||||
character = encoded[position : position + 1]
|
||||
position += 1
|
||||
return character
|
||||
|
||||
def peek_byte() -> bytes:
|
||||
"""Get the byte at the current position, but don't advance position.
|
||||
|
||||
Returns:
|
||||
A bytes object with a single byte.
|
||||
"""
|
||||
return encoded[position : position + 1]
|
||||
|
||||
def get_bytes(size: int) -> bytes:
|
||||
"""Get a number of bytes of encode data.
|
||||
|
||||
Args:
|
||||
size: Number of bytes to retrieve.
|
||||
|
||||
Raises:
|
||||
DecodeError: If there aren't enough bytes.
|
||||
|
||||
Returns:
|
||||
A bytes object.
|
||||
"""
|
||||
nonlocal position
|
||||
bytes_data = encoded[position : position + size]
|
||||
if len(bytes_data) != size:
|
||||
raise DecodeError(b"Missing bytes in {bytes_data!r}")
|
||||
position += size
|
||||
return bytes_data
|
||||
|
||||
def decode_int() -> int:
|
||||
"""Decode an int from the encoded data.
|
||||
|
||||
Returns:
|
||||
An integer.
|
||||
"""
|
||||
int_bytes = b""
|
||||
while (byte := get_byte()) != b"e":
|
||||
int_bytes += byte
|
||||
return int(int_bytes)
|
||||
|
||||
def decode_bytes(size_bytes: bytes) -> bytes:
|
||||
"""Decode a bytes string from the encoded data.
|
||||
|
||||
Returns:
|
||||
A bytes object.
|
||||
"""
|
||||
while (byte := get_byte()) != b":":
|
||||
size_bytes += byte
|
||||
bytes_string = get_bytes(int(size_bytes))
|
||||
return bytes_string
|
||||
|
||||
def decode_string() -> str:
|
||||
"""Decode a (utf-8 encoded) string from the encoded data.
|
||||
|
||||
Returns:
|
||||
A string.
|
||||
"""
|
||||
size_bytes = b""
|
||||
while (byte := get_byte()) != b":":
|
||||
size_bytes += byte
|
||||
bytes_string = get_bytes(int(size_bytes))
|
||||
decoded_string = bytes_string.decode("utf-8", errors="replace")
|
||||
return decoded_string
|
||||
|
||||
def decode_list() -> list[object]:
|
||||
"""Decode a list.
|
||||
|
||||
Returns:
|
||||
A list of data.
|
||||
"""
|
||||
elements: list[object] = []
|
||||
add_element = elements.append
|
||||
while peek_byte() != b"e":
|
||||
add_element(decode())
|
||||
get_byte()
|
||||
return elements
|
||||
|
||||
def decode_tuple() -> tuple[object, ...]:
|
||||
"""Decode a tuple.
|
||||
|
||||
Returns:
|
||||
A tuple of decoded data.
|
||||
"""
|
||||
elements: list[object] = []
|
||||
add_element = elements.append
|
||||
while peek_byte() != b"e":
|
||||
add_element(decode())
|
||||
get_byte()
|
||||
return tuple(elements)
|
||||
|
||||
def decode_dict() -> dict[object, object]:
|
||||
"""Decode a dict.
|
||||
|
||||
Returns:
|
||||
A dict of decoded data.
|
||||
"""
|
||||
elements: dict[object, object] = {}
|
||||
add_element = elements.__setitem__
|
||||
while peek_byte() != b"e":
|
||||
add_element(decode(), decode())
|
||||
get_byte()
|
||||
return elements
|
||||
|
||||
DECODERS = {
|
||||
b"i": decode_int,
|
||||
b"s": decode_string,
|
||||
b"l": decode_list,
|
||||
b"t": decode_tuple,
|
||||
b"d": decode_dict,
|
||||
b"T": lambda: True,
|
||||
b"F": lambda: False,
|
||||
b"N": lambda: None,
|
||||
}
|
||||
|
||||
def decode() -> object:
|
||||
"""Recursively decode data.
|
||||
|
||||
Returns:
|
||||
Decoded data.
|
||||
"""
|
||||
decoder = DECODERS.get(initial := get_byte(), None)
|
||||
if decoder is None:
|
||||
return decode_bytes(initial)
|
||||
return decoder()
|
||||
|
||||
return decode()
|
@@ -1,349 +0,0 @@
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from typing import Awaitable, Callable, Literal
|
||||
from asyncio.subprocess import Process
|
||||
import logging
|
||||
|
||||
from importlib.metadata import version
|
||||
import uuid
|
||||
|
||||
from webshare.download_manager import DownloadManager
|
||||
from webshare._binary_encode import load as binary_load
|
||||
|
||||
log = logging.getLogger("textual-serve")
|
||||
|
||||
|
||||
class AppService:
|
||||
"""Creates and manages a single Textual app subprocess.
|
||||
|
||||
When a user connects to the websocket in their browser, a new AppService
|
||||
instance is created to manage the corresponding Textual app process.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
write_bytes: Callable[[bytes], Awaitable[None]],
|
||||
write_str: Callable[[str], Awaitable[None]],
|
||||
close: Callable[[], Awaitable[None]],
|
||||
download_manager: DownloadManager,
|
||||
debug: bool = False,
|
||||
) -> None:
|
||||
self.app_service_id: str = uuid.uuid4().hex
|
||||
"""The unique ID of this running app service."""
|
||||
self.command = command
|
||||
"""The command to launch the Textual app subprocess."""
|
||||
self.remote_write_bytes = write_bytes
|
||||
"""Write bytes to the client browser websocket."""
|
||||
self.remote_write_str = write_str
|
||||
"""Write string to the client browser websocket."""
|
||||
self.remote_close = close
|
||||
"""Close the client browser websocket."""
|
||||
self.debug = debug
|
||||
"""Enable/disable debug mode."""
|
||||
|
||||
self._process: Process | None = None
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
self._stdin: asyncio.StreamWriter | None = None
|
||||
self._exit_event = asyncio.Event()
|
||||
self._download_manager = download_manager
|
||||
|
||||
@property
|
||||
def stdin(self) -> asyncio.StreamWriter:
|
||||
"""The processes standard input stream."""
|
||||
assert self._stdin is not None
|
||||
return self._stdin
|
||||
|
||||
def _build_environment(self, width: int = 80, height: int = 24) -> dict[str, str]:
|
||||
"""Build an environment dict for the App subprocess.
|
||||
|
||||
Args:
|
||||
width: Initial width.
|
||||
height: Initial height.
|
||||
|
||||
Returns:
|
||||
A environment dict.
|
||||
"""
|
||||
environment = dict(os.environ.copy())
|
||||
environment["TEXTUAL_DRIVER"] = "textual.drivers.web_driver:WebDriver"
|
||||
environment["TEXTUAL_FPS"] = "60"
|
||||
environment["TEXTUAL_COLOR_SYSTEM"] = "truecolor"
|
||||
environment["TERM_PROGRAM"] = "textual"
|
||||
environment["TERM_PROGRAM_VERSION"] = version("textual-serve")
|
||||
environment["COLUMNS"] = str(width)
|
||||
environment["ROWS"] = str(height)
|
||||
if self.debug:
|
||||
environment["TEXTUAL"] = "debug,devtools"
|
||||
environment["TEXTUAL_LOG"] = "textual.log"
|
||||
return environment
|
||||
|
||||
async def _open_app_process(self, width: int = 80, height: int = 24) -> Process:
|
||||
"""Open a process to run the app.
|
||||
|
||||
Args:
|
||||
width: Width of the terminal.
|
||||
height: height of the terminal.
|
||||
"""
|
||||
environment = self._build_environment(width=width, height=height)
|
||||
self._process = process = await asyncio.create_subprocess_shell(
|
||||
self.command,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env=environment,
|
||||
)
|
||||
assert process.stdin is not None
|
||||
self._stdin = process.stdin
|
||||
|
||||
return process
|
||||
|
||||
@classmethod
|
||||
def encode_packet(cls, packet_type: Literal[b"D", b"M"], payload: bytes) -> bytes:
|
||||
"""Encode a packet.
|
||||
|
||||
Args:
|
||||
packet_type: The packet type (b"D" for data or b"M" for meta)
|
||||
payload: The payload.
|
||||
|
||||
Returns:
|
||||
Data as bytes.
|
||||
"""
|
||||
return b"%s%s%s" % (packet_type, len(payload).to_bytes(4, "big"), payload)
|
||||
|
||||
async def send_bytes(self, data: bytes) -> bool:
|
||||
"""Send bytes to process.
|
||||
|
||||
Args:
|
||||
data: Data to send.
|
||||
|
||||
Returns:
|
||||
True if the data was sent, otherwise False.
|
||||
"""
|
||||
stdin = self.stdin
|
||||
try:
|
||||
stdin.write(self.encode_packet(b"D", data))
|
||||
except RuntimeError:
|
||||
return False
|
||||
try:
|
||||
await stdin.drain()
|
||||
except Exception:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def send_meta(self, data: dict[str, str | None | int | bool]) -> bool:
|
||||
"""Send meta information to process.
|
||||
|
||||
Args:
|
||||
data: Meta dict to send.
|
||||
|
||||
Returns:
|
||||
True if the data was sent, otherwise False.
|
||||
"""
|
||||
stdin = self.stdin
|
||||
data_bytes = json.dumps(data).encode("utf-8")
|
||||
try:
|
||||
stdin.write(self.encode_packet(b"M", data_bytes))
|
||||
except RuntimeError:
|
||||
return False
|
||||
try:
|
||||
await stdin.drain()
|
||||
except Exception:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def set_terminal_size(self, width: int, height: int) -> None:
|
||||
"""Tell the process about the new terminal size.
|
||||
|
||||
Args:
|
||||
width: Width of terminal in cells.
|
||||
height: Height of terminal in cells.
|
||||
"""
|
||||
await self.send_meta(
|
||||
{
|
||||
"type": "resize",
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
)
|
||||
|
||||
async def blur(self) -> None:
|
||||
"""Send an (app) blur to the process."""
|
||||
await self.send_meta({"type": "blur"})
|
||||
|
||||
async def focus(self) -> None:
|
||||
"""Send an (app) focus to the process."""
|
||||
await self.send_meta({"type": "focus"})
|
||||
|
||||
async def start(self, width: int, height: int) -> None:
|
||||
await self._open_app_process(width, height)
|
||||
self._task = asyncio.create_task(self.run())
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the process and wait for it to complete."""
|
||||
if self._task is not None:
|
||||
await self._download_manager.cancel_app_downloads(
|
||||
app_service_id=self.app_service_id
|
||||
)
|
||||
|
||||
await self.send_meta({"type": "quit"})
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Run the Textual app process.
|
||||
|
||||
!!! note
|
||||
|
||||
Do not call this manually, use `start`.
|
||||
|
||||
"""
|
||||
META = b"M"
|
||||
DATA = b"D"
|
||||
PACKED = b"P"
|
||||
|
||||
assert self._process is not None
|
||||
process = self._process
|
||||
|
||||
stdout = process.stdout
|
||||
stderr = process.stderr
|
||||
assert stdout is not None
|
||||
assert stderr is not None
|
||||
|
||||
stderr_data = io.BytesIO()
|
||||
|
||||
async def read_stderr() -> None:
|
||||
"""Task to read stderr."""
|
||||
try:
|
||||
while True:
|
||||
data = await stderr.read(1024 * 4)
|
||||
if not data:
|
||||
break
|
||||
stderr_data.write(data)
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
stderr_task = asyncio.create_task(read_stderr())
|
||||
|
||||
try:
|
||||
ready = False
|
||||
# Wait for prelude text, so we know it is a Textual app
|
||||
for _ in range(10):
|
||||
if not (line := await stdout.readline()):
|
||||
break
|
||||
if line == b"__GANGLION__\n":
|
||||
ready = True
|
||||
break
|
||||
|
||||
if not ready:
|
||||
log.error("Application failed to start")
|
||||
if error_text := stderr_data.getvalue():
|
||||
import sys
|
||||
|
||||
sys.stdout.write(error_text.decode("utf-8", "replace"))
|
||||
|
||||
readexactly = stdout.readexactly
|
||||
int_from_bytes = int.from_bytes
|
||||
while True:
|
||||
type_bytes = await readexactly(1)
|
||||
size_bytes = await readexactly(4)
|
||||
size = int_from_bytes(size_bytes, "big")
|
||||
payload = await readexactly(size)
|
||||
if type_bytes == DATA:
|
||||
await self.on_data(payload)
|
||||
elif type_bytes == META:
|
||||
await self.on_meta(payload)
|
||||
elif type_bytes == PACKED:
|
||||
await self.on_packed(payload)
|
||||
|
||||
except asyncio.IncompleteReadError:
|
||||
pass
|
||||
except ConnectionResetError:
|
||||
pass
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
finally:
|
||||
stderr_task.cancel()
|
||||
await stderr_task
|
||||
|
||||
if error_text := stderr_data.getvalue():
|
||||
import sys
|
||||
|
||||
sys.stdout.write(error_text.decode("utf-8", "replace"))
|
||||
|
||||
async def on_data(self, payload: bytes) -> None:
|
||||
"""Called when there is data.
|
||||
|
||||
Args:
|
||||
payload: Data received from process.
|
||||
"""
|
||||
await self.remote_write_bytes(payload)
|
||||
|
||||
async def on_meta(self, data: bytes) -> None:
|
||||
"""Called when there is a meta packet sent from the running app process.
|
||||
|
||||
Args:
|
||||
data: Encoded meta data.
|
||||
"""
|
||||
meta_data: dict[str, object] = json.loads(data)
|
||||
meta_type = meta_data["type"]
|
||||
|
||||
if meta_type == "exit":
|
||||
await self.remote_close()
|
||||
elif meta_type == "open_url":
|
||||
payload = json.dumps(
|
||||
[
|
||||
"open_url",
|
||||
{
|
||||
"url": meta_data["url"],
|
||||
"new_tab": meta_data["new_tab"],
|
||||
},
|
||||
]
|
||||
)
|
||||
await self.remote_write_str(payload)
|
||||
elif meta_type == "deliver_file_start":
|
||||
log.debug("deliver_file_start, %s", meta_data)
|
||||
try:
|
||||
# Record this delivery key as available for download.
|
||||
delivery_key = str(meta_data["key"])
|
||||
await self._download_manager.create_download(
|
||||
app_service=self,
|
||||
delivery_key=delivery_key,
|
||||
file_name=Path(meta_data["path"]).name,
|
||||
open_method=meta_data["open_method"],
|
||||
mime_type=meta_data["mime_type"],
|
||||
encoding=meta_data["encoding"],
|
||||
name=meta_data.get("name", None),
|
||||
)
|
||||
except KeyError:
|
||||
log.error("Missing key in `deliver_file_start` meta packet")
|
||||
return
|
||||
else:
|
||||
# Tell the browser front-end about the new delivery key,
|
||||
# so that it may hit the "/download/{key}" endpoint
|
||||
# to start the download.
|
||||
json_string = json.dumps(["deliver_file_start", delivery_key])
|
||||
await self.remote_write_str(json_string)
|
||||
else:
|
||||
log.warning(
|
||||
f"Unknown meta type: {meta_type!r}. You may need to update `textual-serve`."
|
||||
)
|
||||
|
||||
async def on_packed(self, payload: bytes) -> None:
|
||||
"""Called when there is a packed packet sent from the running app process.
|
||||
|
||||
Args:
|
||||
payload: Encoded packed data.
|
||||
"""
|
||||
unpacked = binary_load(payload)
|
||||
if unpacked[0] == "deliver_chunk":
|
||||
# If we receive a chunk, hand it to the download manager to
|
||||
# handle distribution to the browser.
|
||||
_, delivery_key, chunk = unpacked
|
||||
await self._download_manager.chunk_received(delivery_key, chunk)
|
@@ -1,197 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
import logging
|
||||
from typing import AsyncGenerator, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from webshare.app_service import AppService
|
||||
|
||||
log = logging.getLogger("textual-serve")
|
||||
|
||||
DOWNLOAD_TIMEOUT = 4
|
||||
DOWNLOAD_CHUNK_SIZE = 1024 * 64 # 64 KB
|
||||
|
||||
|
||||
@dataclass
|
||||
class Download:
|
||||
app_service: "AppService"
|
||||
"""The app service that the download is associated with."""
|
||||
|
||||
delivery_key: str
|
||||
"""Key which identifies the download."""
|
||||
|
||||
file_name: str
|
||||
"""The name of the file to download. This will be used to set
|
||||
the Content-Disposition filename."""
|
||||
|
||||
open_method: str
|
||||
"""The method to open the file with. "browser" or "download"."""
|
||||
|
||||
mime_type: str
|
||||
"""The mime type of the content."""
|
||||
|
||||
encoding: str | None = None
|
||||
"""The encoding of the content.
|
||||
Will be None if the content is binary.
|
||||
"""
|
||||
|
||||
name: str | None = None
|
||||
"""Optional name set bt the client."""
|
||||
|
||||
incoming_chunks: asyncio.Queue[bytes | None] = field(default_factory=asyncio.Queue)
|
||||
"""A queue of incoming chunks for the download.
|
||||
Chunks are sent from the app service to the download handler
|
||||
via this queue."""
|
||||
|
||||
|
||||
class DownloadManager:
|
||||
"""Class which manages downloads for the server.
|
||||
|
||||
Serves as the link between the web server and app processes during downloads.
|
||||
|
||||
A single server has a single download manager, which manages all downloads for all
|
||||
running app processes.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._active_downloads: dict[str, Download] = {}
|
||||
"""A dictionary of active downloads.
|
||||
|
||||
When a delivery key is received in a meta packet, it is added to this set.
|
||||
When the user hits the "/download/{key}" endpoint, we ensure the key is in
|
||||
this set and start the download by requesting chunks from the app process.
|
||||
|
||||
When the download is complete, the app process sends a "deliver_file_end"
|
||||
meta packet, and we remove the key from this set.
|
||||
"""
|
||||
|
||||
async def create_download(
|
||||
self,
|
||||
*,
|
||||
app_service: "AppService",
|
||||
delivery_key: str,
|
||||
file_name: str,
|
||||
open_method: str,
|
||||
mime_type: str,
|
||||
encoding: str | None = None,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Prepare for a new download.
|
||||
|
||||
Args:
|
||||
app_service: The app service to start the download for.
|
||||
delivery_key: The delivery key to start the download for.
|
||||
file_name: The name of the file to download.
|
||||
open_method: The method to open the file with.
|
||||
mime_type: The mime type of the content.
|
||||
encoding: The encoding of the content or None if the content is binary.
|
||||
"""
|
||||
self._active_downloads[delivery_key] = Download(
|
||||
app_service,
|
||||
delivery_key,
|
||||
file_name,
|
||||
open_method,
|
||||
mime_type,
|
||||
encoding,
|
||||
name=name,
|
||||
)
|
||||
|
||||
async def download(self, delivery_key: str) -> AsyncGenerator[bytes, None]:
|
||||
"""Download a file from the given app service.
|
||||
|
||||
Args:
|
||||
delivery_key: The delivery key to download.
|
||||
"""
|
||||
|
||||
app_service = await self._get_app_service(delivery_key)
|
||||
download = self._active_downloads[delivery_key]
|
||||
incoming_chunks = download.incoming_chunks
|
||||
|
||||
while True:
|
||||
# Request a chunk from the app service.
|
||||
send_result = await app_service.send_meta(
|
||||
{
|
||||
"type": "deliver_chunk_request",
|
||||
"key": delivery_key,
|
||||
"size": DOWNLOAD_CHUNK_SIZE,
|
||||
"name": download.name,
|
||||
}
|
||||
)
|
||||
|
||||
if not send_result:
|
||||
log.warning(
|
||||
"Download {delivery_key!r} failed to request chunk from app service"
|
||||
)
|
||||
del self._active_downloads[delivery_key]
|
||||
break
|
||||
|
||||
try:
|
||||
chunk = await asyncio.wait_for(incoming_chunks.get(), DOWNLOAD_TIMEOUT)
|
||||
except asyncio.TimeoutError:
|
||||
log.warning(
|
||||
"Download %r failed to receive chunk from app service within %r seconds",
|
||||
delivery_key,
|
||||
DOWNLOAD_TIMEOUT,
|
||||
)
|
||||
chunk = None
|
||||
|
||||
if not chunk:
|
||||
# Empty chunk - the app process has finished sending the file
|
||||
# or the download has been cancelled.
|
||||
incoming_chunks.task_done()
|
||||
del self._active_downloads[delivery_key]
|
||||
break
|
||||
else:
|
||||
incoming_chunks.task_done()
|
||||
yield chunk
|
||||
|
||||
async def chunk_received(self, delivery_key: str, chunk: bytes | str) -> None:
|
||||
"""Handle a chunk received from the app service for a download.
|
||||
|
||||
Args:
|
||||
delivery_key: The delivery key that the chunk was received for.
|
||||
chunk: The chunk that was received.
|
||||
"""
|
||||
|
||||
download = self._active_downloads.get(delivery_key)
|
||||
if not download:
|
||||
# The download may have been cancelled - e.g. the websocket
|
||||
# was closed before the download could complete.
|
||||
log.debug("Chunk received for cancelled download %r", delivery_key)
|
||||
return
|
||||
|
||||
if isinstance(chunk, str):
|
||||
chunk = chunk.encode(download.encoding or "utf-8")
|
||||
await download.incoming_chunks.put(chunk)
|
||||
|
||||
async def _get_app_service(self, delivery_key: str) -> "AppService":
|
||||
"""Get the app service that the given delivery key is linked to.
|
||||
|
||||
Args:
|
||||
delivery_key: The delivery key to get the app service for.
|
||||
"""
|
||||
for key in self._active_downloads.keys():
|
||||
if key == delivery_key:
|
||||
return self._active_downloads[key].app_service
|
||||
else:
|
||||
raise ValueError(f"No active download for delivery key {delivery_key!r}")
|
||||
|
||||
async def get_download_metadata(self, delivery_key: str) -> Download:
|
||||
"""Get the metadata for a download.
|
||||
|
||||
Args:
|
||||
delivery_key: The delivery key to get the metadata for.
|
||||
"""
|
||||
return self._active_downloads[delivery_key]
|
||||
|
||||
async def cancel_app_downloads(self, app_service_id: str) -> None:
|
||||
"""Cancel all downloads for the given app service.
|
||||
|
||||
Args:
|
||||
app_service_id: The app service ID to cancel downloads for.
|
||||
"""
|
||||
for download in self._active_downloads.values():
|
||||
if download.app_service.app_service_id == app_service_id:
|
||||
await download.incoming_chunks.put(None)
|
@@ -1,350 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sys
|
||||
|
||||
from typing import Any
|
||||
|
||||
import aiohttp_jinja2
|
||||
from aiohttp import web
|
||||
from aiohttp import WSMsgType
|
||||
from aiohttp.web_runner import GracefulExit
|
||||
import jinja2
|
||||
|
||||
from importlib.metadata import version
|
||||
|
||||
from rich.console import Console
|
||||
from rich.logging import RichHandler
|
||||
from rich.highlighter import RegexHighlighter
|
||||
|
||||
from webshare.download_manager import DownloadManager
|
||||
|
||||
from .app_service import AppService
|
||||
|
||||
log = logging.getLogger("textual-serve")
|
||||
|
||||
LOGO = r"""[bold magenta]___ ____ _ _ ___ _ _ ____ _ ____ ____ ____ _ _ ____
|
||||
| |___ \/ | | | |__| | __ [__ |___ |__/ | | |___
|
||||
| |___ _/\_ | |__| | | |___ ___] |___ | \ \/ |___ [not bold]VVVVV
|
||||
""".replace("VVVVV", f"v{version('textual-serve')}")
|
||||
|
||||
|
||||
WINDOWS = sys.platform == "WINDOWS"
|
||||
|
||||
|
||||
class LogHighlighter(RegexHighlighter):
|
||||
base_style = "repr."
|
||||
highlights = [
|
||||
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)",
|
||||
r"(?P<path>\[.*?\])",
|
||||
r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
|
||||
]
|
||||
|
||||
|
||||
def to_int(value: str, default: int) -> int:
|
||||
"""Convert to an integer, or return a default if that's not possible.
|
||||
|
||||
Args:
|
||||
number: A string possibly containing a decimal.
|
||||
default: Default value if value can't be decoded.
|
||||
|
||||
Returns:
|
||||
Integer.
|
||||
"""
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
class Server:
|
||||
"""Serve a Textual app."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
command: str,
|
||||
host: str = "localhost",
|
||||
port: int = 8000,
|
||||
title: str | None = None,
|
||||
public_url: str | None = None,
|
||||
statics_path: str | os.PathLike = "./static",
|
||||
templates_path: str | os.PathLike = "./templates",
|
||||
):
|
||||
"""
|
||||
|
||||
Args:
|
||||
app_factory: A callable that returns a new App instance.
|
||||
host: Host of web application.
|
||||
port: Port for server.
|
||||
statics_path: Path to statics folder. May be absolute or relative to server.py.
|
||||
templates_path" Path to templates folder. May be absolute or relative to server.py.
|
||||
"""
|
||||
self.command = command
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.title = title or command
|
||||
self.debug = False
|
||||
|
||||
if public_url is None:
|
||||
if self.port == 80:
|
||||
self.public_url = f"http://{self.host}"
|
||||
elif self.port == 443:
|
||||
self.public_url = f"https://{self.host}"
|
||||
else:
|
||||
self.public_url = f"http://{self.host}:{self.port}"
|
||||
else:
|
||||
self.public_url = public_url
|
||||
|
||||
base_path = (Path(__file__) / "../").resolve().absolute()
|
||||
self.statics_path = base_path / statics_path
|
||||
self.templates_path = base_path / templates_path
|
||||
self.console = Console()
|
||||
self.download_manager = DownloadManager()
|
||||
|
||||
def initialize_logging(self) -> None:
|
||||
"""Initialize logging.
|
||||
|
||||
May be overridden in a subclass.
|
||||
"""
|
||||
FORMAT = "%(message)s"
|
||||
logging.basicConfig(
|
||||
level="DEBUG" if self.debug else "INFO",
|
||||
format=FORMAT,
|
||||
datefmt="[%X]",
|
||||
handlers=[
|
||||
RichHandler(
|
||||
show_path=False,
|
||||
show_time=False,
|
||||
rich_tracebacks=True,
|
||||
tracebacks_show_locals=True,
|
||||
highlighter=LogHighlighter(),
|
||||
console=self.console,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
def request_exit(self) -> None:
|
||||
"""Gracefully exit the app."""
|
||||
raise GracefulExit()
|
||||
|
||||
async def _make_app(self) -> web.Application:
|
||||
"""Make the aiohttp web.Application.
|
||||
|
||||
Returns:
|
||||
New aiohttp web application.
|
||||
"""
|
||||
app = web.Application()
|
||||
|
||||
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(self.templates_path))
|
||||
|
||||
ROUTES = [
|
||||
web.get("/", self.handle_index, name="index"),
|
||||
web.get("/ws", self.handle_websocket, name="websocket"),
|
||||
web.get("/download/{key}", self.handle_download, name="download"),
|
||||
web.static("/static", self.statics_path, show_index=True, name="static"),
|
||||
]
|
||||
app.add_routes(ROUTES)
|
||||
|
||||
app.on_startup.append(self.on_startup)
|
||||
app.on_shutdown.append(self.on_shutdown)
|
||||
return app
|
||||
|
||||
async def handle_download(self, request: web.Request) -> web.StreamResponse:
|
||||
"""Handle a download request."""
|
||||
key = request.match_info["key"]
|
||||
|
||||
try:
|
||||
download_meta = await self.download_manager.get_download_metadata(key)
|
||||
except KeyError:
|
||||
raise web.HTTPNotFound(text=f"Download with key {key!r} not found")
|
||||
|
||||
response = web.StreamResponse()
|
||||
mime_type = download_meta.mime_type
|
||||
|
||||
content_type = mime_type
|
||||
if download_meta.encoding:
|
||||
content_type += f"; charset={download_meta.encoding}"
|
||||
|
||||
response.headers["Content-Type"] = content_type
|
||||
disposition = (
|
||||
"inline" if download_meta.open_method == "browser" else "attachment"
|
||||
)
|
||||
response.headers["Content-Disposition"] = (
|
||||
f"{disposition}; filename={download_meta.file_name}"
|
||||
)
|
||||
|
||||
await response.prepare(request)
|
||||
|
||||
async for chunk in self.download_manager.download(key):
|
||||
await response.write(chunk)
|
||||
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
async def on_shutdown(self, app: web.Application) -> None:
|
||||
"""Called on shutdown.
|
||||
|
||||
Args:
|
||||
app: App instance.
|
||||
"""
|
||||
|
||||
async def on_startup(self, app: web.Application) -> None:
|
||||
"""Called on startup.
|
||||
|
||||
Args:
|
||||
app: App instance.
|
||||
"""
|
||||
|
||||
self.console.print(LOGO, highlight=False)
|
||||
self.console.print(f"Serving {self.command!r} on {self.public_url}")
|
||||
self.console.print("\n[cyan]Press Ctrl+C to quit")
|
||||
|
||||
def serve(self, debug: bool = False) -> None:
|
||||
"""Serve the Textual application.
|
||||
|
||||
This will run a local webserver until it is closed with Ctrl+C
|
||||
|
||||
"""
|
||||
self.debug = debug
|
||||
self.initialize_logging()
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
try:
|
||||
loop.add_signal_handler(signal.SIGINT, self.request_exit)
|
||||
loop.add_signal_handler(signal.SIGTERM, self.request_exit)
|
||||
except NotImplementedError:
|
||||
pass
|
||||
|
||||
if self.debug:
|
||||
log.info("Running in debug mode. You may use textual dev tools.")
|
||||
|
||||
web.run_app(
|
||||
self._make_app(),
|
||||
host=self.host,
|
||||
port=self.port,
|
||||
handle_signals=False,
|
||||
loop=loop,
|
||||
print=lambda *args: None,
|
||||
)
|
||||
|
||||
@aiohttp_jinja2.template("app_index.html")
|
||||
async def handle_index(self, request: web.Request) -> dict[str, Any]:
|
||||
"""Serves the HTML for an app.
|
||||
|
||||
Args:
|
||||
request: Request object.
|
||||
|
||||
Returns:
|
||||
Template data.
|
||||
"""
|
||||
router = request.app.router
|
||||
font_size = to_int(request.query.get("fontsize", "16"), 16)
|
||||
|
||||
def get_url(route: str, **args) -> str:
|
||||
"""Get a URL from the aiohttp router."""
|
||||
path = router[route].url_for(**args)
|
||||
return f"{self.public_url}{path}"
|
||||
|
||||
def get_websocket_url(route: str, **args) -> str:
|
||||
"""Get a URL with a websocket prefix."""
|
||||
url = get_url(route, **args)
|
||||
|
||||
if self.public_url.startswith("https"):
|
||||
return "wss:" + url.split(":", 1)[1]
|
||||
else:
|
||||
return "ws:" + url.split(":", 1)[1]
|
||||
|
||||
context = {
|
||||
"font_size": font_size,
|
||||
"app_websocket_url": get_websocket_url("websocket"),
|
||||
}
|
||||
context["config"] = {
|
||||
"static": {
|
||||
"url": get_url("static", filename="/").rstrip("/") + "/",
|
||||
},
|
||||
}
|
||||
context["application"] = {
|
||||
"name": self.title,
|
||||
}
|
||||
return context
|
||||
|
||||
async def _process_messages(
|
||||
self, websocket: web.WebSocketResponse, app_service: AppService
|
||||
) -> None:
|
||||
"""Process messages from the client browser websocket.
|
||||
|
||||
Args:
|
||||
websocket: Websocket instance.
|
||||
app_service: App service.
|
||||
"""
|
||||
TEXT = WSMsgType.TEXT
|
||||
|
||||
async for message in websocket:
|
||||
if message.type != TEXT:
|
||||
continue
|
||||
envelope = message.json()
|
||||
assert isinstance(envelope, list)
|
||||
type_ = envelope[0]
|
||||
if type_ == "stdin":
|
||||
data = envelope[1]
|
||||
await app_service.send_bytes(data.encode("utf-8"))
|
||||
elif type_ == "resize":
|
||||
data = envelope[1]
|
||||
await app_service.set_terminal_size(data["width"], data["height"])
|
||||
elif type_ == "ping":
|
||||
data = envelope[1]
|
||||
await websocket.send_json(["pong", data])
|
||||
elif type_ == "blur":
|
||||
await app_service.blur()
|
||||
elif type_ == "focus":
|
||||
await app_service.focus()
|
||||
|
||||
async def handle_websocket(self, request: web.Request) -> web.WebSocketResponse:
|
||||
"""Handle the websocket that drives the remote process.
|
||||
|
||||
This is called when the browser connects to the websocket.
|
||||
|
||||
Args:
|
||||
request: Request object.
|
||||
|
||||
Returns:
|
||||
Websocket response.
|
||||
"""
|
||||
websocket = web.WebSocketResponse(heartbeat=15)
|
||||
|
||||
width = to_int(request.query.get("width", "80"), 80)
|
||||
height = to_int(request.query.get("height", "24"), 24)
|
||||
|
||||
app_service: AppService | None = None
|
||||
try:
|
||||
await websocket.prepare(request)
|
||||
app_service = AppService(
|
||||
self.command,
|
||||
write_bytes=websocket.send_bytes,
|
||||
write_str=websocket.send_str,
|
||||
close=websocket.close,
|
||||
download_manager=self.download_manager,
|
||||
debug=self.debug,
|
||||
)
|
||||
await app_service.start(width, height)
|
||||
try:
|
||||
await self._process_messages(websocket, app_service)
|
||||
finally:
|
||||
await app_service.stop()
|
||||
|
||||
except asyncio.CancelledError:
|
||||
await websocket.close()
|
||||
|
||||
except Exception as error:
|
||||
log.exception(error)
|
||||
|
||||
finally:
|
||||
if app_service is not None:
|
||||
await app_service.stop()
|
||||
|
||||
return websocket
|
@@ -1,191 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
|
||||
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
||||
* https://github.com/chjj/term.js
|
||||
* @license MIT
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* Originally forked from (with the author's permission):
|
||||
* Fabrice Bellard's javascript vt100 for jslinux:
|
||||
* http://bellard.org/jslinux/
|
||||
* Copyright (c) 2011 Fabrice Bellard
|
||||
* The original design remains. The terminal itself
|
||||
* has been extended to include xterm CSI codes, among
|
||||
* other features.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Default styles for xterm.js
|
||||
*/
|
||||
|
||||
.xterm {
|
||||
cursor: text;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
-ms-user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
|
||||
.xterm.focus,
|
||||
.xterm:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.xterm .xterm-helpers {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
/**
|
||||
* The z-index of the helpers must be higher than the canvases in order for
|
||||
* IMEs to appear on top.
|
||||
*/
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.xterm .xterm-helper-textarea {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
margin: 0;
|
||||
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
left: -9999em;
|
||||
top: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
z-index: -5;
|
||||
/** Prevent wrapping so the IME appears against the textarea at the correct position */
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.xterm .composition-view {
|
||||
/* TODO: Composition position got messed up somewhere */
|
||||
background: #000;
|
||||
color: #FFF;
|
||||
display: none;
|
||||
position: absolute;
|
||||
white-space: nowrap;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.xterm .composition-view.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.xterm .xterm-viewport {
|
||||
/* On OS X this is required in order for the scroll bar to appear fully opaque */
|
||||
background-color: #000;
|
||||
overflow-y: scroll;
|
||||
cursor: default;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.xterm .xterm-screen {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xterm .xterm-screen canvas {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.xterm .xterm-scroll-area {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.xterm-char-measure-element {
|
||||
display: inline-block;
|
||||
visibility: hidden;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -9999em;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.xterm.enable-mouse-events {
|
||||
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.xterm.xterm-cursor-pointer,
|
||||
.xterm .xterm-cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.xterm.column-select.focus {
|
||||
/* Column selection mode */
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.xterm .xterm-accessibility,
|
||||
.xterm .xterm-message {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 10;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.xterm .live-region {
|
||||
position: absolute;
|
||||
left: -9999px;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xterm-dim {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.xterm-underline-1 { text-decoration: underline; }
|
||||
.xterm-underline-2 { text-decoration: double underline; }
|
||||
.xterm-underline-3 { text-decoration: wavy underline; }
|
||||
.xterm-underline-4 { text-decoration: dotted underline; }
|
||||
.xterm-underline-5 { text-decoration: dashed underline; }
|
||||
|
||||
.xterm-strikethrough {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.xterm-screen .xterm-decoration-container .xterm-decoration {
|
||||
z-index: 6;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.xterm-decoration-overview-ruler {
|
||||
z-index: 7;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.xterm-decoration-top {
|
||||
z-index: 2;
|
||||
position: relative;
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Before Width: | Height: | Size: 58 KiB |
@@ -1,17 +0,0 @@
|
||||
function getStartUrl() {
|
||||
const url = new URL(window.location.href);
|
||||
const params = new URLSearchParams(url.search);
|
||||
params.delete("delay");
|
||||
return url.pathname + "?" + params.toString();
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const ping_url = document.body.dataset.pingurl;
|
||||
if (ping_url) {
|
||||
await fetch(ping_url, {
|
||||
method: "GET",
|
||||
mode: "no-cors",
|
||||
});
|
||||
}
|
||||
window.location.href = getStartUrl();
|
||||
}
|
File diff suppressed because one or more lines are too long
@@ -1,131 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="{{ config.static.url }}css/xterm.css" />
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto%20Mono"/>
|
||||
<script src="{{ config.static.url }}js/textual.js"></script>
|
||||
<script src="{{ config.static.url }}js/script.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: #000000;
|
||||
}
|
||||
|
||||
.dialog-container {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
position: absolute;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10;
|
||||
}
|
||||
.shade {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.intro {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
width: 640px;
|
||||
height: 240px;
|
||||
z-index: 20;
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
background-color: #000000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
body.-first-byte .intro-dialog,
|
||||
body.-first-byte .intro-dialog .shade {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease-out;
|
||||
display: none;
|
||||
}
|
||||
|
||||
body .textual-terminal {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease-out;
|
||||
}
|
||||
|
||||
body.-first-byte .textual-terminal {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
opacity: 1;
|
||||
transition: opacity 0.3s ease-out;
|
||||
}
|
||||
|
||||
body Button {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
background-color: #000000;
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
display: block;
|
||||
}
|
||||
|
||||
.closed-dialog {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
opacity: 0;
|
||||
display: none;
|
||||
}
|
||||
|
||||
body.-closed .closed-dialog {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
opacity: 1;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
#start {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#start.-delay {
|
||||
font-family: "Roboto Mono", menlo, monospace;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
footer {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 12px;
|
||||
padding: 10px 0;
|
||||
background-color: #000000;
|
||||
z-index: 5;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body data-pingurl="{{ ping_url }}">
|
||||
<div class="dialog-container intro-dialog">
|
||||
<div class="shade"></div>
|
||||
<div class="intro">
|
||||
<div>正加载命令行应用实例...<br><br>
|
||||
确保使用现代浏览器并启用 JavaScript<br>
|
||||
终端模拟器基于 XTerm.js<br>应用程序框架: Textual <br>
|
||||
© Wang Zhiyu 2024-2025, 保留此实例的所有权</div>
|
||||
<button type="button" onClick="refresh()" id="start">启动新实例</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-container closed-dialog">
|
||||
<div class="shade"></div>
|
||||
<div class="intro">
|
||||
<div class="message">实例程序已终止</div>
|
||||
<button type="button" onClick="refresh()">重新打开实例</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="terminal"
|
||||
class="textual-terminal"
|
||||
data-session-websocket-url="{{ app_websocket_url }}"
|
||||
data-font-size="{{ font_size }}"
|
||||
></div>
|
||||
</body>
|
||||
</html>
|
@@ -1,9 +1,11 @@
|
||||
[project.scripts]
|
||||
heurams = "src.__main__:main"
|
||||
[build-system]
|
||||
requires = ["setuptools>=45", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "heurams"
|
||||
version = "0.4.0"
|
||||
description = "Heuristic Assisted Memory Scheduler"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["src"]
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
31
src/heurams/context.py
Normal file
31
src/heurams/context.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
全局上下文管理模块
|
||||
"""
|
||||
from contextvars import ContextVar
|
||||
from typing import Optional
|
||||
from heurams.services.config import ConfigFile
|
||||
|
||||
config_var: ContextVar[ConfigFile] = ContextVar('config_var', default=ConfigFile("")) # 配置文件
|
||||
|
||||
runtime_var: ContextVar = ContextVar('runtime_var', default=None) # 运行时共享数据
|
||||
|
||||
class ConfigContext:
|
||||
"""
|
||||
功能完备的上下文管理器
|
||||
用于临时切换配置的作用域, 支持嵌套使用
|
||||
Example:
|
||||
>>> with ConfigContext(test_config):
|
||||
... get_daystamp() # 使用 test_config
|
||||
>>> get_daystamp() # 恢复原配置
|
||||
"""
|
||||
|
||||
def __init__(self, config_provider: ConfigFile):
|
||||
self.config_provider = config_provider
|
||||
self._token = None
|
||||
|
||||
def __enter__(self):
|
||||
self._token = config_var.set(self.config_provider)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
config_var.reset(self._token) # type: ignore
|
126
src/heurams/kernel/particles/electron.py
Normal file
126
src/heurams/kernel/particles/electron.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import toml
|
||||
import time
|
||||
import heurams.services.timer as timer
|
||||
|
||||
class Electron:
|
||||
"""电子: 记忆分析元数据及算法"""
|
||||
algorithm = "SM-2" # 暂时使用 SM-2 算法进行记忆拟合, 考虑 SM-15 替代
|
||||
|
||||
def __init__(self, content: str, metadata: dict):
|
||||
self.content = content
|
||||
self.metadata = metadata
|
||||
if metadata == {}:
|
||||
# print("NULL")
|
||||
self._default_init()
|
||||
|
||||
def _default_init(self):
|
||||
defaults = {
|
||||
'efactor': 2.5, # 易度系数, 越大越简单, 最大为5
|
||||
'real_rept': 0, # (实际)重复次数
|
||||
'rept': 0, # (有效)重复次数
|
||||
'interval': 0, # 最佳间隔
|
||||
'last_date': 0, # 上一次复习的时间戳
|
||||
'next_date': 0, # 将要复习的时间戳
|
||||
'is_activated': 0, # 激活状态
|
||||
# *NOTE: 此处"时间戳"是以天为单位的整数, 即 UNIX 时间戳除以一天的秒数取整
|
||||
'last_modify': time.time() # 最后修改时间戳(此处是UNIX时间戳)
|
||||
}
|
||||
self.metadata = defaults
|
||||
|
||||
def activate(self):
|
||||
self.metadata['is_activated'] = 1
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def modify(self, var: str, value):
|
||||
if var in self.metadata:
|
||||
self.metadata[var] = value
|
||||
self.metadata['last_modify'] = time.time()
|
||||
else:
|
||||
print(f"警告: '{var}' 非已知元数据字段")
|
||||
|
||||
def revisor(self, quality: int = 5, is_new_activation: bool = False):
|
||||
"""SM-2 算法迭代决策机制实现
|
||||
根据 quality(0 ~ 5) 进行参数迭代最佳间隔
|
||||
quality 由主程序评估
|
||||
|
||||
Args:
|
||||
quality (int): 记忆保留率量化参数
|
||||
"""
|
||||
print(f"REVISOR: {quality}, {is_new_activation}")
|
||||
if quality == -1:
|
||||
return -1
|
||||
|
||||
self.metadata['efactor'] = self.metadata['efactor'] + (
|
||||
0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02)
|
||||
)
|
||||
self.metadata['efactor'] = max(1.3, self.metadata['efactor'])
|
||||
|
||||
if quality < 3:
|
||||
# 若保留率低于 3,重置重复次数
|
||||
self.metadata['rept'] = 0
|
||||
self.metadata['interval'] = 0 # 设为0,以便下面重新计算 I(1)
|
||||
else:
|
||||
self.metadata['rept'] += 1
|
||||
|
||||
self.metadata['real_rept'] += 1
|
||||
|
||||
if is_new_activation: # 初次激活
|
||||
self.metadata['rept'] = 0
|
||||
self.metadata['efactor'] = 2.5
|
||||
|
||||
if self.metadata['rept'] == 0: # 刚被重置或初次激活后复习
|
||||
self.metadata['interval'] = 1 # I(1)
|
||||
elif self.metadata['rept'] == 1:
|
||||
self.metadata['interval'] = 6 # I(2) 经验公式
|
||||
else:
|
||||
self.metadata['interval'] = round(
|
||||
self.metadata['interval'] * self.metadata['efactor']
|
||||
)
|
||||
|
||||
self.metadata['last_date'] = timer.get_daystamp()
|
||||
self.metadata['next_date'] = timer.get_daystamp() + self.metadata['interval']
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def __str__(self):
|
||||
return (
|
||||
f"记忆单元预览 \n"
|
||||
f"内容: '{self.content}' \n"
|
||||
f"易度系数: {self.metadata['efactor']:.2f} \n"
|
||||
f"已经重复的次数: {self.metadata['rept']} \n"
|
||||
f"下次间隔: {self.metadata['interval']} 天 \n"
|
||||
f"下次复习日期时间戳: {self.metadata['next_date']}"
|
||||
)
|
||||
|
||||
def __eq__(self, other):
|
||||
if self.content == other.content:
|
||||
return True
|
||||
return False
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.content)
|
||||
|
||||
def __getitem__(self, key):
|
||||
if key == "content":
|
||||
return self.content
|
||||
if key in self.metadata:
|
||||
return self.metadata[key]
|
||||
else:
|
||||
raise KeyError(f"Key '{key}' not found in metadata.")
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key == "content":
|
||||
raise AttributeError("content 应为只读")
|
||||
self.metadata[key] = value
|
||||
self.metadata['last_modify'] = time.time()
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.metadata.keys()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.metadata)
|
||||
|
||||
@staticmethod
|
||||
def placeholder():
|
||||
return Electron("电子对象样例内容", {})
|
@@ -0,0 +1 @@
|
||||
# 音频服务
|
||||
|
@@ -0,0 +1 @@
|
||||
# 缓存服务
|
@@ -0,0 +1,35 @@
|
||||
# 配置文件服务
|
||||
import pathlib
|
||||
import toml
|
||||
import typing
|
||||
|
||||
class ConfigFile:
|
||||
def __init__(self, path: str):
|
||||
self.path = pathlib.Path(path)
|
||||
if not self.path.exists():
|
||||
self.path.touch()
|
||||
self.data = dict()
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
"""从文件加载配置数据"""
|
||||
with open(self.path, 'r') as f:
|
||||
try:
|
||||
self.data = toml.load(f)
|
||||
except toml.TomlDecodeError:
|
||||
self.data = {}
|
||||
|
||||
def modify(self, key: str, value: typing.Any):
|
||||
"""修改配置值并保存"""
|
||||
self.data[key] = value
|
||||
self.save()
|
||||
|
||||
def save(self, path: typing.Union[str, pathlib.Path] = ""):
|
||||
"""保存配置到文件"""
|
||||
save_path = pathlib.Path(path) if path else self.path
|
||||
with open(save_path, 'w') as f:
|
||||
toml.dump(self.data, f)
|
||||
|
||||
def get(self, key: str, default: typing.Any = None) -> typing.Any:
|
||||
"""获取配置值,如果不存在返回默认值"""
|
||||
return self.data.get(key, default)
|
||||
|
5
src/heurams/services/hasher.py
Normal file
5
src/heurams/services/hasher.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# 哈希服务
|
||||
import hashlib
|
||||
|
||||
def get_md5(text):
|
||||
return hashlib.md5(text.encode('utf-8')).hexdigest()
|
@@ -0,0 +1,20 @@
|
||||
# 时间服务
|
||||
from heurams.context import config_var
|
||||
import time
|
||||
|
||||
def get_daystamp() -> int:
|
||||
"""获取当前日戳(以天为单位的整数时间戳)"""
|
||||
time_override = config_var.get().get("daystamp_override", -1)
|
||||
if time_override != -1:
|
||||
return int(time_override)
|
||||
|
||||
return int((time.time() + config_var.get().get("timezone_offset")) // (24 * 3600))
|
||||
|
||||
def get_timestamp() -> float:
|
||||
"""获取 UNIX 时间戳"""
|
||||
# 搞这个类的原因是要支持可复现操作
|
||||
time_override = config_var.get().get("timestamp_override", -1)
|
||||
if time_override != -1:
|
||||
return float(time_override)
|
||||
|
||||
return time.time()
|
@@ -0,0 +1 @@
|
||||
# 文本转语音服务
|
||||
|
@@ -0,0 +1 @@
|
||||
# 版本控制集成服务
|
Reference in New Issue
Block a user