onw AMD 0.1.0: LLMs on the AMD Ryzen AI NPU through FastFlowLM
Browse files- .gitattributes +1 -0
- .gitignore +4 -0
- CHANGELOG.md +14 -0
- CHANGELOG_en.md +15 -0
- LICENSE +202 -0
- README.md +116 -0
- README_en.md +62 -0
- find_python.bat +45 -0
- images/onw-banner.jpg +3 -0
- install.ps1 +53 -0
- install.sh +47 -0
- onw/__init__.py +5 -0
- onw/__main__.py +77 -0
- onw/app.py +528 -0
- onw/dl.py +67 -0
- onw/i18n.json +390 -0
- onw/i18n.py +73 -0
- onw/lemonade.py +321 -0
- onw/logo.py +99 -0
- onw/manager.py +457 -0
- onw/relaunch.py +26 -0
- onw/server.py +371 -0
- onw/tray.py +165 -0
- onw/update.py +144 -0
- onw/web/check.html +143 -0
- onw/web/i18n.js +21 -0
- onw/web/icon.ico +0 -0
- onw/web/icon.png +0 -0
- onw/web/icon.svg +1 -0
- onw/web/index.html +214 -0
- onw/web/manage.html +460 -0
- pyproject.toml +24 -0
- requirements.txt +5 -0
- setup.bat +56 -0
- setup.sh +64 -0
- start.bat +52 -0
- start.sh +31 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
images/onw-banner.jpg filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
*.egg-info/
|
CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 更新履歴
|
| 2 |
+
|
| 3 |
+
## v0.1.0
|
| 4 |
+
|
| 5 |
+
onw(Intel NPU 版 v0.11.3)をもとにした AMD Ryzen AI NPU 版の最初の版。
|
| 6 |
+
|
| 7 |
+
- 推論を NPU 専用エンジン FastFlowLM v1.0.6 に置き換え(取得・起動・中継は Lemonade Server から移植)。初回に自動でダウンロード。
|
| 8 |
+
- モデル一覧は FastFlowLM のチャットモデル。CPU・GPU・ハイブリッドでは動かさない。
|
| 9 |
+
- 思考モードを FastFlowLM の `think` に変換し、思考を `reasoning_content` に分けて返す。
|
| 10 |
+
- Windows では FastFlowLM をジョブオブジェクトで onw のサーバーに結び付け、サーバーが落ちても NPU を握ったまま残らないように。
|
| 11 |
+
- XDNA2 の NPU とドライバーを検出し、ない PC ではダウンロードとロードを止めて理由を表示。
|
| 12 |
+
- 設定から Intel NPU 専用の項目(デバイス、先読み検証、64 トークン処理、NPUW、エキスパートのメモリ)を削除。
|
| 13 |
+
- 検証ページは応答開始までの時間と生成速度をストリーミングで測る形に。
|
| 14 |
+
- OpenVINO のエンジン一式(グラフ組み立て、KV キャッシュ、変換ツール、計測スクリプト)を削除。
|
CHANGELOG_en.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Changelog
|
| 2 |
+
|
| 3 |
+
## v0.1.0
|
| 4 |
+
|
| 5 |
+
First release of the AMD Ryzen AI NPU edition, based on onw (Intel NPU edition) v0.11.3.
|
| 6 |
+
|
| 7 |
+
- Inference replaced with the NPU-only engine FastFlowLM v1.0.6 (fetching, starting and proxying ported from
|
| 8 |
+
Lemonade Server), downloaded on first use.
|
| 9 |
+
- Models: FastFlowLM's chat models. Nothing runs on the CPU, the GPU or as a hybrid.
|
| 10 |
+
- Thinking switches mapped to FastFlowLM's `think`; the thinking comes back as `reasoning_content`.
|
| 11 |
+
- Windows: FastFlowLM is tied to onw's server by a job object, so a crashed server never leaves it holding the NPU.
|
| 12 |
+
- Detects the XDNA2 NPU and its driver; without one, downloads and loading stop and say why.
|
| 13 |
+
- Intel-NPU-only settings removed (device, prompt lookup decoding, 64-token blocks, NPUW, expert memory).
|
| 14 |
+
- The check page measures time to first token and generation speed by streaming.
|
| 15 |
+
- The OpenVINO engine (graph building, KV cache, converter, measuring scripts) removed.
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright 2026 ryugyosoft
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- ja
|
| 5 |
+
- en
|
| 6 |
+
tags:
|
| 7 |
+
- amd
|
| 8 |
+
- npu
|
| 9 |
+
- ryzen-ai
|
| 10 |
+
- xdna2
|
| 11 |
+
- fastflowlm
|
| 12 |
+
- lemonade
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
<img src="images/onw-banner.jpg" alt="onw" width="100%">
|
| 16 |
+
|
| 17 |
+
# onw AMD — 俺のNPUがこんなに動くわけない(AMD Ryzen AI NPU 版)
|
| 18 |
+
|
| 19 |
+
**日本語** | [English](README_en.md) ・ [更新履歴](CHANGELOG.md)
|
| 20 |
+
|
| 21 |
+
LLM を **AMD Ryzen AI の NPU(XDNA2)だけで** 動かすアプリです。[onw](https://huggingface.co/ryugyosoft/onw)(Intel NPU 版)の
|
| 22 |
+
UI と仕組み(タスクトレイ常駐、モデル管理ウィンドウ、OpenAI 互換 API、チャット画面、検証ページ、自動更新)はそのままに、
|
| 23 |
+
推論を NPU 専用エンジン [FastFlowLM](https://github.com/ROCm/FastFlowLM) に置き換えました。FastFlowLM の取得・起動・中継の
|
| 24 |
+
仕組みは [Lemonade Server](https://github.com/lemonade-sdk/lemonade) から移植しています。
|
| 25 |
+
|
| 26 |
+
- **NPU で動かす機能だけ**です。CPU・GPU(iGPU)・NPU+GPU のハイブリッドでは動かしません。
|
| 27 |
+
- NPU エンジンは FastFlowLM(`flm` v1.0.6、約 40 MB)だけで、初回に自動でダウンロードします。モデルは `flm list` に出る
|
| 28 |
+
チャットモデル(Qwen3.5/3.6、Gemma 4、gpt-oss、Llama 3.x、Phi-4-mini、LFM2 など)です。
|
| 29 |
+
|
| 30 |
+
## 必要なもの
|
| 31 |
+
|
| 32 |
+
- **XDNA2 の NPU を持つ AMD Ryzen AI の PC**(Ryzen AI 300 シリーズ〔Strix Point / Krackan Point〕、Ryzen AI Max〔Strix Halo〕以降)。
|
| 33 |
+
XDNA1(Ryzen 7040/8040 の Phoenix / Hawk Point)は FastFlowLM が対応していないため動きません。
|
| 34 |
+
- **NPU ドライバー**(Windows:デバイスマネージャーに「NPU Compute Accelerator Device」が出ていること。
|
| 35 |
+
入れ方は [Lemonade のドライバー案内](https://lemonade-server.ai/driver_install.html))。onw は `flm validate` で確認します。
|
| 36 |
+
- Windows 11、または Linux(`amdxdna` ドライバー)
|
| 37 |
+
- 空き容量:FastFlowLM 約 40 MB + モデル 1〜22 GB
|
| 38 |
+
|
| 39 |
+
## インストール
|
| 40 |
+
|
| 41 |
+
**Windows**(PowerShell に 1 行貼り付け)
|
| 42 |
+
|
| 43 |
+
```powershell
|
| 44 |
+
irm https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.ps1 | iex
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
`%LOCALAPPDATA%\onw-amd` に入り、タスクトレイに onw のアイコンが出て、モデルを選ぶウィンドウが開きます。
|
| 48 |
+
フォルダを直接持っている場合は `setup.bat` を実行してください。
|
| 49 |
+
|
| 50 |
+
**Linux**
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
curl -fsSL https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.sh | bash
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## 使い方
|
| 57 |
+
|
| 58 |
+
1. onw ウィンドウの「**モデル**」タブで、上の「FastFlowLM」の「入れる」を押すとモデルの一覧が出ます。
|
| 59 |
+
使いたいモデルの「ダウンロード」を押します(FastFlowLM がまだなら、先に自動で入ります)。
|
| 60 |
+
2. 「**サーバー**」タブでモデルを選んで「ロード」。状態が「動作中」になったら使えます(ロードは十数秒)。
|
| 61 |
+
3. 「チャット」でブラウザのチャット画面、「検証ページ」で応答開始までの時間と生成速度をまとめて測れます。
|
| 62 |
+
4. 他のアプリからは **OpenAI 互換 API**:base URL `http://localhost:8010/v1`、モデル名はウィンドウに表示される名前
|
| 63 |
+
(例 `qwen3-it-4b-FLM`)。
|
| 64 |
+
|
| 65 |
+
迷ったら **qwen3-it-4b-FLM**(3.1 GB、ツール呼び出し対応)、画像も読ませたいなら **qwen3.5-4b-FLM**(5.0 GB)。
|
| 66 |
+
テスト機(Ryzen AI 9 HX 370)では qwen3.5-0.8b で生成 約 44 tok/s、応答開始 約 0.5 秒でした。
|
| 67 |
+
|
| 68 |
+
- 思考モード(reasoning のラベルがあるモデル):チャット画面の「思考モード」、API の
|
| 69 |
+
`chat_template_kwargs: {"enable_thinking": true}` か `reasoning_effort`。思考は `reasoning_content` に分けて返します。
|
| 70 |
+
|
| 71 |
+
### `onw` コマンド
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
onw serve MODEL [--port 8010] [--host 0.0.0.0] [--api-key KEY] [--context 4096] [--open]
|
| 75 |
+
onw tray # 常駐アプリ(setup が起動するもの)
|
| 76 |
+
onw window [--tab models] # モデル管理・サーバー操作・設定のウィンドウ
|
| 77 |
+
onw list # この PC で動かせるモデル(* はダウンロード済み)
|
| 78 |
+
onw npu # NPU と FastFlowLM の状態(flm validate の結果も)
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
`onw serve` はモデルや FastFlowLM がなければ先にダウンロードします(コンソールで 1 回だけ動かすなら `start.bat モデル名`)。
|
| 82 |
+
|
| 83 |
+
### サーバー
|
| 84 |
+
|
| 85 |
+
- `GET /`(案内)、`/health`(モデルを読み終わると 200、読み込み中は 503)、`/v1/models`、
|
| 86 |
+
`POST /v1/chat/completions`(ストリーミング可)、`POST /v1/completions`、`/chat`、`/check`、`/api/info`
|
| 87 |
+
- 既定のポートは 8010 です(Lemonade Server がよく使う 8000 とぶつからないように)。設定画面で変えられます。
|
| 88 |
+
- CORS は開放済み。LAN に公開するときは API キー(`--api-key` または設定画面)で `/v1` を保護できます。
|
| 89 |
+
- 仕組��は Lemonade Server と同じです:`flm serve` を空いているローカルのポート(8001〜)で子プロセスとして起動し、
|
| 90 |
+
リクエストを転送します(`model` は FastFlowLM のチェックポイント名に書き換えます)。onw のサーバーが止まれば
|
| 91 |
+
FastFlowLM も必ず止まり(Windows ではジョブオブジェクト)、FastFlowLM が止まれば onw のサーバーも止まってウィンドウに理由が出ます。
|
| 92 |
+
|
| 93 |
+
### 保存場所
|
| 94 |
+
|
| 95 |
+
| もの | 場所 |
|
| 96 |
+
|---|---|
|
| 97 |
+
| 設定・ログ | `%APPDATA%\onw-amd`(Linux: `~/.config/onw-amd`) |
|
| 98 |
+
| FastFlowLM | `%APPDATA%\onw-amd\bin\flm\npu` |
|
| 99 |
+
| モデル | 保存先フォルダ(既定 `%APPDATA%\onw-amd\flm`、ウィンドウで変更可)。`FLM_MODEL_PATH` として flm に渡します |
|
| 100 |
+
|
| 101 |
+
## 構成
|
| 102 |
+
|
| 103 |
+
| ファイル | 内容 |
|
| 104 |
+
|---|---|
|
| 105 |
+
| `onw/lemonade.py` | Lemonade Server の FastFlowLM 経路の移植:XDNA2 の検出、FastFlowLM の取得(版は Lemonade の `backend_versions.json` と同じ)、`flm validate / list / pull / remove`、起動コマンド、準備完了の待ち合わせ |
|
| 106 |
+
| `onw/server.py` | OpenAI 互換サーバー:FastFlowLM を起動して転送、思考モードの変換、チャット画面・検証ページ・API キー |
|
| 107 |
+
| `onw/app.py`、`onw/manager.py`、`onw/dl.py` | 設定・モデル一覧・サーバープロセスの管理、ウィンドウの裏側(ローカル API)、ダウンロード(別プロセス) |
|
| 108 |
+
| `onw/tray.py`、`onw/update.py`、`onw/i18n.py`、`onw/web/` | トレイアイコン、自動更新、表示言語(日本語・英語・中国語)、画面 |
|
| 109 |
+
|
| 110 |
+
## ライセンス
|
| 111 |
+
|
| 112 |
+
Powered by [FastFlowLM](https://github.com/ROCm/FastFlowLM)
|
| 113 |
+
|
| 114 |
+
コードは Apache 2.0(onw と同じ)。`onw/lemonade.py` は Lemonade Server(Apache 2.0、AMD / lemonade-sdk)のコードを移植したものです。
|
| 115 |
+
FastFlowLM は onw には含まれず、実行時に公式のリリースからダウンロードされます(コードは MIT、NPU カーネルはソース非公開だが商用を含め無償)。
|
| 116 |
+
モデルはそれぞれのモデルのライセンスに従います。
|
README_en.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# onw AMD — Ore no NPU ga konna ni ugoku wake nai (AMD Ryzen AI NPU edition)
|
| 2 |
+
|
| 3 |
+
[日本語](README.md) | **English** ・ [Changelog](CHANGELOG_en.md)
|
| 4 |
+
|
| 5 |
+
An app that runs LLMs **on the AMD Ryzen AI NPU (XDNA2) alone**. It keeps the UI and the workings of
|
| 6 |
+
[onw](https://huggingface.co/ryugyosoft/onw) (the Intel NPU edition: tray app, model manager window, OpenAI-compatible API,
|
| 7 |
+
chat UI, check page, self-update) and replaces the inference with the NPU-only engine
|
| 8 |
+
[FastFlowLM](https://github.com/ROCm/FastFlowLM). How FastFlowLM is fetched, started and proxied is ported from
|
| 9 |
+
[Lemonade Server](https://github.com/lemonade-sdk/lemonade).
|
| 10 |
+
|
| 11 |
+
- **NPU only.** Nothing runs on the CPU, the GPU (iGPU) or as an NPU+GPU hybrid.
|
| 12 |
+
- The one engine is FastFlowLM (`flm` v1.0.6, about 40 MB), downloaded on first use. The models are the chat models
|
| 13 |
+
`flm list` offers (Qwen3.5 / 3.6, Gemma 4, gpt-oss, Llama 3.x, Phi-4-mini, LFM2, ...).
|
| 14 |
+
|
| 15 |
+
## Requirements
|
| 16 |
+
|
| 17 |
+
- **An AMD Ryzen AI PC with an XDNA2 NPU** (Ryzen AI 300 series [Strix Point / Krackan Point], Ryzen AI Max [Strix Halo] or newer).
|
| 18 |
+
XDNA1 (Ryzen 7040/8040, Phoenix / Hawk Point) is not supported by FastFlowLM.
|
| 19 |
+
- **The NPU driver** ("NPU Compute Accelerator Device" in the Device Manager; see
|
| 20 |
+
[Lemonade's driver guide](https://lemonade-server.ai/driver_install.html)); onw checks it with `flm validate`.
|
| 21 |
+
- Windows 11, or Linux (`amdxdna` driver)
|
| 22 |
+
- Disk: FastFlowLM about 40 MB + 1–22 GB per model
|
| 23 |
+
|
| 24 |
+
## Install
|
| 25 |
+
|
| 26 |
+
**Windows** (paste one line into PowerShell)
|
| 27 |
+
|
| 28 |
+
```powershell
|
| 29 |
+
irm https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.ps1 | iex
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
**Linux**
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
curl -fsSL https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.sh | bash
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## Use
|
| 39 |
+
|
| 40 |
+
1. In the **Models** tab of the onw window, press "Install" next to FastFlowLM to list the models, then "Download" on
|
| 41 |
+
one (FastFlowLM is installed first when missing).
|
| 42 |
+
2. In the **Server** tab pick the model and press "Load". Once it says "Running", it is ready.
|
| 43 |
+
3. "Chat" opens the chat UI; the "Check page" measures time to first token and generation speed.
|
| 44 |
+
4. Other apps: **OpenAI-compatible API**, base URL `http://localhost:8010/v1`, model name as shown in the window
|
| 45 |
+
(e.g. `qwen3-it-4b-FLM`). Thinking (models labelled reasoning): `chat_template_kwargs: {"enable_thinking": true}` or
|
| 46 |
+
`reasoning_effort`; the thinking comes back as `reasoning_content`.
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
onw serve MODEL [--port 8010] [--host 0.0.0.0] [--api-key KEY] [--context 4096] [--open]
|
| 50 |
+
onw tray | onw window [--tab models] | onw list | onw npu
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
The server works like Lemonade Server: it starts `flm serve` as a child process on a free local port (8001 and up)
|
| 54 |
+
and forwards the requests with `model` set to FastFlowLM's checkpoint name. `/health` answers 200 once the model is loaded.
|
| 55 |
+
|
| 56 |
+
## License
|
| 57 |
+
|
| 58 |
+
Powered by [FastFlowLM](https://github.com/ROCm/FastFlowLM)
|
| 59 |
+
|
| 60 |
+
Code: Apache 2.0 (as onw). `onw/lemonade.py` ports code from Lemonade Server (Apache 2.0). FastFlowLM is not part of
|
| 61 |
+
onw; it is downloaded at run time from its own release (code MIT, NPU kernels closed-source but free for any use
|
| 62 |
+
including commercial). Models follow their own licenses.
|
find_python.bat
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
rem Sets PY to a Python 3.10+ command, offering to install Python 3.12 with winget when none is found.
|
| 3 |
+
rem Used by setup.bat and start.bat: call find_python.bat then if not defined PY exit /b 1
|
| 4 |
+
set "PY="
|
| 5 |
+
set "CHECK=import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"
|
| 6 |
+
|
| 7 |
+
rem 1) the py launcher, 2) python on PATH (the Microsoft Store alias fails this check, it is not a real Python),
|
| 8 |
+
rem 3) the per-user install locations winget / python.org use
|
| 9 |
+
if not defined ONW_TEST_NOPY (
|
| 10 |
+
py -3 -c "%CHECK%" >nul 2>nul && set "PY=py -3"
|
| 11 |
+
if not defined PY python -c "%CHECK%" >nul 2>nul && set "PY=python"
|
| 12 |
+
if not defined PY for %%V in (313 312 311 310) do (
|
| 13 |
+
if not defined PY if exist "%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe""
|
| 14 |
+
)
|
| 15 |
+
)
|
| 16 |
+
if defined PY exit /b 0
|
| 17 |
+
|
| 18 |
+
echo.
|
| 19 |
+
echo Python 3.10 or newer was not found.
|
| 20 |
+
where winget >nul 2>nul
|
| 21 |
+
if errorlevel 1 (
|
| 22 |
+
echo winget is not available either. Please install Python from https://www.python.org/downloads/
|
| 23 |
+
echo ^(check "Add python.exe to PATH"^), then run this again.
|
| 24 |
+
start "" https://www.python.org/downloads/
|
| 25 |
+
exit /b 1
|
| 26 |
+
)
|
| 27 |
+
choice /c YN /m "Install Python 3.12 for this user with winget now (accepts the Python license)"
|
| 28 |
+
if errorlevel 2 (
|
| 29 |
+
echo Please install Python 3.10+ from https://www.python.org/downloads/ and run this again.
|
| 30 |
+
exit /b 1
|
| 31 |
+
)
|
| 32 |
+
winget install -e --id Python.Python.3.12 --scope user --accept-package-agreements --accept-source-agreements
|
| 33 |
+
if errorlevel 1 (
|
| 34 |
+
echo winget could not install Python. Please install it from https://www.python.org/downloads/
|
| 35 |
+
exit /b 1
|
| 36 |
+
)
|
| 37 |
+
rem the new PATH is not visible in this window yet: use the installed files directly
|
| 38 |
+
if exist "%LOCALAPPDATA%\Programs\Python\Python312\python.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Python312\python.exe""
|
| 39 |
+
if not defined PY if exist "%LOCALAPPDATA%\Programs\Python\Launcher\py.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Launcher\py.exe" -3"
|
| 40 |
+
if not defined PY (
|
| 41 |
+
echo Python was installed but could not be found yet. Please open a new window and run this again.
|
| 42 |
+
exit /b 1
|
| 43 |
+
)
|
| 44 |
+
echo [setup] using %PY%
|
| 45 |
+
exit /b 0
|
images/onw-banner.jpg
ADDED
|
Git LFS Details
|
install.ps1
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# onw AMD one-line installer for Windows. In PowerShell:
|
| 2 |
+
# irm https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.ps1 | iex
|
| 3 |
+
# Downloads onw AMD into %LOCALAPPDATA%\onw-amd (no git / hf needed) and runs setup.bat, which finds or installs Python,
|
| 4 |
+
# sets up the environment, adds "onw" to the Start menu and starts the tray app. Run it again to update onw.
|
| 5 |
+
$ErrorActionPreference = "Stop"
|
| 6 |
+
$ProgressPreference = "SilentlyContinue"
|
| 7 |
+
$repo = "ryugyosoft/onwAMD"
|
| 8 |
+
$dest = Join-Path $env:LOCALAPPDATA "onw-amd"
|
| 9 |
+
Write-Host ""
|
| 10 |
+
Write-Host "onw AMD - Ore no NPU ga konna ni ugoku wake nai (AMD Ryzen AI NPU)"
|
| 11 |
+
Write-Host "Installing into $dest ..."
|
| 12 |
+
function Get-WithRetry($uri, $out) {
|
| 13 |
+
for ($i = 1; $i -le 4; $i++) {
|
| 14 |
+
try {
|
| 15 |
+
if ($out) { Invoke-WebRequest -UseBasicParsing -Uri $uri -OutFile $out; return }
|
| 16 |
+
return Invoke-RestMethod $uri
|
| 17 |
+
} catch {
|
| 18 |
+
if ($i -eq 4) { throw }
|
| 19 |
+
Write-Host " retrying ($($_.Exception.Message)) ..."
|
| 20 |
+
Start-Sleep -Seconds (2 * $i)
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
if ($env:ONW_AMD_SOURCE) {
|
| 25 |
+
# a local copy instead of the hub (before onw AMD is published, or offline):
|
| 26 |
+
# $env:ONW_AMD_SOURCE = "D:\path\to\onw"; Get-Content "D:\path\to\onw\install.ps1" -Raw | iex
|
| 27 |
+
$src = (Resolve-Path $env:ONW_AMD_SOURCE).Path
|
| 28 |
+
Write-Host "Copying from $src ..."
|
| 29 |
+
$n = 0
|
| 30 |
+
Get-ChildItem -Path $src -Recurse -File | Where-Object {
|
| 31 |
+
$rel = $_.FullName.Substring($src.Length).TrimStart("\")
|
| 32 |
+
$rel -notmatch '^(\.git|\.venv|\.update)(\\|$)' -and $rel -notmatch '(^|\\)(__pycache__|[^\\]*\.egg-info)(\\|$)'
|
| 33 |
+
} | ForEach-Object {
|
| 34 |
+
$out = Join-Path $dest $_.FullName.Substring($src.Length).TrimStart("\")
|
| 35 |
+
New-Item -ItemType Directory -Force -Path (Split-Path $out) | Out-Null
|
| 36 |
+
Copy-Item $_.FullName $out -Force
|
| 37 |
+
$n++
|
| 38 |
+
}
|
| 39 |
+
Write-Host "Copied $n files. Starting setup (Python, packages, Start menu, tray) ..."
|
| 40 |
+
} else {
|
| 41 |
+
$info = Get-WithRetry "https://huggingface.co/api/models/$repo" $null
|
| 42 |
+
foreach ($s in $info.siblings) {
|
| 43 |
+
$f = $s.rfilename
|
| 44 |
+
if ($f -eq ".gitattributes") { continue }
|
| 45 |
+
$out = Join-Path $dest ($f -replace "/", "\")
|
| 46 |
+
New-Item -ItemType Directory -Force -Path (Split-Path $out) | Out-Null
|
| 47 |
+
Get-WithRetry "https://huggingface.co/$repo/resolve/main/$f" $out
|
| 48 |
+
}
|
| 49 |
+
Write-Host "Downloaded $($info.siblings.Count - 1) files. Starting setup (Python, packages, Start menu, tray) ..."
|
| 50 |
+
}
|
| 51 |
+
Set-Content -Path (Join-Path $dest ".onw-installed") -Value "installer" -Encoding ascii # onw may update itself here
|
| 52 |
+
Start-Process -FilePath (Join-Path $dest "setup.bat") -WorkingDirectory $dest
|
| 53 |
+
Write-Host "A setup window opened. When it finishes, onw AMD appears in the task tray and asks which model to download."
|
install.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# onw AMD one-line installer for Ubuntu. In a terminal:
|
| 3 |
+
# curl -fsSL https://huggingface.co/ryugyosoft/onwAMD/resolve/main/install.sh | bash
|
| 4 |
+
# Downloads onw AMD into ~/onw-amd (no git / hf needed) and runs setup.sh (system packages, Python environment,
|
| 5 |
+
# application list entry, top-bar app). Run it again to update onw.
|
| 6 |
+
set -e
|
| 7 |
+
repo="ryugyosoft/onwAMD"
|
| 8 |
+
dest="$HOME/onw-amd"
|
| 9 |
+
echo
|
| 10 |
+
echo "onw AMD - Ore no NPU ga konna ni ugoku wake nai (AMD Ryzen AI NPU)"
|
| 11 |
+
echo "Installing into $dest ..."
|
| 12 |
+
python3 - "$repo" "$dest" <<'PY'
|
| 13 |
+
import json, os, sys, time, urllib.request
|
| 14 |
+
repo, dest = sys.argv[1], sys.argv[2]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def fetch(url, tries=4): # the hub redirects to a CDN; a reset connection is retried
|
| 18 |
+
for i in range(tries):
|
| 19 |
+
try:
|
| 20 |
+
with urllib.request.urlopen(url, timeout=60) as r:
|
| 21 |
+
return r.read()
|
| 22 |
+
except Exception as e:
|
| 23 |
+
if i == tries - 1:
|
| 24 |
+
raise
|
| 25 |
+
print(f" retrying ({e}) ...", flush=True)
|
| 26 |
+
time.sleep(2 * (i + 1))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
info = json.loads(fetch(f"https://huggingface.co/api/models/{repo}"))
|
| 30 |
+
files = [s["rfilename"] for s in info["siblings"] if s["rfilename"] != ".gitattributes"]
|
| 31 |
+
for f in files:
|
| 32 |
+
out = os.path.join(dest, f)
|
| 33 |
+
os.makedirs(os.path.dirname(out), exist_ok=True)
|
| 34 |
+
data = fetch(f"https://huggingface.co/{repo}/resolve/main/{f}")
|
| 35 |
+
if f.endswith((".sh", ".py", ".toml", ".txt", ".md", ".html")):
|
| 36 |
+
data = data.replace(b"\r\n", b"\n") # scripts must have Unix line endings
|
| 37 |
+
with open(out, "wb") as fh:
|
| 38 |
+
fh.write(data)
|
| 39 |
+
open(os.path.join(dest, ".onw-installed"), "w").write("installer\n") # onw may update itself here
|
| 40 |
+
print(f"Downloaded {len(files)} files.")
|
| 41 |
+
PY
|
| 42 |
+
cd "$dest"
|
| 43 |
+
if [ -r /dev/tty ] && [ -w /dev/tty ]; then
|
| 44 |
+
bash setup.sh </dev/tty # piped from curl: setup's questions (sudo) read the terminal
|
| 45 |
+
else
|
| 46 |
+
bash setup.sh # no terminal (a script, CI): run as is
|
| 47 |
+
fi
|
onw/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""onw AMD - Ore no NPU ga konna ni ugoku wake nai (俺のNPUがこんなに動くわけない), AMD Ryzen AI NPU edition.
|
| 2 |
+
|
| 3 |
+
LLMs entirely on the AMD Ryzen AI NPU (XDNA2), through FastFlowLM, the NPU-only engine of Lemonade Server.
|
| 4 |
+
"""
|
| 5 |
+
__version__ = "0.1.0"
|
onw/__main__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""onw AMD - Ore no NPU ga konna ni ugoku wake nai (俺のNPUがこんなに動くわけない), AMD Ryzen AI NPU edition
|
| 2 |
+
|
| 3 |
+
onw serve MODEL [--port 8010] [--host 127.0.0.1] [--context 4096] [--api-key KEY] [--open]
|
| 4 |
+
chat UI + OpenAI-compatible API
|
| 5 |
+
onw tray resident tray / top-bar app
|
| 6 |
+
onw window [--tab models|server|settings] model manager, server control, settings
|
| 7 |
+
onw list the NPU models onw can run here
|
| 8 |
+
onw npu the NPU and FastFlowLM
|
| 9 |
+
|
| 10 |
+
MODEL is a model name from `onw list` (e.g. llama3.2-1b-FLM or qwen3-4b-FLM), downloaded first when missing.
|
| 11 |
+
Everything runs on the AMD NPU (XDNA2) through FastFlowLM, the NPU-only engine Lemonade Server uses.
|
| 12 |
+
"""
|
| 13 |
+
import argparse, sys
|
| 14 |
+
|
| 15 |
+
# `python -m onw` started in the home folder (a desktop launcher: GNOME starts it in ~ and keeps an old Exec= until
|
| 16 |
+
# the next login) puts ~ first on sys.path, and the install folder ~/onw is then imported as an empty namespace
|
| 17 |
+
# package "onw" that hides the real ~/onw/onw. Put the install folder first, drop ~, and import onw again.
|
| 18 |
+
if getattr(sys.modules.get("onw"), "__file__", None) is None:
|
| 19 |
+
import os
|
| 20 |
+
_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 21 |
+
_home = os.path.normcase(os.path.abspath(os.path.expanduser("~")))
|
| 22 |
+
_norm = lambda p: os.path.normcase(os.path.abspath(p or os.getcwd()))
|
| 23 |
+
sys.path[:] = [_root] + [p for p in sys.path if _norm(p) not in (_home, os.path.normcase(_root))]
|
| 24 |
+
for _m in [m for m in sys.modules if m == "onw" or m.startswith("onw.")]:
|
| 25 |
+
del sys.modules[_m]
|
| 26 |
+
import onw # noqa: E402,F401 (the real package now)
|
| 27 |
+
os.chdir(_root)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def list_models():
|
| 31 |
+
from onw import app
|
| 32 |
+
cfg = app.load_config()
|
| 33 |
+
inst = app.installed(cfg)
|
| 34 |
+
for m in app.catalog(cfg):
|
| 35 |
+
mark = "*" if m["key"] in inst else " "
|
| 36 |
+
print(f"{mark} {m['key']:<32} {m['size_gb'] or 0:5.1f} GB {','.join(m['labels'])}")
|
| 37 |
+
if not app.flm_catalog(cfg):
|
| 38 |
+
print(" (the models are listed once FastFlowLM is installed: onw window -> Models, or onw serve MODEL)")
|
| 39 |
+
print("* = downloaded")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def npu():
|
| 43 |
+
from onw import lemonade
|
| 44 |
+
n = lemonade.npu()
|
| 45 |
+
print(f"CPU: {n.get('name')}")
|
| 46 |
+
print(lemonade.npu_text())
|
| 47 |
+
print(f"FastFlowLM: {lemonade.installed_version() or 'not installed'} (onw uses {lemonade.VERSION})")
|
| 48 |
+
if lemonade.binary():
|
| 49 |
+
ok, msg = lemonade.flm_validate()
|
| 50 |
+
print("flm validate:", "ok" if ok else msg)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help", "help"):
|
| 55 |
+
print(__doc__)
|
| 56 |
+
return
|
| 57 |
+
cmd, argv = sys.argv[1], sys.argv[2:]
|
| 58 |
+
if cmd == "serve":
|
| 59 |
+
from onw.server import main as serve
|
| 60 |
+
serve(argv)
|
| 61 |
+
elif cmd == "window":
|
| 62 |
+
from onw.app import window
|
| 63 |
+
window(argv[argv.index("--tab") + 1] if "--tab" in argv else "server",
|
| 64 |
+
argv[argv.index("--updated") + 1] if "--updated" in argv else None)
|
| 65 |
+
elif cmd == "tray":
|
| 66 |
+
from onw.tray import main as tray
|
| 67 |
+
tray(argv)
|
| 68 |
+
elif cmd == "list":
|
| 69 |
+
list_models()
|
| 70 |
+
elif cmd == "npu":
|
| 71 |
+
npu()
|
| 72 |
+
else:
|
| 73 |
+
sys.exit(f"unknown command {cmd!r}\n{__doc__}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
onw/app.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""onw shared state: config, catalog, model folders, server process control; the window (web view) opener.
|
| 2 |
+
|
| 3 |
+
The server runs as its own process (pid in <config>/server.pid), so the tray and this window control the same
|
| 4 |
+
server and it keeps running when the window is closed. The server starts the NPU engine, FastFlowLM (onw.lemonade),
|
| 5 |
+
as its own child. flm keeps the models in the save folder (<config>/models unless the user picks another one).
|
| 6 |
+
"""
|
| 7 |
+
import json, os, shutil, subprocess, sys, threading, time, urllib.request, webbrowser
|
| 8 |
+
|
| 9 |
+
from . import lemonade
|
| 10 |
+
|
| 11 |
+
DEFAULTS = {"model": "", "port": 8010, "lan": False, "api_key": "", "context": 4096, "autostart_server": True,
|
| 12 |
+
"login_start": False, "models_dir": "", "update_check": True, "lang": "auto"}
|
| 13 |
+
CONTEXTS = ["1024", "2048", "4096", "8192", "16384", "32768", "65536", "131072"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ------------------------------------------------------------------ config
|
| 17 |
+
|
| 18 |
+
_CFG_LOCK = threading.RLock() # the tray's threads (manager requests, downloads, the menu) share config.json
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def config_dir():
|
| 22 |
+
base = os.environ.get("APPDATA") if os.name == "nt" else os.path.join(os.path.expanduser("~"), ".config")
|
| 23 |
+
d = os.path.join(base or os.path.expanduser("~"), "onw-amd")
|
| 24 |
+
os.makedirs(d, exist_ok=True)
|
| 25 |
+
return d
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_config():
|
| 29 |
+
p = os.path.join(config_dir(), "config.json")
|
| 30 |
+
with _CFG_LOCK:
|
| 31 |
+
try:
|
| 32 |
+
cfg = {**DEFAULTS, **json.load(open(p, encoding="utf8"))}
|
| 33 |
+
except FileNotFoundError:
|
| 34 |
+
cfg = dict(DEFAULTS)
|
| 35 |
+
except (OSError, ValueError):
|
| 36 |
+
# unreadable (a crash mid-write before 0.11.1 wrote it in place): keep a copy rather than let the next
|
| 37 |
+
# save overwrite the user's folders and API key with the defaults
|
| 38 |
+
try:
|
| 39 |
+
shutil.copy(p, p + ".bad")
|
| 40 |
+
except OSError:
|
| 41 |
+
pass
|
| 42 |
+
cfg = dict(DEFAULTS)
|
| 43 |
+
if cfg.get("context") == 1024 and not cfg.get("context_chosen"): # the old default: the paged KV cache (0.10)
|
| 44 |
+
cfg["context"] = DEFAULTS["context"] # costs nothing until a long chat uses it
|
| 45 |
+
return cfg
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def save_config(cfg):
|
| 49 |
+
"""Written to a temporary file and moved into place: a crash never leaves half a config."""
|
| 50 |
+
p = os.path.join(config_dir(), "config.json")
|
| 51 |
+
with _CFG_LOCK:
|
| 52 |
+
with open(p + ".tmp", "w", encoding="utf8") as f:
|
| 53 |
+
json.dump(cfg, f, indent=1, ensure_ascii=False)
|
| 54 |
+
os.replace(p + ".tmp", p)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def update_config(**changes):
|
| 58 |
+
"""Read, change and save the config as one step (no other thread's save in between)."""
|
| 59 |
+
with _CFG_LOCK:
|
| 60 |
+
cfg = load_config()
|
| 61 |
+
cfg.update(changes)
|
| 62 |
+
save_config(cfg)
|
| 63 |
+
return cfg
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def default_models_dir():
|
| 67 |
+
"""The default save folder, FLM_MODEL_PATH (flm keeps the models in its "models" subfolder)."""
|
| 68 |
+
return os.path.join(config_dir(), "flm")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def models_dir(cfg):
|
| 72 |
+
"""The save folder. One that cannot be used (an unplugged drive, a mistyped path) falls back to the default, so
|
| 73 |
+
the window still opens and the setting can be changed there."""
|
| 74 |
+
d = cfg.get("models_dir") or default_models_dir()
|
| 75 |
+
try:
|
| 76 |
+
os.makedirs(d, exist_ok=True)
|
| 77 |
+
return d
|
| 78 |
+
except OSError:
|
| 79 |
+
d = default_models_dir()
|
| 80 |
+
os.makedirs(d, exist_ok=True)
|
| 81 |
+
return d
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def models_dir_missing(cfg):
|
| 85 |
+
"""The chosen save folder when it cannot be used (models_dir() fell back to the default), else None."""
|
| 86 |
+
d = cfg.get("models_dir")
|
| 87 |
+
return d if d and os.path.normcase(os.path.abspath(models_dir(cfg))) != os.path.normcase(os.path.abspath(d)) else None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_LOCKS = []
|
| 91 |
+
from . import __version__, i18n
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def title():
|
| 95 |
+
"""The window title (the version first: an open window is found by the "onw AMD " prefix, see raise_window)."""
|
| 96 |
+
return f"onw AMD {__version__} - {i18n.T('俺のNPUがこんなに動くわけない', lang=i18n.current(load_config()))}"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def single_instance(name):
|
| 100 |
+
"""True when no other onw process holds the lock `name` (held until this process exits)."""
|
| 101 |
+
if os.name == "nt":
|
| 102 |
+
import ctypes
|
| 103 |
+
k = ctypes.WinDLL("kernel32", use_last_error=True)
|
| 104 |
+
k.CreateMutexW.restype = ctypes.c_void_p
|
| 105 |
+
h = k.CreateMutexW(None, False, f"Local\\onw-{name}")
|
| 106 |
+
if not h:
|
| 107 |
+
return True
|
| 108 |
+
_LOCKS.append(h)
|
| 109 |
+
return ctypes.get_last_error() != 183 # ERROR_ALREADY_EXISTS
|
| 110 |
+
import fcntl
|
| 111 |
+
f = open(os.path.join(config_dir(), f"{name}.lock"), "w")
|
| 112 |
+
try:
|
| 113 |
+
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 114 |
+
except OSError:
|
| 115 |
+
f.close()
|
| 116 |
+
return False
|
| 117 |
+
_LOCKS.append(f)
|
| 118 |
+
return True
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # the install folder (holds onw/)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def icon_path():
|
| 125 |
+
web = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web")
|
| 126 |
+
return os.path.join(web, "icon.ico" if os.name == "nt" else "icon.png")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def launcher_exec():
|
| 130 |
+
"""Exec= of the Linux launchers: the venv's onw console script (`python -m onw` started in ~ imports the install
|
| 131 |
+
folder ~/onw as an empty onw package - onw/__main__.py guards against that too); -m only when there is no script."""
|
| 132 |
+
script = os.path.join(os.path.dirname(sys.executable), "onw")
|
| 133 |
+
return f'"{script}" tray' if os.path.isfile(script) else f'"{sys.executable}" -m onw tray'
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def refresh_shortcut():
|
| 137 |
+
"""Give the Start-menu / application-list entry the onw icon (entries made by setup before the icon existed)."""
|
| 138 |
+
ico = icon_path()
|
| 139 |
+
try:
|
| 140 |
+
if os.name == "nt":
|
| 141 |
+
lnk = os.path.join(os.environ.get("APPDATA", ""), r"Microsoft\Windows\Start Menu\Programs\onw AMD.lnk")
|
| 142 |
+
if not os.path.isfile(lnk) or "icon.ico".encode("utf-16-le") in open(lnk, "rb").read():
|
| 143 |
+
return
|
| 144 |
+
q = lambda s: s.replace("'", "''")
|
| 145 |
+
subprocess.run(["powershell", "-NoProfile", "-Command",
|
| 146 |
+
f"$s = (New-Object -ComObject WScript.Shell).CreateShortcut('{q(lnk)}'); "
|
| 147 |
+
f"$s.IconLocation = '{q(ico)},0'; $s.Save()"], creationflags=0x08000000, timeout=60)
|
| 148 |
+
else:
|
| 149 |
+
p = os.path.expanduser("~/.local/share/applications/onw-amd.desktop")
|
| 150 |
+
if not os.path.isfile(p):
|
| 151 |
+
return
|
| 152 |
+
s = open(p, encoding="utf8").read()
|
| 153 |
+
t = "".join("Icon=" + ico + "\n" if l.startswith("Icon=") else l for l in s.splitlines(True))
|
| 154 |
+
# the console script, not `python -m onw`: GNOME starts launchers in ~ (Path= is not honoured), and with -m
|
| 155 |
+
# the install folder ~/onw would shadow the onw package (quoted: a home folder with a space)
|
| 156 |
+
t = "".join(f"Exec={launcher_exec()}\n" if l.startswith("Exec=") else l for l in t.splitlines(True))
|
| 157 |
+
if not any(l.startswith("Path=") for l in t.splitlines()):
|
| 158 |
+
t = "".join(l + ("Path=" + ROOT + "\n" if l.startswith("Exec=") else "") for l in t.splitlines(True))
|
| 159 |
+
if t != s:
|
| 160 |
+
open(p, "w", encoding="utf8").write(t)
|
| 161 |
+
auto = os.path.expanduser("~/.config/autostart/onw-amd-tray.desktop")
|
| 162 |
+
if os.path.isfile(auto) and f"Exec={launcher_exec()}\n" not in open(auto, encoding="utf8").read():
|
| 163 |
+
set_login_start(True) # the login entry the same way
|
| 164 |
+
except (OSError, subprocess.SubprocessError):
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def raise_window():
|
| 169 |
+
"""Bring the already open onw window to the front (Windows; elsewhere the window manager decides). Found by its
|
| 170 |
+
title's "onw <version> - " start, so a window of another version (just updated) is found too."""
|
| 171 |
+
if os.name == "nt":
|
| 172 |
+
import ctypes, re
|
| 173 |
+
from ctypes import wintypes
|
| 174 |
+
u = ctypes.windll.user32
|
| 175 |
+
found = []
|
| 176 |
+
|
| 177 |
+
def each(h, _):
|
| 178 |
+
n = u.GetWindowTextLengthW(h)
|
| 179 |
+
if n:
|
| 180 |
+
b = ctypes.create_unicode_buffer(n + 1)
|
| 181 |
+
u.GetWindowTextW(h, b, n + 1)
|
| 182 |
+
if re.match(r"onw AMD \d+\.\d+\.\d+ - ", b.value) and u.IsWindowVisible(h):
|
| 183 |
+
found.append(h)
|
| 184 |
+
return True
|
| 185 |
+
u.EnumWindows(ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(each), 0)
|
| 186 |
+
if found:
|
| 187 |
+
u.ShowWindow(found[0], 9) # SW_RESTORE
|
| 188 |
+
u.SetForegroundWindow(found[0])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def usable_ram(ram):
|
| 192 |
+
"""GB a model may take on a PC with `ram` GB (85%), or None when unknown."""
|
| 193 |
+
return None if ram is None else ram * 0.85
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def memory_estimate(size_gb):
|
| 197 |
+
"""GB a model of `size_gb` on disk needs while it runs on the NPU (the NPU shares the system memory): the weights
|
| 198 |
+
plus about 1 GB for the engine and the KV cache. A rough guide, or None."""
|
| 199 |
+
return None if not size_gb else size_gb + 1.0
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def fits(mem, ram):
|
| 203 |
+
return ram is None or mem is None or mem <= usable_ram(ram)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def total_ram_gb():
|
| 207 |
+
try:
|
| 208 |
+
import psutil
|
| 209 |
+
return psutil.virtual_memory().total / 2**30
|
| 210 |
+
except Exception:
|
| 211 |
+
return None
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------------ models
|
| 215 |
+
#
|
| 216 |
+
# A model key is Lemonade's name for a FastFlowLM model: "llama3.2-1b-FLM" for flm's checkpoint "llama3.2:1b".
|
| 217 |
+
# flm keeps the models itself, in the save folder (lemonade.flm_dir).
|
| 218 |
+
|
| 219 |
+
_FLM_CACHE = {"t": 0.0, "models": {}, "error": ""}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def flm_catalog(cfg=None, refresh=False):
|
| 223 |
+
"""flm's chat models (cached for a minute: `flm list` is a program run), {} before FastFlowLM is installed."""
|
| 224 |
+
if not lemonade.binary():
|
| 225 |
+
return {}
|
| 226 |
+
if refresh or time.time() - _FLM_CACHE["t"] > 60:
|
| 227 |
+
try:
|
| 228 |
+
_FLM_CACHE.update(models=lemonade.flm_models(cfg), error="")
|
| 229 |
+
except Exception as e:
|
| 230 |
+
_FLM_CACHE["error"] = str(e)
|
| 231 |
+
_FLM_CACHE["t"] = time.time()
|
| 232 |
+
return _FLM_CACHE["models"]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def catalog(cfg=None):
|
| 236 |
+
"""[{key, title, checkpoint, size_gb, labels, image}] of the models onw can download and run here."""
|
| 237 |
+
return [{"key": name, "title": name, "checkpoint": m["checkpoint"], "size_gb": m["size"], "labels": m["labels"],
|
| 238 |
+
"image": "vision" in m["labels"]} for name, m in flm_catalog(cfg).items()]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def catalog_entry(key, cfg=None):
|
| 242 |
+
return next((m for m in catalog(cfg) if m["key"] == key), None)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def installed(cfg):
|
| 246 |
+
"""{model key: folder flm keeps it in} of the models flm has pulled."""
|
| 247 |
+
return {name: lemonade.flm_dir(cfg) for name, m in flm_catalog(cfg).items() if m["installed"]}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def model_title(key):
|
| 251 |
+
return key
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# ------------------------------------------------------------------ server process (shared by tray and window)
|
| 255 |
+
|
| 256 |
+
PIDFILE = lambda: os.path.join(config_dir(), "server.pid")
|
| 257 |
+
_SERVER_LOCK = threading.RLock() # start / stop / restart one at a time (the window, the tray menu, an update)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _alive(pid, created=None):
|
| 261 |
+
"""The process is running (not a zombie) and, given its start time, is the same process - not a later one that
|
| 262 |
+
reused the pid (after a reboot, or on Linux simply later)."""
|
| 263 |
+
try:
|
| 264 |
+
import psutil
|
| 265 |
+
p = psutil.Process(pid)
|
| 266 |
+
if p.status() == psutil.STATUS_ZOMBIE:
|
| 267 |
+
return False
|
| 268 |
+
return created is None or abs(p.create_time() - created) < 2
|
| 269 |
+
except Exception:
|
| 270 |
+
return False
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _pidfile():
|
| 274 |
+
try:
|
| 275 |
+
return json.load(open(PIDFILE()))
|
| 276 |
+
except (OSError, ValueError):
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def server_info():
|
| 281 |
+
d = _pidfile()
|
| 282 |
+
try:
|
| 283 |
+
return d if d and _alive(d["pid"], d.get("created")) else None
|
| 284 |
+
except KeyError:
|
| 285 |
+
return None
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def server_status(cfg=None):
|
| 289 |
+
"""stopped | loading | running (answers /health) | failed (the process ended without being stopped: an error, the
|
| 290 |
+
port in use, killed for memory - stop_server removes the pid file, so a pid file left behind means that)."""
|
| 291 |
+
d = server_info()
|
| 292 |
+
if d is None:
|
| 293 |
+
return "failed" if _pidfile() is not None else "stopped"
|
| 294 |
+
try:
|
| 295 |
+
urllib.request.urlopen(f"http://127.0.0.1:{d['port']}/health", timeout=1.5)
|
| 296 |
+
return "running"
|
| 297 |
+
except OSError:
|
| 298 |
+
return "loading"
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def failure_reason():
|
| 302 |
+
"""Why the server ended (for the window), from the end of its log."""
|
| 303 |
+
try:
|
| 304 |
+
tail = open(os.path.join(config_dir(), "server.log"), encoding="utf8", errors="replace").read()[-4000:]
|
| 305 |
+
except OSError:
|
| 306 |
+
return ""
|
| 307 |
+
lines = [l.strip() for l in tail.splitlines() if l.strip()]
|
| 308 |
+
for l in reversed(lines):
|
| 309 |
+
if "Errno 98" in l or "Errno 10048" in l or "address already in use" in l.lower():
|
| 310 |
+
return i18n.T("ポートが使用中です(別のサーバーが動いていませんか?)")
|
| 311 |
+
if "Error" in l or "error" in l:
|
| 312 |
+
return l[-300:]
|
| 313 |
+
return (lines[-1][-300:] if lines else "") or i18n.T("サーバーが予期せず終了しました(メモリ不足の可能性)")
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def clear_stale_server():
|
| 317 |
+
"""At tray start: a pid file whose process is gone (a crash, a reboot) is left over from before - not a failure
|
| 318 |
+
to show now, and it would keep the model from loading automatically."""
|
| 319 |
+
if _pidfile() is not None and server_info() is None:
|
| 320 |
+
try:
|
| 321 |
+
os.remove(PIDFILE())
|
| 322 |
+
except OSError:
|
| 323 |
+
pass
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _port_free(host, port):
|
| 327 |
+
import socket
|
| 328 |
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 329 |
+
try:
|
| 330 |
+
if os.name != "nt":
|
| 331 |
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 332 |
+
s.bind((host, port))
|
| 333 |
+
return True
|
| 334 |
+
except OSError:
|
| 335 |
+
return False
|
| 336 |
+
finally:
|
| 337 |
+
s.close()
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def start_server(cfg):
|
| 341 |
+
with _SERVER_LOCK:
|
| 342 |
+
_start_server(cfg)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _start_server(cfg):
|
| 346 |
+
_stop_server()
|
| 347 |
+
model = installed(cfg).get(cfg["model"], cfg["model"])
|
| 348 |
+
if not model:
|
| 349 |
+
raise ValueError("no model selected")
|
| 350 |
+
host = "0.0.0.0" if cfg["lan"] else "127.0.0.1"
|
| 351 |
+
if not _port_free(host, int(cfg["port"])):
|
| 352 |
+
raise ValueError(i18n.T("ポート {0} は別のプログラムが使っています(設定でポートを変えてください)", cfg["port"]))
|
| 353 |
+
args = [sys.executable, "-m", "onw", "serve", cfg["model"], "--port", str(cfg["port"]), "--host", host,
|
| 354 |
+
"--context", str(cfg["context"])]
|
| 355 |
+
env = {**os.environ, "PYTHONUTF8": "1", "FLM_MODEL_PATH": lemonade.flm_dir(cfg)}
|
| 356 |
+
if cfg.get("api_key"):
|
| 357 |
+
env["ONW_API_KEY"] = cfg["api_key"]
|
| 358 |
+
log = open(os.path.join(config_dir(), "server.log"), "w", encoding="utf8")
|
| 359 |
+
kw = {"creationflags": subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
|
| 360 |
+
| subprocess.BELOW_NORMAL_PRIORITY_CLASS} if os.name == "nt" else {"start_new_session": True}
|
| 361 |
+
p = subprocess.Popen(args, cwd=models_dir(cfg), stdout=log, stderr=subprocess.STDOUT, env=env, **kw)
|
| 362 |
+
log.close()
|
| 363 |
+
created = None
|
| 364 |
+
try:
|
| 365 |
+
import psutil
|
| 366 |
+
pr = psutil.Process(p.pid)
|
| 367 |
+
created = pr.create_time()
|
| 368 |
+
if os.name != "nt":
|
| 369 |
+
pr.nice(5) # below the desktop (preexec_fn is unsafe in a threaded process)
|
| 370 |
+
except Exception:
|
| 371 |
+
pass
|
| 372 |
+
info = {"pid": p.pid, "created": created, "port": cfg["port"], "model": cfg["model"], "path": model}
|
| 373 |
+
with open(PIDFILE() + ".tmp", "w") as f:
|
| 374 |
+
json.dump(info, f)
|
| 375 |
+
os.replace(PIDFILE() + ".tmp", PIDFILE())
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def stop_server():
|
| 379 |
+
with _SERVER_LOCK:
|
| 380 |
+
_stop_server()
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _stop_server():
|
| 384 |
+
d = server_info()
|
| 385 |
+
if d:
|
| 386 |
+
try:
|
| 387 |
+
import psutil
|
| 388 |
+
proc = psutil.Process(d["pid"])
|
| 389 |
+
procs = proc.children(recursive=True) + [proc] # the venv launcher starts the real python
|
| 390 |
+
for q in procs:
|
| 391 |
+
q.terminate()
|
| 392 |
+
psutil.wait_procs(procs, timeout=10)
|
| 393 |
+
for q in procs:
|
| 394 |
+
if q.is_running():
|
| 395 |
+
q.kill()
|
| 396 |
+
except Exception:
|
| 397 |
+
pass
|
| 398 |
+
left = _pidfile()
|
| 399 |
+
if left is None or d is None or left.get("pid") == d.get("pid"): # never a newer server's file
|
| 400 |
+
try:
|
| 401 |
+
os.remove(PIDFILE())
|
| 402 |
+
except OSError:
|
| 403 |
+
pass
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def api_url(cfg):
|
| 407 |
+
return f"http://localhost:{cfg['port']}/v1"
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
# ------------------------------------------------------------------ login autostart
|
| 411 |
+
|
| 412 |
+
def set_login_start(on):
|
| 413 |
+
if os.name == "nt":
|
| 414 |
+
# the per-user Run key: Unicode-safe (a batch file in the Startup folder was read in the OEM code page and broke
|
| 415 |
+
# for user names outside it) and no console flashing at logon
|
| 416 |
+
import winreg
|
| 417 |
+
old = os.path.join(os.environ["APPDATA"], "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "onw-tray.cmd")
|
| 418 |
+
if os.path.exists(old):
|
| 419 |
+
os.remove(old)
|
| 420 |
+
pyw = os.path.join(os.path.dirname(sys.executable), "pythonw.exe")
|
| 421 |
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0,
|
| 422 |
+
winreg.KEY_SET_VALUE) as k:
|
| 423 |
+
if on:
|
| 424 |
+
winreg.SetValueEx(k, "onw-amd", 0, winreg.REG_SZ, f'"{pyw}" -m onw tray')
|
| 425 |
+
else:
|
| 426 |
+
try:
|
| 427 |
+
winreg.DeleteValue(k, "onw-amd")
|
| 428 |
+
except FileNotFoundError:
|
| 429 |
+
pass
|
| 430 |
+
return
|
| 431 |
+
d = os.path.join(os.path.expanduser("~"), ".config", "autostart")
|
| 432 |
+
os.makedirs(d, exist_ok=True)
|
| 433 |
+
path = os.path.join(d, "onw-amd-tray.desktop")
|
| 434 |
+
content = ("[Desktop Entry]\nType=Application\nName=onw AMD\nComment=LLMs on the AMD Ryzen AI NPU\n"
|
| 435 |
+
f"Exec={launcher_exec()}\nPath={ROOT}\nX-GNOME-Autostart-enabled=true\n")
|
| 436 |
+
if on:
|
| 437 |
+
with open(path, "w", encoding="utf8") as f:
|
| 438 |
+
f.write(content)
|
| 439 |
+
elif os.path.exists(path):
|
| 440 |
+
os.remove(path)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def open_path(p):
|
| 444 |
+
if os.name == "nt":
|
| 445 |
+
os.startfile(p)
|
| 446 |
+
else:
|
| 447 |
+
subprocess.Popen(["xdg-open", p])
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# ------------------------------------------------------------------ window
|
| 451 |
+
|
| 452 |
+
def window(tab="server", updated=None):
|
| 453 |
+
"""The onw window: onw/web/manage.html in a small native web view (pywebview), talking to the manager (the tray
|
| 454 |
+
process; started here when no tray is running). Without pywebview the same page opens in the browser.
|
| 455 |
+
`updated`: the version just installed (the page says so once)."""
|
| 456 |
+
if not single_instance("window"):
|
| 457 |
+
raise_window()
|
| 458 |
+
return
|
| 459 |
+
from . import manager as mgr
|
| 460 |
+
info = mgr.find_manager()
|
| 461 |
+
own = info is None
|
| 462 |
+
if own:
|
| 463 |
+
info = mgr.serve()
|
| 464 |
+
url = mgr.page_url(info, tab)
|
| 465 |
+
if updated:
|
| 466 |
+
url = url.replace("?token=", f"?updated={updated}&token=")
|
| 467 |
+
try:
|
| 468 |
+
import webview
|
| 469 |
+
except ImportError:
|
| 470 |
+
webview = None
|
| 471 |
+
if webview is None:
|
| 472 |
+
webbrowser.open(url)
|
| 473 |
+
if own: # keep our manager alive while the page is in use:
|
| 474 |
+
try: # until the page has not asked for a minute
|
| 475 |
+
while time.time() - mgr.LAST_SEEN[0] < 60:
|
| 476 |
+
time.sleep(5)
|
| 477 |
+
finally:
|
| 478 |
+
try:
|
| 479 |
+
os.remove(mgr.INFO())
|
| 480 |
+
except OSError:
|
| 481 |
+
pass
|
| 482 |
+
return
|
| 483 |
+
|
| 484 |
+
class Api:
|
| 485 |
+
def pick_folder(self, initial=""):
|
| 486 |
+
w = webview.windows[0]
|
| 487 |
+
r = w.create_file_dialog(webview.FOLDER_DIALOG, directory=initial or os.path.expanduser("~"))
|
| 488 |
+
return (list(r)[0] if r else None)
|
| 489 |
+
|
| 490 |
+
win = webview.create_window(title(), url, js_api=Api(), width=780, height=460, min_size=(420, 320))
|
| 491 |
+
|
| 492 |
+
def follow():
|
| 493 |
+
"""The tray restarted (new manager: new port and token). After an update this window's own code is old too:
|
| 494 |
+
close it and open a fresh window on the new code; otherwise just load the page from the new manager."""
|
| 495 |
+
cur, gone = info, 0
|
| 496 |
+
resume = os.path.join(config_dir(), "resume.json") # written by a tray restarting after an update
|
| 497 |
+
while True:
|
| 498 |
+
time.sleep(2)
|
| 499 |
+
m = mgr.find_manager()
|
| 500 |
+
if m is None: # the tray quit: close too, unless it is restarting
|
| 501 |
+
gone = 0 if os.path.exists(resume) else gone + 1
|
| 502 |
+
if gone >= 2 and mgr.find_manager() is None:
|
| 503 |
+
win.destroy()
|
| 504 |
+
return
|
| 505 |
+
continue
|
| 506 |
+
gone = 0
|
| 507 |
+
if m["pid"] != cur["pid"]:
|
| 508 |
+
cur = m
|
| 509 |
+
try:
|
| 510 |
+
v = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{m['port']}/api/state?token={m['token']}",
|
| 511 |
+
timeout=5).read())["version"]
|
| 512 |
+
except Exception:
|
| 513 |
+
v = ""
|
| 514 |
+
if v and v != __version__:
|
| 515 |
+
try:
|
| 516 |
+
page = win.evaluate_js("location.hash.slice(1)") or "server"
|
| 517 |
+
except Exception:
|
| 518 |
+
page = "server"
|
| 519 |
+
subprocess.Popen([sys.executable, "-m", "onw.relaunch", str(os.getpid()), "window", "--tab", page,
|
| 520 |
+
"--updated", v], cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
| 521 |
+
**({"creationflags": subprocess.CREATE_NO_WINDOW | subprocess.DETACHED_PROCESS}
|
| 522 |
+
if os.name == "nt" else {"start_new_session": True}))
|
| 523 |
+
win.destroy() # the new window takes the single-instance lock once we exit
|
| 524 |
+
return
|
| 525 |
+
win.load_url(mgr.page_url(m, tab))
|
| 526 |
+
if not own:
|
| 527 |
+
threading.Thread(target=follow, daemon=True).start()
|
| 528 |
+
webview.start(icon=icon_path())
|
onw/dl.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download one model (or just FastFlowLM) as its own process: the manager can cancel it by ending the process, and
|
| 2 |
+
a crash inside a download cannot take the tray down. Progress goes to a small JSON file the manager reads.
|
| 3 |
+
|
| 4 |
+
usage (internal): python -m onw.dl KEY STATUS_FILE a model ("...-FLM"): FastFlowLM first when missing,
|
| 5 |
+
then `flm pull`
|
| 6 |
+
python -m onw.dl --engine STATUS_FILE just FastFlowLM
|
| 7 |
+
"""
|
| 8 |
+
import json, os, re, subprocess, sys, time
|
| 9 |
+
|
| 10 |
+
from . import app, lemonade
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Status:
|
| 14 |
+
def __init__(self, path):
|
| 15 |
+
self.path, self.last = path, 0.0
|
| 16 |
+
|
| 17 |
+
def __call__(self, frac, text, force=False):
|
| 18 |
+
if not force and time.time() - self.last < 0.5:
|
| 19 |
+
return
|
| 20 |
+
self.last = time.time()
|
| 21 |
+
with open(self.path + ".tmp", "w", encoding="utf8") as f:
|
| 22 |
+
json.dump({"frac": round(frac, 4), "text": text}, f, ensure_ascii=False)
|
| 23 |
+
os.replace(self.path + ".tmp", self.path)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def engine(status):
|
| 27 |
+
if not lemonade.up_to_date():
|
| 28 |
+
lemonade.install(status)
|
| 29 |
+
status(1.0, "FastFlowLM " + lemonade.VERSION, force=True)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def model(key, status):
|
| 33 |
+
"""`flm pull <checkpoint>`; progress from its "[FLM] Downloading X/Y: file" lines (lemonade: flm_download)."""
|
| 34 |
+
cfg = app.load_config()
|
| 35 |
+
ok, msg = lemonade.flm_validate(cfg)
|
| 36 |
+
if not ok:
|
| 37 |
+
sys.exit(f"FastFlowLM NPU check failed: {msg}")
|
| 38 |
+
m = lemonade.flm_models(cfg).get(key)
|
| 39 |
+
if m is None:
|
| 40 |
+
sys.exit(f"FastFlowLM has no model {key}")
|
| 41 |
+
p = subprocess.Popen(lemonade.flm_pull_command(m["checkpoint"]), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 42 |
+
env=lemonade.flm_env(cfg), text=True, encoding="utf8", errors="replace", **lemonade.NO_WINDOW)
|
| 43 |
+
pat = re.compile(r"Downloading\s+(\d+)/(\d+):\s*(.*)")
|
| 44 |
+
for line in p.stdout:
|
| 45 |
+
print(line, end="", flush=True)
|
| 46 |
+
g = pat.search(line)
|
| 47 |
+
if g:
|
| 48 |
+
i, n = int(g.group(1)), int(g.group(2))
|
| 49 |
+
status((i - 1) / max(n, 1), f"{i}/{n}: {g.group(3).strip()[:60]}", force=True)
|
| 50 |
+
if p.wait() != 0:
|
| 51 |
+
sys.exit(f"flm pull failed (exit code {p.returncode})")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main():
|
| 55 |
+
args = sys.argv[1:]
|
| 56 |
+
if args[0] == "--engine":
|
| 57 |
+
engine(Status(args[1]))
|
| 58 |
+
return
|
| 59 |
+
key, status = args[0], Status(args[1])
|
| 60 |
+
status(0.0, "…", force=True)
|
| 61 |
+
engine(lambda frac, text, force=False: status(0.0, text, force))
|
| 62 |
+
model(key, status)
|
| 63 |
+
status(1.0, "done", force=True)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
main()
|
onw/i18n.json
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"en": {
|
| 3 |
+
"0 = 無効": "0 = off",
|
| 4 |
+
"1 = 無効": "1 = off",
|
| 5 |
+
"2ターン会話: 1ターン目": "Two-turn chat: turn 1",
|
| 6 |
+
"2ターン会話: 2ターン目": "Two-turn chat: turn 2",
|
| 7 |
+
"API キー(任意)": "API key (optional)",
|
| 8 |
+
"LAN からの接続を許可する(API キー推奨)": "Allow connections from the LAN (API key recommended)",
|
| 9 |
+
"NPU でロード中…": "Loading on the NPU…",
|
| 10 |
+
"NPU エンジン": "NPU engine",
|
| 11 |
+
"OpenAI API のURLをコピー": "Copy the OpenAI API URL",
|
| 12 |
+
"URL をコピーしました": "URL copied",
|
| 13 |
+
"auto(OS に合わせる)": "auto (follow the OS)",
|
| 14 |
+
"onw AMD 検証ページ": "onw AMD check page",
|
| 15 |
+
"onw v{0} が使えます": "onw v{0} is available",
|
| 16 |
+
"onw の更新": "onw update",
|
| 17 |
+
"onw の更新中です。終わってからダウンロードしてください": "onw is updating; download after it finishes",
|
| 18 |
+
"onw を更新します。サーバーは一度止まり、更新後に同じモデルを読み込み直します。よろしいですか?": "Update onw? The server stops for a moment and loads the same model again after the update.",
|
| 19 |
+
"onw を更新(v{0})": "Update onw (v{0})",
|
| 20 |
+
"onw を開く(モデル・サーバー・設定)": "Open onw (models, server, settings)",
|
| 21 |
+
"v{0} に更新しました": "Updated to v{0}",
|
| 22 |
+
"v{0} に更新しました。onw を起動し直してください": "Updated to v{0}. Please restart onw",
|
| 23 |
+
"v{0} に更新しました。再起動します…": "Updated to v{0}. Restarting…",
|
| 24 |
+
"{0} を削除しますか?\n{1}": "Delete {0}?\n{1}",
|
| 25 |
+
"{0} トークン": "{0} tokens",
|
| 26 |
+
"{0}秒": "{0} s",
|
| 27 |
+
"「更新」を押すと自動で入れ替えて再起動します。": "Choose \"Update\" to replace it and restart automatically.",
|
| 28 |
+
"あとで": "Later",
|
| 29 |
+
"この PC ではメモリ不足の可能性": "May not fit this PC's memory",
|
| 30 |
+
"この PC には XDNA2 の NPU が見つかりません(Ryzen AI 300 シリーズ以降と NPU ドライバーが必要です)": "No XDNA2 NPU found on this PC (a Ryzen AI 300 series or newer and the NPU driver are needed)",
|
| 31 |
+
"この PC のメモリ {0} GB ・ メモリ目安は今の設定での値": "This PC: {0} GB RAM · estimates use the current settings",
|
| 32 |
+
"このサーバー(OpenAI互換API)に実際のリクエストを送って、動作と速度を確かめます。": "Sends real requests to this server (OpenAI-compatible API) to check that it works and how fast.",
|
| 33 |
+
"このフォルダの onw は 1 行インストーラーで入れたものではないので、自動更新できません": "This onw was not installed with the one-line installer, so it cannot update itself",
|
| 34 |
+
"このフォルダは自動更新の対象外です(1 行インストーラーで入れ直してください)": "This folder cannot update itself (reinstall with the one-line installer)",
|
| 35 |
+
"このモデルはロード中です。先にアンロードしてください。": "This model is loaded. Unload it first.",
|
| 36 |
+
"この画像に描かれている図形と文字を、色も含めて一文で答えてください。": "In one sentence, describe the shapes and the text in this image, including their colors.",
|
| 37 |
+
"この画像を説明してください。": "Describe this image.",
|
| 38 |
+
"この画面は onw のウィンドウかトレイから開いてください": "Open this page from the onw window or the tray",
|
| 39 |
+
"すべてNPUで実行中": "Running entirely on the NPU",
|
| 40 |
+
"そのフォルダは使えません: {0}": "That folder cannot be used: {0}",
|
| 41 |
+
"そのモデルはありません": "No such model",
|
| 42 |
+
"その都市の人口は?一文で。": "What is that city's population? One sentence.",
|
| 43 |
+
"なし": "No",
|
| 44 |
+
"アンロード": "Unload",
|
| 45 |
+
"アンロード(サーバー停止)": "Unload (stop the server)",
|
| 46 |
+
"エラー: {0}": "Error: {0}",
|
| 47 |
+
"キャンセル": "Cancel",
|
| 48 |
+
"コピー": "Copy",
|
| 49 |
+
"コピーしてください": "Copy this",
|
| 50 |
+
"コンテキスト長": "Context length",
|
| 51 |
+
"コンテキスト長は会話で使える最大の長さで、FastFlowLM に --ctx-len として渡します。長いほど使うメモリが増えます。変更はモデルの再ロード後に反映されます。": "The context length is the longest a conversation can get; it is passed to FastFlowLM as --ctx-len. Longer takes more memory. Changes apply when the model is loaded again.",
|
| 52 |
+
"コード向け": "for code",
|
| 53 |
+
"サイズ": "Size",
|
| 54 |
+
"サーバー": "Server",
|
| 55 |
+
"サーバーが予期せず終了しました(メモリ不足の可能性)": "The server stopped unexpectedly (possibly out of memory)",
|
| 56 |
+
"サーバーに接続できません": "Cannot connect to the server",
|
| 57 |
+
"ダウンロード": "Download",
|
| 58 |
+
"ダウンロードが終わってから更新してください": "Update after the download finishes",
|
| 59 |
+
"ダウンロードに失敗: {0}": "Download failed: {0}",
|
| 60 |
+
"ダウンロード中 {0}/{1}": "Downloading {0}/{1}",
|
| 61 |
+
"ダウンロード中 {0}・ウィンドウを閉じても続きます": "Downloading {0} · keeps going if you close the window",
|
| 62 |
+
"ダウンロード中(進み具合)": "Downloading (progress)",
|
| 63 |
+
"チャット": "Chat",
|
| 64 |
+
"チャットを開く": "Open chat",
|
| 65 |
+
"ツール呼び出し": "tool calling",
|
| 66 |
+
"テキスト生成": "Text generation",
|
| 67 |
+
"デバイス": "Device",
|
| 68 |
+
"パッケージを更新中(数分かかることがあります)": "Updating packages (may take a few minutes)",
|
| 69 |
+
"フォルダが見つかりません: {0}": "Folder not found: {0}",
|
| 70 |
+
"フォルダのパスを入力してください": "Enter the folder path",
|
| 71 |
+
"フォルダを開く": "Open folder",
|
| 72 |
+
"プロンプト": "Prompt",
|
| 73 |
+
"ポート": "Port",
|
| 74 |
+
"ポート {0} は別のプログラムが使っています(設定でポートを変えてください)": "Port {0} is used by another program (change the port in the settings)",
|
| 75 |
+
"ポートかコンテキスト長の値が不正です": "Invalid port or context length",
|
| 76 |
+
"ポートが使用中です(別のサーバーが動いていませんか?)": "The port is in use (is another server running?)",
|
| 77 |
+
"メッセージを入力してください。": "Type a message.",
|
| 78 |
+
"メッセージを入力するか、画像を添付・貼り付け・ドロップしてください。": "Type a message, or attach, paste or drop an image.",
|
| 79 |
+
"メッセージ(Enterで送信、Shift+Enterで改行)": "Message (Enter to send, Shift+Enter for a new line)",
|
| 80 |
+
"メモリ 約{0} GB": "memory ~{0} GB",
|
| 81 |
+
"メモリ目安": "Memory (est.)",
|
| 82 |
+
"モデル": "Models",
|
| 83 |
+
"モデルの一覧は、FastFlowLM(約 40 MB)を入れると出ます": "The models are listed once FastFlowLM (about 40 MB) is installed",
|
| 84 |
+
"モデルは読み込まれていません": "No model loaded",
|
| 85 |
+
"モデルをロード": "Load model",
|
| 86 |
+
"モデルを削除": "Delete model",
|
| 87 |
+
"モデル名": "Model name",
|
| 88 |
+
"モデル未選択": "No model selected",
|
| 89 |
+
"ログ": "Log",
|
| 90 |
+
"ログイン時にトレイを起動する": "Start the tray at login",
|
| 91 |
+
"ロード": "Load",
|
| 92 |
+
"ロードしています…": "Loading…",
|
| 93 |
+
"ロードできません: {0}": "Cannot load: {0}",
|
| 94 |
+
"ロードに失敗": "Load failed",
|
| 95 |
+
"ロード中": "Loading",
|
| 96 |
+
"ロード中…": "Loading…",
|
| 97 |
+
"ロード失敗": "Load failed",
|
| 98 |
+
"ロード済み": "Loaded",
|
| 99 |
+
"・メモリ 約{0} GB はこの PC では不足の可能性": " · ~{0} GB may not fit this PC",
|
| 100 |
+
"一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。モデルはすべて AMD NPU(XDNA2)の上だけで動きます(NPU 専用エンジン FastFlowLM)。": "One model at a time. Pick another model and press \"Switch\" to unload the current one and load it. Every model runs on the AMD NPU (XDNA2) alone, through the NPU-only engine FastFlowLM.",
|
| 101 |
+
"今すぐ確認": "Check now",
|
| 102 |
+
"今は v{0}。「更新する」で入れ替えて再起動します": "You have v{0}. \"Update\" replaces it and restarts",
|
| 103 |
+
"他のアプリからは <code id=\"base\"></code> を OpenAI の base URL に、モデル名は <code id=\"mid\"></code> を指定してください(APIキー設定時は <code>Authorization: Bearer キー</code>)。": "In other apps, use <code id=\"base\"></code> as the OpenAI base URL and <code id=\"mid\"></code> as the model name (with an API key set: <code>Authorization: Bearer KEY</code>).",
|
| 104 |
+
"会話をクリア": "Clear the conversation",
|
| 105 |
+
"使うモデル": "Model to use",
|
| 106 |
+
"使用中": "In use",
|
| 107 |
+
"保存": "Save",
|
| 108 |
+
"保存しました": "Saved",
|
| 109 |
+
"保存先": "Save to",
|
| 110 |
+
"保存先 {0} が使えないため、既定のフォルダを使っています(「変更…」で選び直せます)": "The save folder {0} cannot be used, so the default folder is used (choose another with \"Change…\")",
|
| 111 |
+
"保存先を {0} にしますか?\n今の保存先のモデルはそのまま残ります(新しい保存先には出ません)。": "Use {0} as the save folder?\nThe models in the current one stay there (they are not shown for the new one).",
|
| 112 |
+
"俺のNPUがこんなに動くわけない": "There's no way my NPU runs this well",
|
| 113 |
+
"停止": "Stop",
|
| 114 |
+
"停止中": "Stopped",
|
| 115 |
+
"入れる": "Install",
|
| 116 |
+
"入れ替え中": "Replacing files",
|
| 117 |
+
"切り替え": "Switch",
|
| 118 |
+
"別のダウンロードが進行中です": "Another download is in progress",
|
| 119 |
+
"削除": "Remove",
|
| 120 |
+
"動作中": "Running",
|
| 121 |
+
"取得済み": "Downloaded",
|
| 122 |
+
"可": "Yes",
|
| 123 |
+
"回答": "Answer",
|
| 124 |
+
"場所": "Location",
|
| 125 |
+
"変更…": "Change…",
|
| 126 |
+
"変更点": "What's new",
|
| 127 |
+
"失敗": "Failed",
|
| 128 |
+
"完了": "Done",
|
| 129 |
+
"対応": "Yes",
|
| 130 |
+
"応答開始": "First token",
|
| 131 |
+
"応答開始 {0}秒 · {1}トークン · {2} tok/s · 文脈 {3}{4}": "first token {0} s · {1} tokens · {2} tok/s · context {3}{4}",
|
| 132 |
+
"思考": "Thinking",
|
| 133 |
+
"思考モード": "Thinking mode",
|
| 134 |
+
"接続なし": "Offline",
|
| 135 |
+
"接続中…": "Connecting…",
|
| 136 |
+
"文脈は約1000トークン": "Context: about 1000 tokens",
|
| 137 |
+
"文脈は約{0}トークン": "Context: about {0} tokens",
|
| 138 |
+
"新しいバージョン v{0} があります": "Version v{0} is available",
|
| 139 |
+
"新しいバージョンがあります": "A new version is available",
|
| 140 |
+
"新しい会話": "New chat",
|
| 141 |
+
"新し���会話です。": "New conversation.",
|
| 142 |
+
"新しい版はありません": "No newer version",
|
| 143 |
+
"日本の四季について、それぞれ一文ずつ説明してください。": "Describe each of Japan's four seasons in one sentence.",
|
| 144 |
+
"日本の首都はどこですか?一文で。": "What is the capital of Japan? One sentence.",
|
| 145 |
+
"日本語": "日本語",
|
| 146 |
+
"更新": "Update",
|
| 147 |
+
"更新あり": "Update",
|
| 148 |
+
"更新あり v{0}": "Update v{0}",
|
| 149 |
+
"更新しました": "Updated",
|
| 150 |
+
"更新する": "Update",
|
| 151 |
+
"更新できませんでした": "Update failed",
|
| 152 |
+
"更新できませんでした: {0}": "Update failed: {0}",
|
| 153 |
+
"更新を確認できませんでした: {0}": "Could not check for updates: {0}",
|
| 154 |
+
"更新を確認できませんでした(オフライン?)": "Could not check for updates (offline?)",
|
| 155 |
+
"最大トークン": "Max tokens",
|
| 156 |
+
"最新版です": "You're up to date",
|
| 157 |
+
"最終確認 {0}": "Last checked {0}",
|
| 158 |
+
"未インストール": "not installed",
|
| 159 |
+
"未取得": "Not downloaded",
|
| 160 |
+
"未設定なら何を入れても通ります": "Not set: any key is accepted",
|
| 161 |
+
"東京は日本の首都であり、政治・経済・文化の中心地である。江戸時代には徳川幕府が置かれ、1868年の明治維新で東京と改称された。現在は約1400万人が暮らす世界有数の大都市で、多くの企業や大学が集まっている。": "Tokyo is the capital of Japan and the center of its politics, economy and culture. In the Edo period it was the seat of the Tokugawa shogunate, and it was renamed Tokyo in the Meiji Restoration of 1868. Today about 14 million people live there, making it one of the largest cities in the world, home to many companies and universities.",
|
| 162 |
+
"検証を実行": "Run checks",
|
| 163 |
+
"検証ページ": "Check page",
|
| 164 |
+
"検証ページを開く": "Open check page",
|
| 165 |
+
"次の文章を、元の表現をなるべく使って2文に要約してください。": "Summarize the following text in two sentences, reusing its wording as much as possible.",
|
| 166 |
+
"止まった理由: {0}": "Why it stopped: {0}",
|
| 167 |
+
"温度": "Temperature",
|
| 168 |
+
"準備中…": "Preparing…",
|
| 169 |
+
"状態": "Status",
|
| 170 |
+
"生成速度": "Decode speed",
|
| 171 |
+
"画像": "Image",
|
| 172 |
+
"画像も読めます": "Reads images too",
|
| 173 |
+
"画像を添付": "Attach an image",
|
| 174 |
+
"画像入力": "Image input",
|
| 175 |
+
"確認中…": "Checking…",
|
| 176 |
+
"简体中文": "简体中文",
|
| 177 |
+
"約{0} GB": "~{0} GB",
|
| 178 |
+
"終了(サーバーも停止)": "Quit (stops the server too)",
|
| 179 |
+
"結果": "Result",
|
| 180 |
+
"繰り返し抑制": "Repetition penalty",
|
| 181 |
+
"考えてから答えます": "thinks before answering",
|
| 182 |
+
"要約": "Summary",
|
| 183 |
+
"言語": "Language",
|
| 184 |
+
"設定": "Settings",
|
| 185 |
+
"設定は保存しました。サーバーを新しい設定で今すぐ再起動しますか?(キャンセルしても、次にモデルを読み込むときから反映されます)": "Settings saved. Restart the server with the new settings now? (Cancel keeps them for the next model load.)",
|
| 186 |
+
"読み込み中…": "Loading…",
|
| 187 |
+
"起動時と 1 日ごとに更新を確認する": "Check for updates at startup and daily",
|
| 188 |
+
"起動時に前回ロードしたモデルを自動でロードする": "Load the last model automatically at startup",
|
| 189 |
+
"送信": "Send",
|
| 190 |
+
"項目": "Test",
|
| 191 |
+
"(ロード済み)": " (loaded)",
|
| 192 |
+
"(停止しました)": "(stopped)",
|
| 193 |
+
"(再利用 {0})": " (reused {0})",
|
| 194 |
+
"(画像)": "(image)"
|
| 195 |
+
},
|
| 196 |
+
"zh": {
|
| 197 |
+
"0 = 無効": "0 = 关闭",
|
| 198 |
+
"1 = 無効": "1 = 关闭",
|
| 199 |
+
"2ターン会話: 1ターン目": "两轮对话:第 1 轮",
|
| 200 |
+
"2ターン会話: 2ターン目": "两轮对话:第 2 轮",
|
| 201 |
+
"API キー(任意)": "API 密钥(可选)",
|
| 202 |
+
"LAN からの接続を許可する(API キー推奨)": "允许局域网连接(建议设置 API 密钥)",
|
| 203 |
+
"NPU でロード中…": "正在 NPU 上加载…",
|
| 204 |
+
"NPU エンジン": "NPU 引擎",
|
| 205 |
+
"OpenAI API のURLをコピー": "复制 OpenAI API 地址",
|
| 206 |
+
"URL をコピーしました": "已复制 URL",
|
| 207 |
+
"auto(OS に合わせる)": "auto(跟随系统)",
|
| 208 |
+
"onw AMD 検証ページ": "onw AMD 验证页面",
|
| 209 |
+
"onw v{0} が使えます": "onw v{0} 已发布",
|
| 210 |
+
"onw の更新": "onw 更新",
|
| 211 |
+
"onw の更新中です。終わってからダウンロードしてください": "onw 正在更新,请在完成后再下载",
|
| 212 |
+
"onw を更新します。サーバーは一度止まり、更新後に同じモデルを読み込み直します。よろしいですか?": "要更新 onw 吗?服务器会暂时停止,更新后重新加载同一个模型。",
|
| 213 |
+
"onw を更新(v{0})": "更新 onw(v{0})",
|
| 214 |
+
"onw を開く(モデル・サーバー・設定)": "打开 onw(模型・服务器・设置)",
|
| 215 |
+
"v{0} に更新しました": "已更新到 v{0}",
|
| 216 |
+
"v{0} に更新しました。onw を起動し直してください": "已更新到 v{0},请重新启动 onw",
|
| 217 |
+
"v{0} に更新しました。再起動します…": "已更新到 v{0},正在重启…",
|
| 218 |
+
"{0} を削除しますか?\n{1}": "删除 {0}?\n{1}",
|
| 219 |
+
"{0} トークン": "{0} token",
|
| 220 |
+
"{0}秒": "{0} 秒",
|
| 221 |
+
"「更新」を押すと��動で入れ替えて再起動します。": "点击“更新”即可自动替换并重启。",
|
| 222 |
+
"あとで": "稍后",
|
| 223 |
+
"この PC ではメモリ不足の可能性": "本机内存可能不足",
|
| 224 |
+
"この PC には XDNA2 の NPU が見つかりません(Ryzen AI 300 シリーズ以降と NPU ドライバーが必要です)": "此电脑上未找到 XDNA2 NPU(需要 Ryzen AI 300 系列或更新的处理器以及 NPU 驱动)",
|
| 225 |
+
"この PC のメモリ {0} GB ・ メモリ目安は今の設定での値": "本机内存 {0} GB · 内存估计基于当前设置",
|
| 226 |
+
"このサーバー(OpenAI互換API)に実際のリクエストを送って、動作と速度を確かめます。": "向本服务器(OpenAI 兼容 API)发送真实请求,检查运行情况和速度。",
|
| 227 |
+
"このフォルダの onw は 1 行インストーラーで入れたものではないので、自動更新できません": "此 onw 不是用一行安装命令安装的,无法自动更新",
|
| 228 |
+
"このフォルダは自動更新の対象外です(1 行インストーラーで入れ直してください)": "此文件夹不支持自动更新(请用一行安装命令重新安装)",
|
| 229 |
+
"このモデルはロード中です。先にアンロードしてください。": "该模型正在使用中,请先卸载。",
|
| 230 |
+
"この画像に描かれている図形と文字を、色も含めて一文で答えてください。": "请用一句话说明这张图片中的图形和文字,包括颜色。",
|
| 231 |
+
"この画像を説明してください。": "请描述这张图片。",
|
| 232 |
+
"この画面は onw のウィンドウかトレイから開いてください": "请从 onw 窗口或托盘图标打开此页面",
|
| 233 |
+
"すべてNPUで実行中": "全部在 NPU 上运行",
|
| 234 |
+
"そのフォルダは使えません: {0}": "无法使用该文件夹:{0}",
|
| 235 |
+
"そのモデルはありません": "没有该模型",
|
| 236 |
+
"その都市の人口は?一文で。": "那座城市的人口是多少?用一句话回答。",
|
| 237 |
+
"なし": "不支持",
|
| 238 |
+
"アンロード": "卸载",
|
| 239 |
+
"アンロード(サーバー停止)": "卸载(停止服务器)",
|
| 240 |
+
"エラー: {0}": "错误:{0}",
|
| 241 |
+
"キャンセル": "取消",
|
| 242 |
+
"コピー": "复制",
|
| 243 |
+
"コピーしてください": "请复制",
|
| 244 |
+
"コンテキスト長": "上下文长度",
|
| 245 |
+
"コンテキスト長は会話で使える最大の長さで、FastFlowLM に --ctx-len として渡します。長いほど使うメモリが増えます。変更はモデルの再ロード後に反映されます。": "上下文长度是对话可使用的最大长度,会作为 --ctx-len 传给 FastFlowLM。越长占用的内存越多。更改在重新加载模型后生效。",
|
| 246 |
+
"コード向け": "适合编程",
|
| 247 |
+
"サイズ": "大小",
|
| 248 |
+
"サーバー": "服务器",
|
| 249 |
+
"サーバーが予期せず終了しました(メモリ不足の可能性)": "服务器意外停止(可能是内存不足)",
|
| 250 |
+
"サーバーに接続できません": "无法连接服务器",
|
| 251 |
+
"ダウンロード": "下载",
|
| 252 |
+
"ダウンロードが終わってから更新してください": "请在下载完成后再更新",
|
| 253 |
+
"ダウンロードに失敗: {0}": "下载失败:{0}",
|
| 254 |
+
"ダウンロード中 {0}/{1}": "下载中 {0}/{1}",
|
| 255 |
+
"ダウンロード中 {0}・ウィンドウを閉じても続きます": "下载中 {0}・关闭窗口也会继续",
|
| 256 |
+
"ダウンロード中(進み具合)": "下载中(进度)",
|
| 257 |
+
"チャット": "聊天",
|
| 258 |
+
"チャットを開く": "打开聊天",
|
| 259 |
+
"ツール呼び出し": "工具调用",
|
| 260 |
+
"テキスト生成": "文本生成",
|
| 261 |
+
"デバイス": "设备",
|
| 262 |
+
"パッケージを更新中(数分かかることがあります)": "正在更新软件包(可能需要几分钟)",
|
| 263 |
+
"フォルダが見つかりません: {0}": "找不到文件夹:{0}",
|
| 264 |
+
"フォルダのパスを入力してください": "请输入文件夹路径",
|
| 265 |
+
"フォルダを開く": "打开文件夹",
|
| 266 |
+
"プロンプト": "提示",
|
| 267 |
+
"ポート": "端口",
|
| 268 |
+
"ポート {0} は別のプログラムが使っています(設定でポートを変えてください)": "端口 {0} 已被其他程序占用(请在设置中更换端口)",
|
| 269 |
+
"ポートかコンテキスト長の値が不正です": "端口或上下文长度无效",
|
| 270 |
+
"ポートが使用中です(別のサーバーが動いていませんか?)": "端口已被占用(是否有其他服务器在运行?)",
|
| 271 |
+
"メッセージを入力してください。": "请输入消息。",
|
| 272 |
+
"メッセージを入力するか、画像を添付・貼り付け・ドロップしてください。": "输入消息,或添加、粘贴、拖放图片。",
|
| 273 |
+
"メッセージ(Enterで送信、Shift+Enterで改行)": "消息(Enter 发送,Shift+Enter 换行)",
|
| 274 |
+
"メモリ 約{0} GB": "内存约 {0} GB",
|
| 275 |
+
"メモリ目安": "内存估计",
|
| 276 |
+
"モデル": "模型",
|
| 277 |
+
"モデルの一覧は、FastFlowLM(約 40 MB)を入れると出ます": "安装 FastFlowLM(约 40 MB)后会列出模型",
|
| 278 |
+
"モデルは読み込まれていません": "未加载模型",
|
| 279 |
+
"モデルをロード": "加载模型",
|
| 280 |
+
"モデルを削除": "���除模型",
|
| 281 |
+
"モデル名": "模型名称",
|
| 282 |
+
"モデル未選択": "未选择模型",
|
| 283 |
+
"ログ": "日志",
|
| 284 |
+
"ログイン時にトレイを起動する": "登录时启动托盘",
|
| 285 |
+
"ロード": "加载",
|
| 286 |
+
"ロードしています…": "正在加载…",
|
| 287 |
+
"ロードできません: {0}": "无法加载:{0}",
|
| 288 |
+
"ロードに失敗": "加载失败",
|
| 289 |
+
"ロード中": "加载中",
|
| 290 |
+
"ロード中…": "加载中…",
|
| 291 |
+
"ロード失敗": "加载失败",
|
| 292 |
+
"ロード済み": "已加载",
|
| 293 |
+
"・メモリ 約{0} GB はこの PC では不足の可能性": "・约 {0} GB,本机内存可能不足",
|
| 294 |
+
"一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。モデルはすべて AMD NPU(XDNA2)の上だけで動きます(NPU 専用エンジン FastFlowLM)。": "一次一个模型。选择另一个模型并点击“切换”,会先卸载当前模型再加载。所有模型都只在 AMD NPU(XDNA2)上运行(NPU 专用引擎 FastFlowLM)。",
|
| 295 |
+
"今すぐ確認": "立即检查",
|
| 296 |
+
"今は v{0}。「更新する」で入れ替えて再起動します": "当前为 v{0}。点击“更新”即可替换并重启",
|
| 297 |
+
"他のアプリからは <code id=\"base\"></code> を OpenAI の base URL に、モデル名は <code id=\"mid\"></code> を指定してください(APIキー設定時は <code>Authorization: Bearer キー</code>)。": "在其他应用中,把 <code id=\"base\"></code> 设为 OpenAI 的 base URL,模型名称填写 <code id=\"mid\"></code>(设置了 API 密钥时:<code>Authorization: Bearer 密钥</code>)。",
|
| 298 |
+
"会話をクリア": "清空对话",
|
| 299 |
+
"使うモデル": "使用的模型",
|
| 300 |
+
"使用中": "使用中",
|
| 301 |
+
"保存": "保存",
|
| 302 |
+
"保存しました": "已保存",
|
| 303 |
+
"保存先": "保存位置",
|
| 304 |
+
"保存先 {0} が使えないため、既定のフォルダを使っています(「変更…」で選び直せます)": "保存位置 {0} 无法使用,正在使用默认文件夹(可通过“更改…”重新选择)",
|
| 305 |
+
"保存先を {0} にしますか?\n今の保存先のモデルはそのまま残ります(新しい保存先には出ません)。": "将保存位置改为 {0}?\n当前保存位置中的模型会保留在原处(不会在新位置中显示)。",
|
| 306 |
+
"俺のNPUがこんなに動くわけない": "我的NPU哪有这么能跑",
|
| 307 |
+
"停止": "停止",
|
| 308 |
+
"停止中": "已停止",
|
| 309 |
+
"入れる": "安装",
|
| 310 |
+
"入れ替え中": "正在替换文件",
|
| 311 |
+
"切り替え": "切换",
|
| 312 |
+
"別のダウンロードが進行中です": "另一个下载正在进行",
|
| 313 |
+
"削除": "删除",
|
| 314 |
+
"動作中": "运行中",
|
| 315 |
+
"取得済み": "已下载",
|
| 316 |
+
"可": "支持",
|
| 317 |
+
"回答": "回答",
|
| 318 |
+
"場所": "位置",
|
| 319 |
+
"変更…": "更改…",
|
| 320 |
+
"変更点": "更新内容",
|
| 321 |
+
"失敗": "失败",
|
| 322 |
+
"完了": "完成",
|
| 323 |
+
"対応": "支持",
|
| 324 |
+
"応答開始": "首个令牌",
|
| 325 |
+
"応答開始 {0}秒 · {1}トークン · {2} tok/s · 文脈 {3}{4}": "首个 token {0} 秒 · {1} token · {2} tok/s · 上下文 {3}{4}",
|
| 326 |
+
"思考": "思考",
|
| 327 |
+
"思考モード": "思考模式",
|
| 328 |
+
"接続なし": "未连接",
|
| 329 |
+
"接続中…": "连接中…",
|
| 330 |
+
"文脈は約1000トークン": "上下文约 1000 token",
|
| 331 |
+
"文脈は約{0}トークン": "上下文约 {0} token",
|
| 332 |
+
"新しいバージョン v{0} があります": "有新版本 v{0}",
|
| 333 |
+
"新しいバージョンがあります": "有新版本",
|
| 334 |
+
"新しい会話": "新对话",
|
| 335 |
+
"新しい会話です。": "新对话。",
|
| 336 |
+
"新しい版はありません": "没有新版本",
|
| 337 |
+
"日本の四季について、それぞれ一文ずつ説明してください。": "请用一句话分别介绍日本的四季。",
|
| 338 |
+
"日本の首都はどこですか?一文で。": "日本的首都是哪里?用一句话回答。",
|
| 339 |
+
"日本語": "日本語",
|
| 340 |
+
"更新": "更新",
|
| 341 |
+
"更新あり": "有更新",
|
| 342 |
+
"更新あり v{0}": "有更新 v{0}",
|
| 343 |
+
"更新しました": "已更新",
|
| 344 |
+
"更新する": "更新",
|
| 345 |
+
"更新できませんでした": "更新失败",
|
| 346 |
+
"更新できませんでした: {0}": "更新失败:{0}",
|
| 347 |
+
"更新を確認できませんでした: {0}": "无法检查更新:{0}",
|
| 348 |
+
"更新を確認できませんでした(オフライン?)": "无法检查更新(离线?)",
|
| 349 |
+
"最大トークン": "最大 token 数",
|
| 350 |
+
"最新版です": "已是最新版本",
|
| 351 |
+
"最終確認 {0}": "上次检查 {0}",
|
| 352 |
+
"未インストール": "未安装",
|
| 353 |
+
"未取得": "未下载",
|
| 354 |
+
"未設定なら何を入れても通ります": "未设置时任何密钥都可通过",
|
| 355 |
+
"東京は日本の首都であり、政治・経済・文化の中心地である。江戸時代には徳川幕府が置かれ、1868年の明治維新で東京と改称された。現在は約1400万人が暮らす世界有数の大都市で、多くの企業や大学が集まっている。": "东京是日本的首都,也是政治、经济和文化的中心。江户时代德川幕府设在这里,1868年明治维新时改称东京。如今约有1400万人居住于此,是世界屈指可数的大都市,聚集了众多企业和大学。",
|
| 356 |
+
"検証を実行": "运行检测",
|
| 357 |
+
"検証ページ": "检测页面",
|
| 358 |
+
"検証ページを開く": "打开检测页面",
|
| 359 |
+
"次の文章を、元の表現をなるべく使って2文に要約してください。": "请尽量使用原文的表达,把下面的文字概括成两句话。",
|
| 360 |
+
"止まった理由: {0}": "停止原因:{0}",
|
| 361 |
+
"温度": "温度",
|
| 362 |
+
"準備中…": "准备中…",
|
| 363 |
+
"状態": "状态",
|
| 364 |
+
"生成速度": "生成速度",
|
| 365 |
+
"画像": "图像",
|
| 366 |
+
"画像も読めます": "也能读图",
|
| 367 |
+
"画像を添付": "添加图片",
|
| 368 |
+
"画像入力": "图像输入",
|
| 369 |
+
"確認中…": "检查中…",
|
| 370 |
+
"简体中文": "简体中文",
|
| 371 |
+
"約{0} GB": "约 {0} GB",
|
| 372 |
+
"終了(サーバーも停止)": "退出(同时停止服务器)",
|
| 373 |
+
"結果": "结果",
|
| 374 |
+
"繰り返し抑制": "重复惩罚",
|
| 375 |
+
"考えてから答えます": "先思考再回答",
|
| 376 |
+
"要約": "摘要",
|
| 377 |
+
"言語": "语言",
|
| 378 |
+
"設定": "设置",
|
| 379 |
+
"設定は保存しました。サーバーを新しい設定で今すぐ再起動しますか?(キャンセルしても、次にモデルを読み込むときから反映されます)": "设置已保存。现在用新设置重启服务器?(取消后,下次加载模型时生效)",
|
| 380 |
+
"読み込み中…": "加载中…",
|
| 381 |
+
"起動時と 1 日ごとに更新を確認する": "启动时及每天检查更新",
|
| 382 |
+
"起動時に前回ロードしたモデルを自動でロードする": "启动时自动加载上次的模型",
|
| 383 |
+
"送信": "发送",
|
| 384 |
+
"項目": "项目",
|
| 385 |
+
"(ロード済み)": "(已加载)",
|
| 386 |
+
"(停止しました)": "(已停止)",
|
| 387 |
+
"(再利用 {0})": "(复用 {0})",
|
| 388 |
+
"(画像)": "(图片)"
|
| 389 |
+
}
|
| 390 |
+
}
|
onw/i18n.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""UI language. The UI is written in Japanese; i18n.json maps those strings to English and Simplified Chinese.
|
| 2 |
+
|
| 3 |
+
T("ロードできません: {0}", e) the string in the current language (config "lang": auto / ja / en / zh)
|
| 4 |
+
page(path) an HTML page with the table for its language (web/i18n.js does the swapping)
|
| 5 |
+
"""
|
| 6 |
+
import json, os, time
|
| 7 |
+
|
| 8 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
LANGS = {"ja": "日本語", "en": "English", "zh": "简体中文"}
|
| 10 |
+
_table = None
|
| 11 |
+
_cur = (0.0, "ja")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def table():
|
| 15 |
+
global _table
|
| 16 |
+
if _table is None:
|
| 17 |
+
with open(os.path.join(HERE, "i18n.json"), encoding="utf8") as f:
|
| 18 |
+
_table = json.load(f)
|
| 19 |
+
return _table
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def system():
|
| 23 |
+
"""The OS display language: ja / zh / en (everything else)."""
|
| 24 |
+
try:
|
| 25 |
+
if os.name == "nt":
|
| 26 |
+
import ctypes
|
| 27 |
+
return {0x11: "ja", 0x04: "zh"}.get(ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF, "en")
|
| 28 |
+
v = next((os.environ[k] for k in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG") if os.environ.get(k)), "")
|
| 29 |
+
return "ja" if v.startswith("ja") else "zh" if v.startswith("zh") else "en"
|
| 30 |
+
except Exception:
|
| 31 |
+
return "en"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def current(cfg=None):
|
| 35 |
+
global _cur
|
| 36 |
+
if cfg is None:
|
| 37 |
+
if time.time() - _cur[0] < 2: # T() is called many times per page refresh
|
| 38 |
+
return _cur[1]
|
| 39 |
+
from . import app
|
| 40 |
+
cfg = app.load_config()
|
| 41 |
+
v = cfg.get("lang", "auto")
|
| 42 |
+
lang = v if v in LANGS else system()
|
| 43 |
+
_cur = (time.time(), lang)
|
| 44 |
+
return lang
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def strings(lang):
|
| 48 |
+
"""Japanese -> lang (Chinese falls back to English where it has no entry)."""
|
| 49 |
+
if lang == "ja":
|
| 50 |
+
return {}
|
| 51 |
+
t = table()
|
| 52 |
+
return {**t.get("en", {}), **t.get(lang, {})}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def T(s, *a, lang=None):
|
| 56 |
+
lang = lang or current()
|
| 57 |
+
r = s if lang == "ja" else strings(lang).get(s, s)
|
| 58 |
+
return r.format(*a) if a else r
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def page(path, lang=None):
|
| 62 |
+
"""The page's HTML with its language table and web/i18n.js in place of the <script>/*i18n*/</script> marker."""
|
| 63 |
+
if lang is None:
|
| 64 |
+
from . import app
|
| 65 |
+
lang = current(app.load_config()) # not the cached value: the page may follow a language change
|
| 66 |
+
html = open(path, encoding="utf8").read()
|
| 67 |
+
js = open(os.path.join(HERE, "web", "i18n.js"), encoding="utf8").read()
|
| 68 |
+
data = json.dumps(strings(lang), ensure_ascii=False).replace("</", "<\\/")
|
| 69 |
+
html = html.replace('<html lang="ja">', f'<html lang="{lang}">', 1)
|
| 70 |
+
zh = ('<style>html:lang(zh) body { font-family: system-ui, "Segoe UI", "Microsoft YaHei UI", "PingFang SC", '
|
| 71 |
+
'"Noto Sans CJK SC", "Noto Sans SC", sans-serif; }</style>\n')
|
| 72 |
+
html = html.replace("<script>/*i18n*/</script>", f"{zh}<script>const LANG = {json.dumps(lang)}, I18N = {data};\n{js}</script>", 1)
|
| 73 |
+
return html.encode("utf8")
|
onw/lemonade.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The AMD NPU side of onw, ported from Lemonade Server (github.com/lemonade-sdk/lemonade, Apache-2.0).
|
| 2 |
+
|
| 3 |
+
Lemonade runs LLMs on the Ryzen AI NPU (XDNA2) by starting an NPU engine as a separate program that serves an
|
| 4 |
+
OpenAI-compatible API on localhost. onw does the same with the one engine that is NPU-only, FastFlowLM
|
| 5 |
+
(github.com/ROCm/FastFlowLM): `flm serve`, models pulled by flm itself (`flm list --json` / `flm pull`). Windows and
|
| 6 |
+
Linux. (lemonade: src/cpp/server/backends/fastflowlm/fastflowlm_server.cpp, fastflowlm_models.cpp)
|
| 7 |
+
|
| 8 |
+
FastFlowLM is downloaded on first use from its GitHub release into <config>/bin/flm/npu, pinned to the version in
|
| 9 |
+
Lemonade's src/cpp/resources/backend_versions.json.
|
| 10 |
+
|
| 11 |
+
npu() the NPU: {"arch": "XDNA2" | None, "name", "driver"} (lemonade: system_info.cpp)
|
| 12 |
+
installed_version() FastFlowLM's installed version, or None; install(progress) downloads it
|
| 13 |
+
binary() path of flm(.exe) under the install folder
|
| 14 |
+
flm_validate() (ok, message): driver / firmware check by `flm validate --json`
|
| 15 |
+
flm_models(), flm_pull_command(), flm_remove()
|
| 16 |
+
serve_command(...) the command line that serves one model on a port, and the URL that answers once it is ready
|
| 17 |
+
"""
|
| 18 |
+
import json, os, shutil, subprocess, sys, tarfile, time, urllib.request, zipfile
|
| 19 |
+
|
| 20 |
+
VERSION = "v1.0.6" # lemonade backend_versions.json: "flm": {"npu": "v1.0.6"}
|
| 21 |
+
ENGINE = "FastFlowLM"
|
| 22 |
+
WINDOWS = os.name == "nt"
|
| 23 |
+
NO_WINDOW = {"creationflags": subprocess.CREATE_NO_WINDOW} if WINDOWS else {}
|
| 24 |
+
DRIVER_URL = "https://lemonade-server.ai/driver_install.html"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ------------------------------------------------------------------ the NPU (lemonade: system_info.cpp)
|
| 28 |
+
|
| 29 |
+
_npu = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def npu(refresh=False):
|
| 33 |
+
"""{"arch": "XDNA2" or None, "name": CPU name, "driver": NPU driver version or ""}. Only XDNA2 (Strix Point,
|
| 34 |
+
Krackan Point, Strix Halo, Gorgon Point, ...) runs FastFlowLM; XDNA1 (Phoenix, Hawk Point) does not."""
|
| 35 |
+
global _npu
|
| 36 |
+
if _npu is None or refresh:
|
| 37 |
+
try:
|
| 38 |
+
_npu = _npu_windows() if WINDOWS else _npu_linux()
|
| 39 |
+
except Exception as e:
|
| 40 |
+
_npu = {"arch": None, "name": "", "driver": "", "error": str(e)}
|
| 41 |
+
return _npu
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _ps(cmd):
|
| 45 |
+
r = subprocess.run(["powershell", "-NoProfile", "-Command", cmd], capture_output=True, text=True,
|
| 46 |
+
encoding="utf8", errors="replace", timeout=60, **NO_WINDOW)
|
| 47 |
+
return r.stdout.strip()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _npu_windows():
|
| 51 |
+
# the XDNA2 NPU is PCI\VEN_1022&DEV_17F0 ("NPU Compute Accelerator Device")
|
| 52 |
+
out = _ps("$d = Get-CimInstance Win32_PnPEntity -Filter \"PNPDeviceID LIKE '%VEN_1022&DEV_17F0%'\" | Select-Object -First 1;"
|
| 53 |
+
"$v = (Get-CimInstance Win32_PnPSignedDriver -Filter \"DeviceName = 'NPU Compute Accelerator Device'\" | Select-Object -First 1).DriverVersion;"
|
| 54 |
+
"$c = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name;"
|
| 55 |
+
"[pscustomobject]@{found = [bool]$d; driver = [string]$v; cpu = [string]$c} | ConvertTo-Json -Compress")
|
| 56 |
+
d = json.loads(out or "{}")
|
| 57 |
+
return {"arch": "XDNA2" if d.get("found") and d.get("driver") else None, "name": (d.get("cpu") or "").strip(),
|
| 58 |
+
"driver": d.get("driver") or ""}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _npu_linux():
|
| 62 |
+
arch, name = None, ""
|
| 63 |
+
base = "/sys/bus/pci/devices"
|
| 64 |
+
for dev in os.listdir(base):
|
| 65 |
+
rd = lambda f: open(os.path.join(base, dev, f)).read().strip()
|
| 66 |
+
try:
|
| 67 |
+
if rd("vendor") == "0x1022" and rd("device") == "0x17f0" and rd("revision") in ("0x10", "0x11", "0x20"):
|
| 68 |
+
drv = os.path.basename(os.path.realpath(os.path.join(base, dev, "driver")))
|
| 69 |
+
arch = "XDNA2" if drv == "amdxdna" else None
|
| 70 |
+
except OSError:
|
| 71 |
+
continue
|
| 72 |
+
try:
|
| 73 |
+
name = next(l.split(":", 1)[1].strip() for l in open("/proc/cpuinfo") if l.startswith("model name"))
|
| 74 |
+
except (OSError, StopIteration):
|
| 75 |
+
pass
|
| 76 |
+
ver = ""
|
| 77 |
+
try:
|
| 78 |
+
ver = open("/sys/module/amdxdna/version").read().strip()
|
| 79 |
+
except OSError:
|
| 80 |
+
pass
|
| 81 |
+
return {"arch": arch, "name": name, "driver": ver}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def npu_text():
|
| 85 |
+
n = npu()
|
| 86 |
+
if not n.get("arch"):
|
| 87 |
+
return "NPU: XDNA2 not found"
|
| 88 |
+
return f"NPU: {n['arch']}" + (f" (driver {n['driver']})" if n.get("driver") else "")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ------------------------------------------------------------------ the engine (lemonade: backend_utils.cpp)
|
| 92 |
+
|
| 93 |
+
def install_dir():
|
| 94 |
+
from .app import config_dir
|
| 95 |
+
return os.path.join(config_dir(), "bin", "flm", "npu")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def installed_version():
|
| 99 |
+
try:
|
| 100 |
+
v = open(os.path.join(install_dir(), "version.txt"), encoding="utf8").read().strip()
|
| 101 |
+
except OSError:
|
| 102 |
+
return None
|
| 103 |
+
return v if binary() else None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def up_to_date():
|
| 107 |
+
return installed_version() == VERSION
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def binary():
|
| 111 |
+
"""flm(.exe) inside the install folder, or None."""
|
| 112 |
+
exe = "flm.exe" if WINDOWS else "flm"
|
| 113 |
+
for root, _, files in os.walk(install_dir()):
|
| 114 |
+
if exe in files:
|
| 115 |
+
return os.path.join(root, exe)
|
| 116 |
+
return None
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def release_asset(version=VERSION):
|
| 120 |
+
"""(url, file name) of FastFlowLM's release download (lemonade: FastFlowLMServer::get_install_params)."""
|
| 121 |
+
bare = version[1:] if version.startswith("v") else version
|
| 122 |
+
name = f"fastflowlm_{bare}_windows_amd64.zip" if WINDOWS else f"fastflowlm_{bare}_linux.tar.gz"
|
| 123 |
+
return f"https://github.com/ROCm/FastFlowLM/releases/download/{version}/{name}", name
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def install(progress=lambda frac, text: None, should_stop=lambda: False):
|
| 127 |
+
"""Download and unpack the pinned FastFlowLM (into a staging folder first: a broken download leaves the
|
| 128 |
+
installed one as it is)."""
|
| 129 |
+
url, name = release_asset()
|
| 130 |
+
root = os.path.dirname(install_dir())
|
| 131 |
+
os.makedirs(root, exist_ok=True)
|
| 132 |
+
arc, stage = os.path.join(root, name), os.path.join(root, "npu.new")
|
| 133 |
+
req = urllib.request.Request(url, headers={"User-Agent": "onw-amd"})
|
| 134 |
+
with urllib.request.urlopen(req, timeout=60) as r, open(arc + ".part", "wb") as f:
|
| 135 |
+
total, n = int(r.headers.get("Content-Length") or 0), 0
|
| 136 |
+
while True:
|
| 137 |
+
if should_stop():
|
| 138 |
+
raise RuntimeError("cancelled")
|
| 139 |
+
b = r.read(1 << 20)
|
| 140 |
+
if not b:
|
| 141 |
+
break
|
| 142 |
+
f.write(b)
|
| 143 |
+
n += len(b)
|
| 144 |
+
progress(n / total if total else 0.0, f"FastFlowLM {n / 2**20:.0f} / {total / 2**20:.0f} MB")
|
| 145 |
+
os.replace(arc + ".part", arc)
|
| 146 |
+
progress(1.0, "FastFlowLM: unpacking")
|
| 147 |
+
shutil.rmtree(stage, ignore_errors=True)
|
| 148 |
+
if name.endswith(".zip"):
|
| 149 |
+
with zipfile.ZipFile(arc) as z:
|
| 150 |
+
z.extractall(stage)
|
| 151 |
+
else:
|
| 152 |
+
with tarfile.open(arc) as t:
|
| 153 |
+
t.extractall(stage, filter="data") if sys.version_info >= (3, 12) else t.extractall(stage)
|
| 154 |
+
with open(os.path.join(stage, "version.txt"), "w", encoding="utf8") as f:
|
| 155 |
+
f.write(VERSION + "\n")
|
| 156 |
+
shutil.rmtree(install_dir(), ignore_errors=True)
|
| 157 |
+
os.replace(stage, install_dir())
|
| 158 |
+
os.remove(arc)
|
| 159 |
+
if not WINDOWS and binary():
|
| 160 |
+
os.chmod(binary(), 0o755)
|
| 161 |
+
if not binary():
|
| 162 |
+
raise RuntimeError(f"{name} did not contain the flm program")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ------------------------------------------------------------------ models (lemonade: fastflowlm_models.cpp)
|
| 166 |
+
|
| 167 |
+
def flm_dir(cfg=None):
|
| 168 |
+
"""FLM_MODEL_PATH: where flm keeps its models (the save folder; flm puts them in its "models" subfolder)."""
|
| 169 |
+
from . import app
|
| 170 |
+
return app.models_dir(cfg or app.load_config())
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def flm_env(cfg=None):
|
| 174 |
+
return {**os.environ, "FLM_MODEL_PATH": flm_dir(cfg)}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _flm(args, cfg=None, timeout=120):
|
| 178 |
+
exe = binary()
|
| 179 |
+
if not exe:
|
| 180 |
+
raise RuntimeError("FastFlowLM is not installed")
|
| 181 |
+
return subprocess.run([exe, *args], capture_output=True, text=True, encoding="utf8", errors="replace",
|
| 182 |
+
timeout=timeout, env=flm_env(cfg), **NO_WINDOW)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _json_in(text):
|
| 186 |
+
"""The JSON object in flm's output (it may print a banner around it)."""
|
| 187 |
+
s, e = text.find("{"), text.rfind("}")
|
| 188 |
+
return json.loads(text[s:e + 1]) if s >= 0 and e > s else {}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def flm_validate(cfg=None):
|
| 192 |
+
"""(ok, message) from `flm validate --json` (lemonade: run_flm_validate)."""
|
| 193 |
+
try:
|
| 194 |
+
r = _flm(["validate", "--json"], cfg, timeout=60)
|
| 195 |
+
j = _json_in(r.stdout)
|
| 196 |
+
except Exception as e:
|
| 197 |
+
return False, str(e)
|
| 198 |
+
if j.get("ready"):
|
| 199 |
+
return True, ""
|
| 200 |
+
errs = [msg for key, msg in (("amd_device_found", "No AMD NPU device found."),
|
| 201 |
+
("all_fw_ok", "NPU firmware is incompatible."),
|
| 202 |
+
("kernel_ok", "Kernel version is incompatible."),
|
| 203 |
+
("memlock_ok", "Memlock limits are too low."),
|
| 204 |
+
("npu_driver_ok", "NPU driver version is too old."))
|
| 205 |
+
if key in j and not j[key]]
|
| 206 |
+
if not j and r.returncode == 0:
|
| 207 |
+
return True, ""
|
| 208 |
+
return False, (" ".join(errs) or "NPU validation failed.") + f" ({DRIVER_URL})"
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flm_name(checkpoint):
|
| 212 |
+
"""lemonade's model name for an flm checkpoint: "llama3.2:1b" -> "llama3.2-1b-FLM"."""
|
| 213 |
+
return checkpoint.replace(":", "-") + "-FLM"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def flm_models(cfg=None):
|
| 217 |
+
"""{name: {"checkpoint", "size", "labels", "installed"}} of flm's chat models (`flm list --json`). Embedding and
|
| 218 |
+
speech-to-text models are left out: onw is a chat server."""
|
| 219 |
+
r = _flm(["list", "--json"], cfg)
|
| 220 |
+
out = {}
|
| 221 |
+
for m in _json_in(r.stdout).get("models", []):
|
| 222 |
+
ck = m.get("name")
|
| 223 |
+
if not isinstance(ck, str) or "whisper" in ck.lower() or "embed" in ck.lower():
|
| 224 |
+
continue
|
| 225 |
+
out[flm_name(ck)] = {"checkpoint": ck, "size": m.get("footprint") or 0.0,
|
| 226 |
+
"labels": [l for l in m.get("label") or [] if isinstance(l, str)],
|
| 227 |
+
"installed": bool(m.get("installed"))}
|
| 228 |
+
return out
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def flm_pull_command(checkpoint, force=False):
|
| 232 |
+
exe = binary()
|
| 233 |
+
if not exe:
|
| 234 |
+
raise RuntimeError("FastFlowLM is not installed")
|
| 235 |
+
return [exe, "pull", checkpoint] + (["--force"] if force else [])
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def flm_remove(checkpoint, cfg=None):
|
| 239 |
+
r = _flm(["remove", checkpoint], cfg)
|
| 240 |
+
if r.returncode != 0:
|
| 241 |
+
raise RuntimeError((r.stdout + r.stderr).strip()[-300:] or f"flm remove failed ({r.returncode})")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
# ------------------------------------------------------------------ serving (lemonade: fastflowlm_server.cpp load())
|
| 245 |
+
|
| 246 |
+
def serve_command(checkpoint, port, ctx, cfg=None):
|
| 247 |
+
"""(argv, readiness URL path, extra env) that serve one model on a port. flm has no /health: lemonade waits for
|
| 248 |
+
/api/tags."""
|
| 249 |
+
exe = binary()
|
| 250 |
+
if not exe:
|
| 251 |
+
raise RuntimeError("FastFlowLM is not installed")
|
| 252 |
+
return ([exe, "serve", checkpoint, "--ctx-len", str(ctx), "--port", str(port), "--host", "127.0.0.1", "--quiet"],
|
| 253 |
+
"/api/tags", {"FLM_MODEL_PATH": flm_dir(cfg)})
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
_JOB = []
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def tie_to_this_process(proc):
|
| 260 |
+
"""Windows: put the engine into a job object that ends it when this process ends in any way (a crash, a kill from
|
| 261 |
+
the task manager), so no engine is left holding the NPU. Elsewhere the engine is in our session and the tray
|
| 262 |
+
stops the whole process tree."""
|
| 263 |
+
if not WINDOWS:
|
| 264 |
+
return
|
| 265 |
+
import ctypes
|
| 266 |
+
from ctypes import wintypes
|
| 267 |
+
k = ctypes.WinDLL("kernel32", use_last_error=True)
|
| 268 |
+
k.CreateJobObjectW.restype = wintypes.HANDLE
|
| 269 |
+
k.OpenProcess.restype = wintypes.HANDLE
|
| 270 |
+
|
| 271 |
+
class Basic(ctypes.Structure):
|
| 272 |
+
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
|
| 273 |
+
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
|
| 274 |
+
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
|
| 275 |
+
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), ("SchedulingClass", wintypes.DWORD)]
|
| 276 |
+
|
| 277 |
+
class Extended(ctypes.Structure):
|
| 278 |
+
_fields_ = [("BasicLimitInformation", Basic), ("IoInfo", ctypes.c_uint64 * 6),
|
| 279 |
+
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
| 280 |
+
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
| 281 |
+
if not _JOB:
|
| 282 |
+
job = k.CreateJobObjectW(None, None)
|
| 283 |
+
info = Extended()
|
| 284 |
+
info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
| 285 |
+
k.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) # ExtendedLimitInformation
|
| 286 |
+
_JOB.append(job) # the handle closes (and the job ends) with us
|
| 287 |
+
h = k.OpenProcess(0x0001 | 0x0100, False, proc.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA
|
| 288 |
+
if h:
|
| 289 |
+
k.AssignProcessToJobObject(_JOB[0], h)
|
| 290 |
+
k.CloseHandle(h)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def free_port(start=8001, avoid=()):
|
| 294 |
+
"""The first free localhost port from `start` (lemonade: WrappedServer::choose_port)."""
|
| 295 |
+
import socket
|
| 296 |
+
for p in range(start, start + 1000):
|
| 297 |
+
if p in avoid:
|
| 298 |
+
continue
|
| 299 |
+
s = socket.socket()
|
| 300 |
+
try:
|
| 301 |
+
s.bind(("127.0.0.1", p))
|
| 302 |
+
return p
|
| 303 |
+
except OSError:
|
| 304 |
+
continue
|
| 305 |
+
finally:
|
| 306 |
+
s.close()
|
| 307 |
+
raise RuntimeError("no free port for the NPU engine")
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def wait_ready(proc, url, timeout=900, poll=1.0):
|
| 311 |
+
"""Wait until `url` answers (the engine has loaded the model); False when the process ended first."""
|
| 312 |
+
t0 = time.time()
|
| 313 |
+
while time.time() - t0 < timeout:
|
| 314 |
+
if proc.poll() is not None:
|
| 315 |
+
return False
|
| 316 |
+
try:
|
| 317 |
+
urllib.request.urlopen(url, timeout=2)
|
| 318 |
+
return True
|
| 319 |
+
except OSError:
|
| 320 |
+
time.sleep(poll)
|
| 321 |
+
return False
|
onw/logo.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The onw logo: a chip with a bold "o" dashing to the right (its left pins are speed lines).
|
| 2 |
+
|
| 3 |
+
One set of shapes, drawn with Pillow (tray icon, .ico / .png) or written out as SVG (pages, README).
|
| 4 |
+
The full design is for 48 px and up; `simple` (3 thick pins per side) stays readable at 16-32 px.
|
| 5 |
+
python -m onw.logo regenerate onw/web/icon.ico, icon.png, icon.svg
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
BLUE, GRAY, WHITE = (24, 104, 240), (128, 132, 142), (255, 255, 255)
|
| 10 |
+
BADGE = {"running": (46, 160, 67), "loading": (219, 150, 20), "failed": (200, 50, 50)}
|
| 11 |
+
BOX = (70, 90, 846) # viewBox x, y, size of the design space (traced from the 1024 px original)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def shapes(simple=False):
|
| 15 |
+
"""(kind, coords, width) in design units: 'rect' = rounded chip body, 'line' = round-capped bar, 'o' = the letter."""
|
| 16 |
+
s = [("rect", (332, 256, 844, 767, 80), 0)]
|
| 17 |
+
if simple:
|
| 18 |
+
w, pins = 64, (436, 588, 740)
|
| 19 |
+
rows = (512 - 152, 512, 512 + 152)
|
| 20 |
+
speed = [(150, 360), (95, 512), (190, 664)]
|
| 21 |
+
o = (150, 150, 66, 70)
|
| 22 |
+
else:
|
| 23 |
+
w, pins = 38, (436, 512, 588, 664, 740)
|
| 24 |
+
rows = (360, 436, 512, 588, 664)
|
| 25 |
+
speed = [(268, 360), (124, 436), (209, 512), (95, 588), (275, 664)]
|
| 26 |
+
s += [("line", (181, 360, 208, 360), w), ("line", (181, 664, 212, 664), w)] # short dashes ahead
|
| 27 |
+
o = (120, 117, 57, 67)
|
| 28 |
+
for x in pins:
|
| 29 |
+
s += [("line", (x, 212, x, 300), w), ("line", (x, 815, x, 720), w)]
|
| 30 |
+
for y in rows:
|
| 31 |
+
s.append(("line", (891, y, 800, y), w))
|
| 32 |
+
for x, y in speed:
|
| 33 |
+
s.append(("line", (x, y, 380, y), w))
|
| 34 |
+
s.append(("o", (588, 512) + o, 0))
|
| 35 |
+
return s
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def draw(size, simple=None, state=None):
|
| 39 |
+
"""RGBA image of the logo; state (running / loading / failed / anything else = stopped) adds the tray badge."""
|
| 40 |
+
from PIL import Image, ImageDraw
|
| 41 |
+
if simple is None:
|
| 42 |
+
simple = size <= 32
|
| 43 |
+
ss = max(4, 2048 // size) # supersample, then scale down
|
| 44 |
+
n = size * ss
|
| 45 |
+
k, (ox, oy, _) = n / BOX[2], BOX
|
| 46 |
+
P = lambda x, y: ((x - ox) * k, (y - oy) * k)
|
| 47 |
+
color = BLUE if state in (None, "running", "loading", "failed") else GRAY
|
| 48 |
+
im = Image.new("RGBA", (n, n), (0, 0, 0, 0))
|
| 49 |
+
d = ImageDraw.Draw(im)
|
| 50 |
+
for kind, c, w in shapes(simple):
|
| 51 |
+
if kind == "rect":
|
| 52 |
+
d.rounded_rectangle(P(*c[:2]) + P(*c[2:4]), c[4] * k, fill=color)
|
| 53 |
+
elif kind == "line":
|
| 54 |
+
a, b, r = P(*c[:2]), P(*c[2:]), w * k / 2
|
| 55 |
+
d.line(a + b, fill=color, width=round(w * k))
|
| 56 |
+
for x, y in (a, b):
|
| 57 |
+
d.ellipse((x - r, y - r, x + r, y + r), fill=color)
|
| 58 |
+
else:
|
| 59 |
+
(cx, cy), (rx, ry, hx, hy) = P(*c[:2]), (v * k for v in c[2:])
|
| 60 |
+
d.ellipse((cx - rx, cy - ry, cx + rx, cy + ry), fill=WHITE)
|
| 61 |
+
d.ellipse((cx - hx, cy - hy, cx + hx, cy + hy), fill=color)
|
| 62 |
+
if state in BADGE: # status dot, cut out of the chip's corner
|
| 63 |
+
(cx, cy), r = P(800, 800), 118 * k
|
| 64 |
+
g = r + 44 * k
|
| 65 |
+
d.ellipse((cx - g, cy - g, cx + g, cy + g), fill=(0, 0, 0, 0))
|
| 66 |
+
d.ellipse((cx - r, cy - r, cx + r, cy + r), fill=BADGE[state])
|
| 67 |
+
return im.resize((size, size), Image.LANCZOS)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def svg(simple=False):
|
| 71 |
+
ox, oy, n = BOX
|
| 72 |
+
h = "#%02x%02x%02x" % BLUE
|
| 73 |
+
L = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{ox} {oy} {n} {n}">']
|
| 74 |
+
for kind, c, w in shapes(simple):
|
| 75 |
+
if kind == "rect":
|
| 76 |
+
x0, y0, x1, y1, r = c
|
| 77 |
+
L.append(f'<rect x="{x0}" y="{y0}" width="{x1 - x0}" height="{y1 - y0}" rx="{r}" fill="{h}"/>')
|
| 78 |
+
elif kind == "line":
|
| 79 |
+
L.append(f'<line x1="{c[0]}" y1="{c[1]}" x2="{c[2]}" y2="{c[3]}" stroke="{h}" stroke-width="{w}" stroke-linecap="round"/>')
|
| 80 |
+
else:
|
| 81 |
+
cx, cy, rx, ry, hx, hy = c
|
| 82 |
+
L.append(f'<ellipse cx="{cx}" cy="{cy}" rx="{rx}" ry="{ry}" fill="#fff"/>'
|
| 83 |
+
f'<ellipse cx="{cx}" cy="{cy}" rx="{hx}" ry="{hy}" fill="{h}"/>')
|
| 84 |
+
return "".join(L) + "</svg>"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
web = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web")
|
| 89 |
+
sizes = [16, 20, 24, 32, 40, 48, 64, 128, 256]
|
| 90 |
+
big = draw(256)
|
| 91 |
+
big.save(os.path.join(web, "icon.ico"), sizes=[(s, s) for s in sizes], append_images=[draw(s) for s in sizes[:-1]])
|
| 92 |
+
big.save(os.path.join(web, "icon.png"))
|
| 93 |
+
with open(os.path.join(web, "icon.svg"), "w", encoding="utf8", newline="\n") as f:
|
| 94 |
+
f.write(svg() + "\n")
|
| 95 |
+
print("icon.ico, icon.png, icon.svg ->", web)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
onw/manager.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The onw manager: FastFlowLM, model list, downloads, server control and settings behind a small local HTTP API, used by the
|
| 2 |
+
window (onw/web/manage.html in a webview or a browser). It runs inside the tray process, so downloads keep going when
|
| 3 |
+
the window is closed; `onw window` without a tray runs its own copy.
|
| 4 |
+
|
| 5 |
+
GET /manage.html the page
|
| 6 |
+
GET /api/state everything the page shows (polled once a second)
|
| 7 |
+
POST /api/<action> load / unload / restart / download / install_engine / cancel_download / delete /
|
| 8 |
+
save_dir / settings / open
|
| 9 |
+
|
| 10 |
+
Bound to 127.0.0.1 only; every /api call needs the token from <config>/manager.json (X-Onw-Token header or ?token=).
|
| 11 |
+
"""
|
| 12 |
+
import json, os, secrets, shutil, subprocess, sys, threading, time, webbrowser
|
| 13 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 14 |
+
from urllib.parse import parse_qs, urlparse
|
| 15 |
+
|
| 16 |
+
from . import app, lemonade, __version__
|
| 17 |
+
from . import i18n
|
| 18 |
+
from .i18n import T
|
| 19 |
+
|
| 20 |
+
WEB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web")
|
| 21 |
+
INFO = lambda: os.path.join(app.config_dir(), "manager.json")
|
| 22 |
+
LAST_SEEN = [time.time()] # when the page last asked for the state (a browser-only window keeps us alive)
|
| 23 |
+
NOTES = {"vision": "画像も読めます", "reasoning": "考えてから答えます", "coding": "コード向け", "tool-calling": "ツール呼び出し"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def find_manager():
|
| 27 |
+
"""{port, token} of a running manager (the tray), or None."""
|
| 28 |
+
try:
|
| 29 |
+
d = json.load(open(INFO()))
|
| 30 |
+
if app._alive(d["pid"]):
|
| 31 |
+
return d
|
| 32 |
+
except (OSError, ValueError, KeyError):
|
| 33 |
+
pass
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Manager:
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self.lock = threading.Lock()
|
| 40 |
+
self.dl = None # {"key", "proc", "status", "frac", "text", "error", "done", "log"}
|
| 41 |
+
self.npu = None
|
| 42 |
+
self.ram = app.total_ram_gb()
|
| 43 |
+
self.busy = "" # a message about a long action (loading / deleting) for the page
|
| 44 |
+
self.busy_err = False
|
| 45 |
+
self.upd = {"latest": None, "tag": None, "notes": "", "checked": None, "state": "idle", "msg": "",
|
| 46 |
+
"checking": False, "error": ""}
|
| 47 |
+
self.on_updated = None # set by the tray: restart into the new version
|
| 48 |
+
self.on_update_found = None # set by the tray: notification
|
| 49 |
+
threading.Thread(target=self._update_loop, daemon=True).start()
|
| 50 |
+
threading.Thread(target=self._npu_info, daemon=True).start()
|
| 51 |
+
|
| 52 |
+
def _npu_info(self):
|
| 53 |
+
lemonade.npu()
|
| 54 |
+
self.npu = lemonade.npu_text()
|
| 55 |
+
|
| 56 |
+
# ---------------------------------------------------------------- state
|
| 57 |
+
def _engine(self):
|
| 58 |
+
"""FastFlowLM: installed version and the version onw uses."""
|
| 59 |
+
v = lemonade.installed_version()
|
| 60 |
+
return {"name": lemonade.ENGINE, "installed": v, "version": lemonade.VERSION,
|
| 61 |
+
"state": "ok" if v == lemonade.VERSION else ("old" if v else "missing")}
|
| 62 |
+
|
| 63 |
+
def state(self):
|
| 64 |
+
LAST_SEEN[0] = time.time()
|
| 65 |
+
cfg = app.load_config()
|
| 66 |
+
inst = app.installed(cfg)
|
| 67 |
+
info = app.server_info()
|
| 68 |
+
status = app.server_status(cfg)
|
| 69 |
+
self._poll_download()
|
| 70 |
+
dl = self.dl
|
| 71 |
+
models = []
|
| 72 |
+
for c in app.catalog(cfg):
|
| 73 |
+
key = c["key"]
|
| 74 |
+
path = inst.get(key)
|
| 75 |
+
mem = app.memory_estimate(c["size_gb"])
|
| 76 |
+
m = {"key": key, "title": c["title"], "path": path, "image": c["image"], "size_gb": c["size_gb"],
|
| 77 |
+
"mem_gb": mem, "fits": app.fits(mem, self.ram), "deletable": bool(path),
|
| 78 |
+
"note": "・".join(T(NOTES[l]) for l in c["labels"] if l in NOTES)}
|
| 79 |
+
m["state"] = self._state_of(key, path, info, status, dl)
|
| 80 |
+
if dl and dl["key"] == key and not dl.get("done"):
|
| 81 |
+
m["progress"] = dl["frac"]
|
| 82 |
+
m["note"] = T("ダウンロード中 {0}・ウィンドウを閉じても続きます", dl["text"])
|
| 83 |
+
elif dl and dl.get("done") == key and dl.get("error"):
|
| 84 |
+
m["note"] = T("ダウンロードに失敗: {0}", dl["error"])
|
| 85 |
+
models.append(m)
|
| 86 |
+
eng_dl = dl if dl and dl["key"] == "engine" else None
|
| 87 |
+
return {"version": __version__, "npu": self.npu or "", "npu_ok": lemonade.npu().get("arch") == "XDNA2",
|
| 88 |
+
"ram_gb": self.ram, "config": cfg, "api_url": app.api_url(cfg),
|
| 89 |
+
"models_dir_missing": app.models_dir_missing(cfg), "engine": self._engine(),
|
| 90 |
+
"engine_dl": {"frac": eng_dl["frac"], "text": eng_dl["text"], "error": eng_dl.get("error"),
|
| 91 |
+
"done": bool(eng_dl.get("done"))} if eng_dl else None,
|
| 92 |
+
"flm_error": app._FLM_CACHE.get("error", ""),
|
| 93 |
+
"server": {"status": status, "model": info and info.get("model"), "path": info and info.get("path"),
|
| 94 |
+
"error": app.failure_reason() if status == "failed" else "",
|
| 95 |
+
"title": app.model_title(info["model"]) if info else None, "port": info and info.get("port"),
|
| 96 |
+
"mem_gb": app.memory_estimate((app.catalog_entry(info["model"], cfg) or {}).get("size_gb"))
|
| 97 |
+
if info else None},
|
| 98 |
+
"save_dir": app.models_dir(cfg), "models": models, "busy": self.busy, "busy_err": self.busy_err,
|
| 99 |
+
"log": os.path.join(app.config_dir(), "server.log"),
|
| 100 |
+
"update": {**self.upd, "can_update": self._can_update(), "current": __version__}}
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def _state_of(key, path, info, status, dl):
|
| 104 |
+
if info and info.get("model") == key:
|
| 105 |
+
return "live" if status == "running" else ("loading" if status == "loading" else "failed")
|
| 106 |
+
if dl and dl["key"] == key and not dl.get("done"):
|
| 107 |
+
return "downloading"
|
| 108 |
+
if path:
|
| 109 |
+
return "ready"
|
| 110 |
+
return "missing"
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------- downloads (a child process per download)
|
| 113 |
+
def _spawn(self, key, args):
|
| 114 |
+
log = os.path.join(app.config_dir(), "download.log")
|
| 115 |
+
status = os.path.join(app.config_dir(), "download.json")
|
| 116 |
+
try:
|
| 117 |
+
os.remove(status)
|
| 118 |
+
except OSError:
|
| 119 |
+
pass
|
| 120 |
+
kw = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
|
| 121 |
+
with open(log, "w", encoding="utf8") as out: # a file, not a pipe: a chatty download never blocks on it
|
| 122 |
+
proc = subprocess.Popen([sys.executable, "-m", "onw.dl", *args, status], stdout=out,
|
| 123 |
+
stderr=subprocess.STDOUT, env={**os.environ, "PYTHONUTF8": "1"}, **kw)
|
| 124 |
+
self.dl = {"key": key, "proc": proc, "status": status, "frac": 0.0, "text": T("準備中…"), "error": None,
|
| 125 |
+
"done": None, "log": log}
|
| 126 |
+
|
| 127 |
+
def download(self, key):
|
| 128 |
+
cfg = app.load_config()
|
| 129 |
+
if app.catalog_entry(key, cfg) is None:
|
| 130 |
+
return {"error": T("そのモデルはありません")}
|
| 131 |
+
if lemonade.npu().get("arch") != "XDNA2":
|
| 132 |
+
return {"error": T("この PC には XDNA2 の NPU が見つかりません(Ryzen AI 300 シリーズ以降と NPU ドライバーが必要です)")}
|
| 133 |
+
info = app.server_info()
|
| 134 |
+
if info and info.get("model") == key:
|
| 135 |
+
return {"error": T("このモデルはロード中です。先にアンロードしてください。")}
|
| 136 |
+
if self.upd["state"] == "updating":
|
| 137 |
+
return {"error": T("onw の更新中です。終わってからダウンロードしてください")}
|
| 138 |
+
with self.lock:
|
| 139 |
+
if self.dl and self.dl["proc"].poll() is None:
|
| 140 |
+
return {"error": T("別のダウンロードが進行中です")}
|
| 141 |
+
self._spawn(key, [key])
|
| 142 |
+
return {}
|
| 143 |
+
|
| 144 |
+
def install_engine(self):
|
| 145 |
+
if self.upd["state"] == "updating":
|
| 146 |
+
return {"error": T("onw の更新中です。終わってからダウンロードしてください")}
|
| 147 |
+
with self.lock:
|
| 148 |
+
if self.dl and self.dl["proc"].poll() is None:
|
| 149 |
+
return {"error": T("別のダウンロードが進行中です")}
|
| 150 |
+
self._spawn("engine", ["--engine"])
|
| 151 |
+
return {}
|
| 152 |
+
|
| 153 |
+
def cancel_download(self):
|
| 154 |
+
with self.lock:
|
| 155 |
+
if self.dl and self.dl["proc"].poll() is None:
|
| 156 |
+
try: # flm pull runs as a child of the download process
|
| 157 |
+
import psutil
|
| 158 |
+
procs = psutil.Process(self.dl["proc"].pid).children(recursive=True)
|
| 159 |
+
except Exception:
|
| 160 |
+
procs = []
|
| 161 |
+
self.dl["proc"].terminate()
|
| 162 |
+
for q in procs:
|
| 163 |
+
try:
|
| 164 |
+
q.terminate()
|
| 165 |
+
except Exception:
|
| 166 |
+
pass
|
| 167 |
+
try:
|
| 168 |
+
self.dl["proc"].wait(10)
|
| 169 |
+
except subprocess.TimeoutExpired:
|
| 170 |
+
self.dl["proc"].kill()
|
| 171 |
+
self.dl = None
|
| 172 |
+
return {}
|
| 173 |
+
|
| 174 |
+
def _poll_download(self):
|
| 175 |
+
dl = self.dl
|
| 176 |
+
if not dl or dl.get("done"):
|
| 177 |
+
return
|
| 178 |
+
try:
|
| 179 |
+
st = json.load(open(dl["status"], encoding="utf8"))
|
| 180 |
+
dl["frac"], dl["text"] = min(float(st.get("frac", 0)), 0.99), st.get("text") or dl["text"]
|
| 181 |
+
except (OSError, ValueError):
|
| 182 |
+
pass
|
| 183 |
+
rc = dl["proc"].poll()
|
| 184 |
+
if rc is not None:
|
| 185 |
+
dl["done"] = dl["key"]
|
| 186 |
+
if rc != 0:
|
| 187 |
+
try:
|
| 188 |
+
out = open(dl["log"], encoding="utf8", errors="replace").read()[-4000:]
|
| 189 |
+
except OSError:
|
| 190 |
+
out = ""
|
| 191 |
+
dl["error"] = " ".join(out.split()[-30:]) or f"exit code {rc}"
|
| 192 |
+
else:
|
| 193 |
+
dl["frac"] = 1.0
|
| 194 |
+
app.flm_catalog(refresh=True) # flm pulled a model / FastFlowLM was installed
|
| 195 |
+
if not dl["key"].startswith("engine:"):
|
| 196 |
+
with app._CFG_LOCK:
|
| 197 |
+
if not app.load_config().get("model"):
|
| 198 |
+
app.update_config(model=dl["key"])
|
| 199 |
+
|
| 200 |
+
# ---------------------------------------------------------------- server
|
| 201 |
+
def load(self, key):
|
| 202 |
+
if key not in app.installed(app.load_config()):
|
| 203 |
+
return {"error": T("そのモデルはありません")}
|
| 204 |
+
cfg = app.update_config(model=key)
|
| 205 |
+
self.busy, self.busy_err = T("ロードしています…"), False
|
| 206 |
+
|
| 207 |
+
def work():
|
| 208 |
+
try:
|
| 209 |
+
app.start_server(cfg)
|
| 210 |
+
except Exception as e:
|
| 211 |
+
self.busy, self.busy_err = T("ロードできません: {0}", e), True
|
| 212 |
+
return
|
| 213 |
+
self.busy = ""
|
| 214 |
+
threading.Thread(target=work, daemon=True).start()
|
| 215 |
+
return {}
|
| 216 |
+
|
| 217 |
+
def unload(self):
|
| 218 |
+
threading.Thread(target=app.stop_server, daemon=True).start()
|
| 219 |
+
return {}
|
| 220 |
+
|
| 221 |
+
def restart(self):
|
| 222 |
+
info = app.server_info()
|
| 223 |
+
return self.load(info["model"]) if info else {}
|
| 224 |
+
|
| 225 |
+
# ---------------------------------------------------------------- models
|
| 226 |
+
def delete(self, key):
|
| 227 |
+
cfg = app.load_config()
|
| 228 |
+
info = app.server_info()
|
| 229 |
+
if key not in app.installed(cfg):
|
| 230 |
+
return {"error": T("そのモデルはありません")}
|
| 231 |
+
if info and info.get("model") == key:
|
| 232 |
+
return {"error": T("このモデルはロード中です。先にアンロードしてください。")}
|
| 233 |
+
try: # flm keeps its own models
|
| 234 |
+
lemonade.flm_remove(app.flm_catalog(cfg)[key]["checkpoint"], cfg)
|
| 235 |
+
except Exception as e:
|
| 236 |
+
return {"error": str(e)}
|
| 237 |
+
app.flm_catalog(cfg, refresh=True)
|
| 238 |
+
return {}
|
| 239 |
+
|
| 240 |
+
def save_dir(self, path):
|
| 241 |
+
"""A new save folder: flm finds the models in it from now on (the ones in the old folder stay there)."""
|
| 242 |
+
new = os.path.abspath(path)
|
| 243 |
+
try:
|
| 244 |
+
os.makedirs(new, exist_ok=True)
|
| 245 |
+
except OSError as e:
|
| 246 |
+
return {"error": T("そのフォルダは使えません: {0}", e)}
|
| 247 |
+
if app.server_info():
|
| 248 |
+
return {"error": T("このモデルはロード中です。先にアンロードしてください。")}
|
| 249 |
+
app.update_config(models_dir=new)
|
| 250 |
+
app.flm_catalog(refresh=True)
|
| 251 |
+
return {}
|
| 252 |
+
|
| 253 |
+
def settings(self, new):
|
| 254 |
+
with app._CFG_LOCK:
|
| 255 |
+
return self._settings(new)
|
| 256 |
+
|
| 257 |
+
def _settings(self, new):
|
| 258 |
+
cfg = app.load_config()
|
| 259 |
+
try:
|
| 260 |
+
port, ctx = int(new.get("port", cfg["port"])), int(new.get("context", cfg["context"]))
|
| 261 |
+
if not (1 <= port <= 65535) or ctx < 256:
|
| 262 |
+
raise ValueError
|
| 263 |
+
except (TypeError, ValueError):
|
| 264 |
+
return {"error": T("ポートかコンテキスト長の値が不正です")}
|
| 265 |
+
from .i18n import LANGS
|
| 266 |
+
if new.get("lang", "auto") not in ("auto", *LANGS):
|
| 267 |
+
new = {k: v for k, v in new.items() if k != "lang"}
|
| 268 |
+
old = dict(cfg)
|
| 269 |
+
for k in ("lan", "api_key", "autostart_server", "login_start", "update_check", "lang"):
|
| 270 |
+
if k in new:
|
| 271 |
+
cfg[k] = new[k]
|
| 272 |
+
cfg["port"], cfg["context"] = port, ctx
|
| 273 |
+
server_keys = ("lan", "api_key", "port", "context")
|
| 274 |
+
app.save_config(cfg)
|
| 275 |
+
i18n.current(cfg) # messages switch language right away
|
| 276 |
+
try:
|
| 277 |
+
app.set_login_start(bool(cfg["login_start"]))
|
| 278 |
+
except OSError:
|
| 279 |
+
pass
|
| 280 |
+
changed = any(str(old.get(k)) != str(cfg.get(k)) for k in server_keys)
|
| 281 |
+
return {"restart_needed": changed and app.server_info() is not None}
|
| 282 |
+
|
| 283 |
+
# ---------------------------------------------------------------- updates of onw itself
|
| 284 |
+
@staticmethod
|
| 285 |
+
def _can_update():
|
| 286 |
+
from . import update
|
| 287 |
+
return update.can_update()
|
| 288 |
+
|
| 289 |
+
def _update_loop(self):
|
| 290 |
+
time.sleep(30) # let the tray and the server start first
|
| 291 |
+
while True:
|
| 292 |
+
if app.load_config().get("update_check", True):
|
| 293 |
+
self.check_update()
|
| 294 |
+
time.sleep(24 * 3600)
|
| 295 |
+
|
| 296 |
+
def start_check(self):
|
| 297 |
+
"""The window's "Check now": checks in the background and answers at once; the page follows
|
| 298 |
+
upd["checking"] / upd["error"] (a slow connection must not leave the button without an answer)."""
|
| 299 |
+
if not self.upd["checking"]:
|
| 300 |
+
threading.Thread(target=self.check_update, daemon=True).start()
|
| 301 |
+
return {"checking": True}
|
| 302 |
+
|
| 303 |
+
def check_update(self):
|
| 304 |
+
self.upd.update(checking=True, error="")
|
| 305 |
+
try:
|
| 306 |
+
r = self._check_update()
|
| 307 |
+
except Exception as e:
|
| 308 |
+
r = {"error": T("更新を確認できませんでした: {0}", e)}
|
| 309 |
+
self.upd.update(checking=False, error=r.get("error", ""))
|
| 310 |
+
return r
|
| 311 |
+
|
| 312 |
+
def _check_update(self):
|
| 313 |
+
from . import update
|
| 314 |
+
found = update.latest()
|
| 315 |
+
self.upd["checked"] = time.time()
|
| 316 |
+
if found is None:
|
| 317 |
+
return {"error": T("更新を確認できませんでした(オフライン?)")}
|
| 318 |
+
v, tag = found
|
| 319 |
+
if update.newer(v):
|
| 320 |
+
fresh = self.upd["latest"] != v
|
| 321 |
+
self.upd.update(latest=v, tag=tag, notes=update.notes(lang=i18n.current()))
|
| 322 |
+
if fresh and self.on_update_found:
|
| 323 |
+
try:
|
| 324 |
+
self.on_update_found(v)
|
| 325 |
+
except Exception:
|
| 326 |
+
pass
|
| 327 |
+
else:
|
| 328 |
+
self.upd.update(latest=None, tag=None, notes="")
|
| 329 |
+
return {"latest": self.upd["latest"]}
|
| 330 |
+
|
| 331 |
+
def run_update(self):
|
| 332 |
+
from . import update
|
| 333 |
+
if not self.upd["tag"]:
|
| 334 |
+
return {"error": T("新しい版はありません")}
|
| 335 |
+
if not update.can_update():
|
| 336 |
+
return {"error": T("このフォルダの onw は 1 行インストーラーで入れたものではないので、自動更新できません")}
|
| 337 |
+
if self.upd["state"] == "updating":
|
| 338 |
+
return {}
|
| 339 |
+
if self.dl and self.dl["proc"].poll() is None: # the restart would orphan the download
|
| 340 |
+
return {"error": T("ダウンロードが終わってから更新してください")}
|
| 341 |
+
self.upd.update(state="updating", msg=T("準備中…"))
|
| 342 |
+
|
| 343 |
+
def work():
|
| 344 |
+
try:
|
| 345 |
+
v = update.apply(self.upd["tag"], progress=lambda t: self.upd.update(msg=t))
|
| 346 |
+
self.upd.update(state="done", msg=T("v{0} に更新しました。再起動します…", v))
|
| 347 |
+
if self.on_updated:
|
| 348 |
+
self.on_updated()
|
| 349 |
+
else:
|
| 350 |
+
self.upd["msg"] = T("v{0} に更新しました。onw を起動し直してください", v)
|
| 351 |
+
except Exception as e:
|
| 352 |
+
self.upd.update(state="error", msg=T("更新できませんでした: {0}", e))
|
| 353 |
+
threading.Thread(target=work, daemon=True).start()
|
| 354 |
+
return {}
|
| 355 |
+
|
| 356 |
+
def open(self, what, key=None):
|
| 357 |
+
cfg = app.load_config()
|
| 358 |
+
if what == "log":
|
| 359 |
+
app.open_path(os.path.join(app.config_dir(), "server.log"))
|
| 360 |
+
elif what == "folder":
|
| 361 |
+
app.open_path(app.models_dir(cfg))
|
| 362 |
+
elif what in ("chat", "check"):
|
| 363 |
+
webbrowser.open(f"http://localhost:{cfg['port']}/{what}")
|
| 364 |
+
elif what == "flm":
|
| 365 |
+
webbrowser.open("https://github.com/ROCm/FastFlowLM")
|
| 366 |
+
return {}
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class _Handler(BaseHTTPRequestHandler):
|
| 370 |
+
manager: Manager = None
|
| 371 |
+
token: str = ""
|
| 372 |
+
|
| 373 |
+
def log_message(self, *a): # quiet
|
| 374 |
+
pass
|
| 375 |
+
|
| 376 |
+
def _send(self, code, body, ctype="application/json"):
|
| 377 |
+
data = body if isinstance(body, bytes) else json.dumps(body, ensure_ascii=False).encode("utf8")
|
| 378 |
+
self.send_response(code)
|
| 379 |
+
self.send_header("Content-Type", ctype + ("; charset=utf-8" if ctype.startswith("text") else ""))
|
| 380 |
+
self.send_header("Content-Length", str(len(data)))
|
| 381 |
+
self.send_header("Cache-Control", "no-store")
|
| 382 |
+
self.end_headers()
|
| 383 |
+
self.wfile.write(data)
|
| 384 |
+
|
| 385 |
+
def _authed(self, q):
|
| 386 |
+
t = self.headers.get("X-Onw-Token") or (q.get("token") or [""])[0]
|
| 387 |
+
return secrets.compare_digest(t, self.token)
|
| 388 |
+
|
| 389 |
+
def do_GET(self):
|
| 390 |
+
u = urlparse(self.path)
|
| 391 |
+
q = parse_qs(u.query)
|
| 392 |
+
if u.path in ("/", "/manage.html"):
|
| 393 |
+
return self._send(200, i18n.page(os.path.join(WEB, "manage.html")), "text/html")
|
| 394 |
+
if u.path == "/api/state":
|
| 395 |
+
if not self._authed(q):
|
| 396 |
+
return self._send(403, {"error": "forbidden"})
|
| 397 |
+
return self._send(200, self.manager.state())
|
| 398 |
+
self._send(404, {"error": "not found"})
|
| 399 |
+
|
| 400 |
+
def do_POST(self):
|
| 401 |
+
u = urlparse(self.path)
|
| 402 |
+
if not self._authed(parse_qs(u.query)):
|
| 403 |
+
return self._send(403, {"error": "forbidden"})
|
| 404 |
+
m = self.manager
|
| 405 |
+
act = u.path[len("/api/"):]
|
| 406 |
+
try:
|
| 407 |
+
n = int(self.headers.get("Content-Length") or 0)
|
| 408 |
+
body = json.loads(self.rfile.read(n) or b"{}")
|
| 409 |
+
if act == "load":
|
| 410 |
+
r = m.load(body["key"])
|
| 411 |
+
elif act == "unload":
|
| 412 |
+
r = m.unload()
|
| 413 |
+
elif act == "restart":
|
| 414 |
+
r = m.restart()
|
| 415 |
+
elif act == "download":
|
| 416 |
+
r = m.download(body["key"])
|
| 417 |
+
elif act == "cancel_download":
|
| 418 |
+
r = m.cancel_download()
|
| 419 |
+
elif act == "delete":
|
| 420 |
+
r = m.delete(body["key"])
|
| 421 |
+
elif act == "install_engine":
|
| 422 |
+
r = m.install_engine()
|
| 423 |
+
elif act == "save_dir":
|
| 424 |
+
r = m.save_dir(body["path"])
|
| 425 |
+
elif act == "settings":
|
| 426 |
+
r = m.settings(body)
|
| 427 |
+
elif act == "update_check":
|
| 428 |
+
r = m.start_check()
|
| 429 |
+
elif act == "update":
|
| 430 |
+
r = m.run_update()
|
| 431 |
+
elif act == "open":
|
| 432 |
+
r = m.open(body.get("what"), body.get("key"))
|
| 433 |
+
else:
|
| 434 |
+
return self._send(404, {"error": "not found"})
|
| 435 |
+
except Exception as e:
|
| 436 |
+
r = {"error": str(e)}
|
| 437 |
+
self._send(200, r)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def serve(manager=None):
|
| 441 |
+
"""Start the manager's HTTP server in a daemon thread; returns {port, token}. Writes <config>/manager.json."""
|
| 442 |
+
manager = manager or Manager()
|
| 443 |
+
handler = type("H", (_Handler,), {"manager": manager, "token": secrets.token_hex(16)})
|
| 444 |
+
srv = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
| 445 |
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
| 446 |
+
info = {"port": srv.server_address[1], "token": handler.token, "pid": os.getpid()}
|
| 447 |
+
with open(INFO(), "w") as f:
|
| 448 |
+
json.dump(info, f)
|
| 449 |
+
try:
|
| 450 |
+
os.chmod(INFO(), 0o600)
|
| 451 |
+
except OSError:
|
| 452 |
+
pass
|
| 453 |
+
return info
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def page_url(info, tab="server"):
|
| 457 |
+
return f"http://127.0.0.1:{info['port']}/manage.html?token={info['token']}#{tab}"
|
onw/relaunch.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Start onw again once an old process has exited (after an update: the tray, or an open onw window).
|
| 2 |
+
usage (internal): python -m onw.relaunch OLD_PID [onw arguments, default: tray]"""
|
| 3 |
+
import os, subprocess, sys, time
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def main():
|
| 7 |
+
pid = int(sys.argv[1])
|
| 8 |
+
args = sys.argv[2:] or ["tray"]
|
| 9 |
+
try:
|
| 10 |
+
import psutil
|
| 11 |
+
deadline = time.time() + 60
|
| 12 |
+
while psutil.pid_exists(pid) and time.time() < deadline:
|
| 13 |
+
time.sleep(0.5)
|
| 14 |
+
except ImportError:
|
| 15 |
+
time.sleep(5)
|
| 16 |
+
exe = sys.executable
|
| 17 |
+
if os.name == "nt" and exe.lower().endswith("python.exe") and os.path.exists(exe[:-10] + "pythonw.exe"):
|
| 18 |
+
exe = exe[:-10] + "pythonw.exe"
|
| 19 |
+
kw = ({"creationflags": subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt"
|
| 20 |
+
else {"start_new_session": True})
|
| 21 |
+
subprocess.Popen([exe, "-m", "onw", *args], cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
| 22 |
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kw)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__ == "__main__":
|
| 26 |
+
main()
|
onw/server.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible API server for one model on the AMD Ryzen AI NPU (point other apps at http://HOST:PORT/v1).
|
| 2 |
+
|
| 3 |
+
The model runs in FastFlowLM (`flm serve`, the NPU-only engine Lemonade Server uses; see onw.lemonade), started
|
| 4 |
+
here as a child process on a free localhost port; this server forwards the OpenAI requests to it (as Lemonade's
|
| 5 |
+
WrappedServer does) and adds the chat UI, the check page and the API key.
|
| 6 |
+
|
| 7 |
+
GET / what this server is: model, OpenAI base URL, endpoints (JSON)
|
| 8 |
+
GET /v1/models
|
| 9 |
+
GET /v1/models/{id}
|
| 10 |
+
POST /v1/chat/completions (stream true/false)
|
| 11 |
+
POST /v1/completions
|
| 12 |
+
GET /health 200 once the engine has loaded the model (503 while it loads)
|
| 13 |
+
GET /chat browser chat UI for trying the model
|
| 14 |
+
GET /check verification page: speed, image, multi-turn
|
| 15 |
+
GET /api/info model, engine and NPU details
|
| 16 |
+
|
| 17 |
+
usage: onw serve MODEL [--port 8010] [--host 0.0.0.0] [--api-key KEY] [--context 4096] [--open]
|
| 18 |
+
MODEL is a model name from the onw window or `onw list` (llama3.2-1b-FLM, qwen3-4b-FLM, ...); it is downloaded
|
| 19 |
+
first when missing. CORS is open, so browser-based clients work too; with --api-key every /v1 request needs
|
| 20 |
+
"Authorization: Bearer KEY".
|
| 21 |
+
"""
|
| 22 |
+
import argparse, asyncio, atexit, json, os, subprocess, sys, threading, time
|
| 23 |
+
|
| 24 |
+
import httpx
|
| 25 |
+
import uvicorn
|
| 26 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 27 |
+
from fastapi.exceptions import RequestValidationError
|
| 28 |
+
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
|
| 29 |
+
from onw import __version__, i18n, lemonade
|
| 30 |
+
|
| 31 |
+
MODEL_ID = "npu-model" # set in main()
|
| 32 |
+
app = FastAPI(title="LLM on the AMD NPU")
|
| 33 |
+
info = {}
|
| 34 |
+
WEB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web")
|
| 35 |
+
API_KEY = None # --api-key: required as a Bearer token on /v1
|
| 36 |
+
BACKEND = {"url": None, "model": None, "proc": None} # the engine: base URL, the model name it expects, its process
|
| 37 |
+
READY = threading.Event()
|
| 38 |
+
client = None # httpx.AsyncClient, made on the first request (inside the event loop)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def oai_error(status, message, type_="invalid_request_error", code=None):
|
| 42 |
+
"""An error in OpenAI's shape: {"error": {"message", "type", "code"}}."""
|
| 43 |
+
return JSONResponse({"error": {"message": message, "type": type_, "param": None, "code": code}}, status_code=status)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@app.exception_handler(HTTPException)
|
| 47 |
+
async def _http_error(request, e):
|
| 48 |
+
return oai_error(e.status_code, str(e.detail), "invalid_request_error" if e.status_code < 500 else "server_error")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@app.exception_handler(RequestValidationError)
|
| 52 |
+
async def _validation_error(request, e):
|
| 53 |
+
return oai_error(400, str(e))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@app.exception_handler(Exception)
|
| 57 |
+
async def _server_error(request, e):
|
| 58 |
+
return oai_error(500, f"{type(e).__name__}: {e}", "server_error")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@app.middleware("http")
|
| 62 |
+
async def cors_and_key(request: Request, call_next):
|
| 63 |
+
"""Open CORS (browser-based OpenAI clients) and the optional API key on /v1."""
|
| 64 |
+
if request.method == "OPTIONS":
|
| 65 |
+
resp = JSONResponse({})
|
| 66 |
+
elif API_KEY and request.url.path.startswith("/v1") and \
|
| 67 |
+
request.headers.get("authorization", "") != f"Bearer {API_KEY}":
|
| 68 |
+
resp = oai_error(401, "invalid API key", code="invalid_api_key")
|
| 69 |
+
else:
|
| 70 |
+
resp = await call_next(request)
|
| 71 |
+
resp.headers["Access-Control-Allow-Origin"] = "*"
|
| 72 |
+
resp.headers["Access-Control-Allow-Headers"] = "*"
|
| 73 |
+
resp.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
|
| 74 |
+
return resp
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@app.get("/")
|
| 78 |
+
def index(request: Request):
|
| 79 |
+
base = str(request.base_url).rstrip("/")
|
| 80 |
+
return {"object": "onw.server", "name": "onw AMD - 俺のNPUがこんなに動くわけない", "version": __version__,
|
| 81 |
+
"model": MODEL_ID, "engine": info.get("engine_name"), "openai_base_url": base + "/v1",
|
| 82 |
+
"api_key_required": bool(API_KEY), "ready": READY.is_set(),
|
| 83 |
+
"endpoints": {"models": "/v1/models", "chat_completions": "/v1/chat/completions",
|
| 84 |
+
"completions": "/v1/completions", "health": "/health", "chat_ui": "/chat",
|
| 85 |
+
"check_page": "/check", "info": "/api/info"},
|
| 86 |
+
"context": info.get("context"), "vision": info.get("vision")}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@app.get("/health")
|
| 90 |
+
def health():
|
| 91 |
+
if not READY.is_set():
|
| 92 |
+
return JSONResponse({"status": "loading", "model": MODEL_ID}, status_code=503)
|
| 93 |
+
return {"status": "ok", "model": MODEL_ID}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@app.get("/chat")
|
| 97 |
+
def chat_ui():
|
| 98 |
+
return HTMLResponse(i18n.page(os.path.join(WEB, "index.html")))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@app.get("/check")
|
| 102 |
+
def check_page():
|
| 103 |
+
return HTMLResponse(i18n.page(os.path.join(WEB, "check.html")))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@app.get("/api/info")
|
| 107 |
+
def api_info():
|
| 108 |
+
return {**info, "ready": READY.is_set()}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
STARTED = int(time.time())
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _model_card():
|
| 115 |
+
return {"id": MODEL_ID, "object": "model", "created": STARTED, "owned_by": "local-npu",
|
| 116 |
+
"engine": info.get("engine"), "labels": info.get("labels", [])}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@app.get("/v1/models")
|
| 120 |
+
def models():
|
| 121 |
+
return {"object": "list", "data": [_model_card()]}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@app.get("/v1/models/{model_id:path}")
|
| 125 |
+
def model(model_id: str):
|
| 126 |
+
if model_id != MODEL_ID:
|
| 127 |
+
raise HTTPException(404, f"model {model_id!r} not found (this server runs {MODEL_ID!r})")
|
| 128 |
+
return _model_card()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ThinkSplit:
|
| 132 |
+
"""FastFlowLM writes the thinking into the content as <think>...</think>; OpenAI clients (and the chat UI) expect it
|
| 133 |
+
in reasoning_content. Fed the content piece by piece (a tag may be cut between two pieces), returns
|
| 134 |
+
(reasoning, content) for each piece."""
|
| 135 |
+
OPEN, CLOSE = "<think>", "</think>"
|
| 136 |
+
|
| 137 |
+
def __init__(self):
|
| 138 |
+
self.state, self.buf = "start", "" # start (nothing seen yet) -> think -> gap -> text, or start -> text
|
| 139 |
+
|
| 140 |
+
def feed(self, s, final=False):
|
| 141 |
+
self.buf += s
|
| 142 |
+
think = text = ""
|
| 143 |
+
while True:
|
| 144 |
+
if self.state == "start": # only a leading <think> opens the thinking
|
| 145 |
+
head = self.buf.lstrip()
|
| 146 |
+
if head.startswith(self.OPEN):
|
| 147 |
+
self.state, self.buf = "think", head[len(self.OPEN):]
|
| 148 |
+
elif self.OPEN.startswith(head) and not final:
|
| 149 |
+
break # "", "<", "<thi": wait for more
|
| 150 |
+
else:
|
| 151 |
+
self.state = "text"
|
| 152 |
+
elif self.state == "think":
|
| 153 |
+
i = self.buf.find(self.CLOSE)
|
| 154 |
+
if i >= 0:
|
| 155 |
+
think += self.buf[:i]
|
| 156 |
+
self.state, self.buf = "gap", self.buf[i + len(self.CLOSE):]
|
| 157 |
+
continue
|
| 158 |
+
keep = 0 if final else next((k for k in range(len(self.CLOSE) - 1, 0, -1)
|
| 159 |
+
if self.buf.endswith(self.CLOSE[:k])), 0)
|
| 160 |
+
think, self.buf = think + self.buf[:len(self.buf) - keep], self.buf[len(self.buf) - keep:]
|
| 161 |
+
break
|
| 162 |
+
elif self.state == "gap": # the line breaks between </think> and the answer
|
| 163 |
+
self.buf = self.buf.lstrip("\n")
|
| 164 |
+
if not self.buf:
|
| 165 |
+
break
|
| 166 |
+
self.state = "text"
|
| 167 |
+
else:
|
| 168 |
+
text, self.buf = text + self.buf, ""
|
| 169 |
+
break
|
| 170 |
+
return think, text
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def flm_request(body):
|
| 174 |
+
"""OpenAI / onw thinking switches -> FastFlowLM's "think". Always sent: flm keeps the last request's setting for
|
| 175 |
+
the following ones, so a request without a switch would otherwise think when the one before asked for it."""
|
| 176 |
+
if "think" in body:
|
| 177 |
+
return
|
| 178 |
+
on = (body.get("chat_template_kwargs") or {}).get("enable_thinking")
|
| 179 |
+
effort = body.get("reasoning_effort")
|
| 180 |
+
if isinstance(effort, str):
|
| 181 |
+
on = effort not in ("none", "minimal")
|
| 182 |
+
body["think"] = bool(on)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
async def split_stream(lines):
|
| 186 |
+
"""SSE lines from FastFlowLM -> the same events with <think> moved into delta.reasoning_content."""
|
| 187 |
+
sp = ThinkSplit()
|
| 188 |
+
async for line in lines:
|
| 189 |
+
if not line.startswith("data:") or line.strip() == "data: [DONE]":
|
| 190 |
+
yield line + "\n"
|
| 191 |
+
continue
|
| 192 |
+
try:
|
| 193 |
+
j = json.loads(line[5:])
|
| 194 |
+
except ValueError:
|
| 195 |
+
yield line + "\n"
|
| 196 |
+
continue
|
| 197 |
+
for c in j.get("choices") or []:
|
| 198 |
+
d = c.setdefault("delta", {})
|
| 199 |
+
final = c.get("finish_reason") is not None # the last chunk: flush what waited for more
|
| 200 |
+
if isinstance(d.get("content"), str) or final:
|
| 201 |
+
think, text = sp.feed(d.get("content") or "", final=final)
|
| 202 |
+
if text or isinstance(d.get("content"), str):
|
| 203 |
+
d["content"] = text
|
| 204 |
+
if think:
|
| 205 |
+
d["reasoning_content"] = (d.get("reasoning_content") or "") + think
|
| 206 |
+
yield "data: " + json.dumps(j, ensure_ascii=False) + "\n"
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
async def forward(request: Request, path):
|
| 210 |
+
"""Send the request on to the engine (the model name it knows in "model"); streams stay streams."""
|
| 211 |
+
global client
|
| 212 |
+
if not READY.is_set():
|
| 213 |
+
return oai_error(503, "the model is still loading on the NPU", "server_error", "model_loading")
|
| 214 |
+
try:
|
| 215 |
+
body = await request.json()
|
| 216 |
+
except ValueError:
|
| 217 |
+
raise HTTPException(400, "the request body is not valid JSON")
|
| 218 |
+
if not isinstance(body, dict):
|
| 219 |
+
raise HTTPException(400, "the request body must be a JSON object")
|
| 220 |
+
if (body.get("n") or 1) != 1:
|
| 221 |
+
raise HTTPException(400, "n > 1 is not supported (one NPU engine)")
|
| 222 |
+
body["model"] = BACKEND["model"]
|
| 223 |
+
flm_request(body)
|
| 224 |
+
if client is None:
|
| 225 |
+
client = httpx.AsyncClient(base_url=BACKEND["url"], timeout=httpx.Timeout(None, connect=10))
|
| 226 |
+
req = client.build_request("POST", path, json=body)
|
| 227 |
+
try:
|
| 228 |
+
r = await client.send(req, stream=True)
|
| 229 |
+
except httpx.HTTPError as e:
|
| 230 |
+
return oai_error(502, f"the NPU engine did not answer: {e}", "server_error")
|
| 231 |
+
ctype = r.headers.get("content-type", "application/json")
|
| 232 |
+
if body.get("stream") and r.status_code == 200:
|
| 233 |
+
async def relay():
|
| 234 |
+
try:
|
| 235 |
+
if path.endswith("chat/completions"):
|
| 236 |
+
async for line in split_stream(r.aiter_lines()):
|
| 237 |
+
yield line
|
| 238 |
+
else:
|
| 239 |
+
async for chunk in r.aiter_raw():
|
| 240 |
+
yield chunk
|
| 241 |
+
finally: # the client left or the answer ended: stop the engine's work
|
| 242 |
+
await r.aclose()
|
| 243 |
+
return StreamingResponse(relay(), status_code=r.status_code, media_type=ctype.split(";")[0],
|
| 244 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 245 |
+
data = await r.aread()
|
| 246 |
+
await r.aclose()
|
| 247 |
+
if r.status_code == 200 and "json" in ctype: # the answer carries this server's model name
|
| 248 |
+
try:
|
| 249 |
+
j = json.loads(data)
|
| 250 |
+
if isinstance(j, dict) and "model" in j:
|
| 251 |
+
j["model"] = MODEL_ID
|
| 252 |
+
for c in j.get("choices") or []:
|
| 253 |
+
msg = c.get("message") or {}
|
| 254 |
+
if isinstance(msg.get("content"), str):
|
| 255 |
+
think, text = ThinkSplit().feed(msg["content"], final=True)
|
| 256 |
+
if think:
|
| 257 |
+
msg["content"], msg["reasoning_content"] = text, think
|
| 258 |
+
data = json.dumps(j, ensure_ascii=False).encode("utf8")
|
| 259 |
+
except ValueError:
|
| 260 |
+
pass
|
| 261 |
+
if r.status_code >= 400 and "json" not in ctype:
|
| 262 |
+
return oai_error(r.status_code, data.decode("utf8", "replace")[:1000] or "NPU engine error", "server_error")
|
| 263 |
+
return Response(data, status_code=r.status_code, media_type=ctype.split(";")[0])
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.post("/v1/chat/completions")
|
| 267 |
+
async def chat(request: Request):
|
| 268 |
+
return await forward(request, "/v1/chat/completions")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@app.post("/v1/completions")
|
| 272 |
+
async def completions(request: Request):
|
| 273 |
+
return await forward(request, "/v1/completions")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------------ the model and its engine
|
| 277 |
+
|
| 278 |
+
def resolve(key):
|
| 279 |
+
"""(flm checkpoint, labels) of a model name ("llama3.2-1b-FLM", or flm's own "llama3.2:1b"). Downloads what is
|
| 280 |
+
missing: FastFlowLM, then the model."""
|
| 281 |
+
from onw import app as onwapp
|
| 282 |
+
cfg = onwapp.load_config()
|
| 283 |
+
if not lemonade.up_to_date():
|
| 284 |
+
print(f"[setup] installing FastFlowLM {lemonade.VERSION} ...", flush=True)
|
| 285 |
+
last = [0.0]
|
| 286 |
+
|
| 287 |
+
def progress(frac, text):
|
| 288 |
+
if time.time() - last[0] > 5:
|
| 289 |
+
last[0] = time.time()
|
| 290 |
+
print(f"[setup] {text}", flush=True)
|
| 291 |
+
lemonade.install(progress)
|
| 292 |
+
ok, msg = lemonade.flm_validate(cfg)
|
| 293 |
+
if not ok:
|
| 294 |
+
sys.exit(f"ERROR: FastFlowLM NPU check failed: {msg}")
|
| 295 |
+
cat = lemonade.flm_models(cfg)
|
| 296 |
+
m = cat.get(key) or cat.get(lemonade.flm_name(key))
|
| 297 |
+
if m is None:
|
| 298 |
+
sys.exit(f"ERROR: FastFlowLM has no model {key!r} (onw list shows the models).")
|
| 299 |
+
if not m["installed"]:
|
| 300 |
+
print(f"[setup] flm pull {m['checkpoint']} ...", flush=True)
|
| 301 |
+
if subprocess.run(lemonade.flm_pull_command(m["checkpoint"]), env=lemonade.flm_env(cfg)).returncode != 0:
|
| 302 |
+
sys.exit("ERROR: flm pull failed")
|
| 303 |
+
return m["checkpoint"], m["labels"]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def start_engine(checkpoint, port, ctx):
|
| 307 |
+
"""Start FastFlowLM on a free port and mark READY once it answers; if it ends, this server ends too (the window
|
| 308 |
+
then shows the failure and the log)."""
|
| 309 |
+
bport = lemonade.free_port(8001, avoid=(port,))
|
| 310 |
+
argv, ready_path, env = lemonade.serve_command(checkpoint, bport, ctx)
|
| 311 |
+
print(f"[onw] FastFlowLM: {' '.join(argv)}", flush=True)
|
| 312 |
+
kw = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
|
| 313 |
+
proc = subprocess.Popen(argv, env={**os.environ, **env}, cwd=os.path.dirname(argv[0]),
|
| 314 |
+
stdout=sys.stdout, stderr=subprocess.STDOUT, **kw)
|
| 315 |
+
lemonade.tie_to_this_process(proc)
|
| 316 |
+
BACKEND.update(url=f"http://127.0.0.1:{bport}", proc=proc)
|
| 317 |
+
atexit.register(lambda: proc.poll() is None and proc.kill())
|
| 318 |
+
|
| 319 |
+
def watch():
|
| 320 |
+
t0 = time.time()
|
| 321 |
+
if lemonade.wait_ready(proc, BACKEND["url"] + ready_path):
|
| 322 |
+
print(f"[onw] model loaded on the NPU in {time.time() - t0:.0f} s", flush=True)
|
| 323 |
+
READY.set()
|
| 324 |
+
rc = proc.wait()
|
| 325 |
+
print(f"ERROR: the NPU engine (FastFlowLM) ended (exit code {rc})", flush=True)
|
| 326 |
+
os._exit(1)
|
| 327 |
+
threading.Thread(target=watch, daemon=True).start()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def main(argv=None):
|
| 331 |
+
global MODEL_ID, API_KEY
|
| 332 |
+
ap = argparse.ArgumentParser(prog="onw serve", description="chat UI + OpenAI-compatible API on the AMD NPU")
|
| 333 |
+
ap.add_argument("model", help="model name from `onw list` (llama3.2-1b-FLM, qwen3-4b-FLM, ...)")
|
| 334 |
+
ap.add_argument("--host", default="127.0.0.1")
|
| 335 |
+
ap.add_argument("--port", type=int, default=8010)
|
| 336 |
+
ap.add_argument("--context", type=int, default=4096, help="context length in tokens (default 4096)")
|
| 337 |
+
ap.add_argument("--open", action="store_true", help="open the chat UI in the default browser once loaded")
|
| 338 |
+
ap.add_argument("--api-key", help="require this key as a Bearer token on /v1 (e.g. with --host 0.0.0.0)")
|
| 339 |
+
a = ap.parse_args(argv)
|
| 340 |
+
API_KEY = a.api_key or os.environ.get("ONW_API_KEY") or None
|
| 341 |
+
n = lemonade.npu()
|
| 342 |
+
print(f"[onw] AMD {__version__} | {lemonade.npu_text()} | {n.get('name', '')}", flush=True)
|
| 343 |
+
if n.get("arch") != "XDNA2":
|
| 344 |
+
sys.exit("ERROR: no AMD XDNA2 NPU found (Ryzen AI 300 series or newer with the NPU driver installed). "
|
| 345 |
+
f"onw AMD runs models on the NPU only. Driver: {lemonade.DRIVER_URL}")
|
| 346 |
+
from onw.app import _port_free
|
| 347 |
+
if not _port_free(a.host, a.port): # before the engine starts and loads the model for nothing
|
| 348 |
+
sys.exit(f"ERROR: port {a.port} is in use by another program (choose another one with --port)")
|
| 349 |
+
checkpoint, labels = resolve(a.model)
|
| 350 |
+
MODEL_ID = lemonade.flm_name(checkpoint)
|
| 351 |
+
BACKEND["model"] = checkpoint # flm wants its checkpoint name in "model"
|
| 352 |
+
info.update(model=MODEL_ID, title=MODEL_ID, engine="flm", engine_name=lemonade.ENGINE,
|
| 353 |
+
engine_version=lemonade.VERSION, devices={"lm": "NPU"}, npu=lemonade.npu_text(),
|
| 354 |
+
labels=labels, vision="vision" in labels, think="reasoning" in labels, context=a.context,
|
| 355 |
+
max_context=a.context)
|
| 356 |
+
start_engine(checkpoint, a.port, a.context)
|
| 357 |
+
if a.open:
|
| 358 |
+
import webbrowser
|
| 359 |
+
host = "localhost" if a.host in ("0.0.0.0", "127.0.0.1") else a.host
|
| 360 |
+
|
| 361 |
+
def open_when_ready():
|
| 362 |
+
READY.wait()
|
| 363 |
+
webbrowser.open(f"http://{host}:{a.port}/chat")
|
| 364 |
+
threading.Thread(target=open_when_ready, daemon=True).start()
|
| 365 |
+
print(f"\n OpenAI API: http://localhost:{a.port}/v1 (model id: {MODEL_ID})"
|
| 366 |
+
f"\n Chat UI: http://localhost:{a.port}/chat\n Check page: http://localhost:{a.port}/check\n", flush=True)
|
| 367 |
+
uvicorn.run(app, host=a.host, port=a.port, log_level="warning")
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
if __name__ == "__main__":
|
| 371 |
+
main()
|
onw/tray.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""onw AMD tray: the resident icon (Windows task tray / Ubuntu top-bar indicator).
|
| 2 |
+
|
| 3 |
+
onw tray icon + menu: open the onw window (models / server / settings), chat UI, check page, copy the
|
| 4 |
+
OpenAI API URL, start / stop the server. With no model downloaded yet it opens the model manager.
|
| 5 |
+
|
| 6 |
+
The server itself runs as a separate process managed by onw.app (so the window and the tray share it). The tray
|
| 7 |
+
also hosts the manager (onw.manager: downloads, model list, settings) that the window talks to, so downloads keep
|
| 8 |
+
going while the window is closed.
|
| 9 |
+
"""
|
| 10 |
+
import json, os, subprocess, sys, threading, time, webbrowser
|
| 11 |
+
|
| 12 |
+
from . import app, __version__
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def open_window(tab="server", updated=None):
|
| 16 |
+
exe = sys.executable
|
| 17 |
+
if os.name == "nt" and exe.lower().endswith("python.exe"):
|
| 18 |
+
exe = exe[:-10] + "pythonw.exe"
|
| 19 |
+
subprocess.Popen([exe, "-m", "onw", "window", "--tab", tab] + (["--updated", updated] if updated else []))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def icon_image(state):
|
| 23 |
+
from . import logo
|
| 24 |
+
return logo.draw(64, simple=True, state=state) # the small-size logo + a status dot (grey when stopped)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def copy_text(text):
|
| 28 |
+
"""Copy to the clipboard: clip (Windows), wl-copy (Wayland) or xclip / xsel (X11). False when none is there."""
|
| 29 |
+
if os.name == "nt":
|
| 30 |
+
cmds = [(["clip"], text.encode("utf-16-le"))]
|
| 31 |
+
else:
|
| 32 |
+
cmds = [(["wl-copy"], text.encode()), (["xclip", "-selection", "clipboard"], text.encode()),
|
| 33 |
+
(["xsel", "--clipboard", "--input"], text.encode())]
|
| 34 |
+
for cmd, data in cmds:
|
| 35 |
+
try:
|
| 36 |
+
if subprocess.run(cmd, input=data, check=False, timeout=5).returncode == 0:
|
| 37 |
+
return True
|
| 38 |
+
except (OSError, subprocess.SubprocessError):
|
| 39 |
+
continue
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main(argv=None):
|
| 44 |
+
if not app.single_instance("tray"): # already in the tray (e.g. started again from the menu)
|
| 45 |
+
open_window()
|
| 46 |
+
return
|
| 47 |
+
import pystray
|
| 48 |
+
from . import manager as mgr
|
| 49 |
+
app.clear_stale_server() # a pid file from before a crash / reboot
|
| 50 |
+
manager = mgr.Manager()
|
| 51 |
+
mgr.serve(manager) # the window's backend lives here
|
| 52 |
+
from .i18n import T
|
| 53 |
+
labels = {"stopped": "停止中", "loading": "ロード中…", "running": "動作中", "failed": "ロードに失敗"}
|
| 54 |
+
state = {"s": app.server_status()}
|
| 55 |
+
|
| 56 |
+
def cfg():
|
| 57 |
+
return app.load_config()
|
| 58 |
+
|
| 59 |
+
def status_text(_=None):
|
| 60 |
+
info = app.server_info()
|
| 61 |
+
name = (info or {}).get("model") or cfg().get("model") or T("モデル未選択")
|
| 62 |
+
return f"onw AMD: {T(labels[state['s']])} — {name.split('/')[-1]}"
|
| 63 |
+
|
| 64 |
+
def start(_=None, __=None):
|
| 65 |
+
c = cfg()
|
| 66 |
+
if not app.installed(c):
|
| 67 |
+
open_window("models")
|
| 68 |
+
return
|
| 69 |
+
if c["model"] not in app.installed(c):
|
| 70 |
+
c = app.update_config(model=next(iter(app.installed(c))))
|
| 71 |
+
try:
|
| 72 |
+
app.start_server(c)
|
| 73 |
+
except Exception: # e.g. the port in use: the window says why
|
| 74 |
+
open_window("server")
|
| 75 |
+
|
| 76 |
+
def quit_(icon, __=None):
|
| 77 |
+
app.stop_server()
|
| 78 |
+
try: # manager.json points at this process: a later
|
| 79 |
+
os.remove(mgr.INFO()) # `onw window` then starts its own manager
|
| 80 |
+
except OSError:
|
| 81 |
+
pass
|
| 82 |
+
icon.stop()
|
| 83 |
+
|
| 84 |
+
def restart_after_update(icon_=None):
|
| 85 |
+
"""Stop the server, start a fresh tray on the new code, reload the model that was running."""
|
| 86 |
+
info = app.server_info()
|
| 87 |
+
with open(os.path.join(app.config_dir(), "resume.json"), "w") as f:
|
| 88 |
+
json.dump({"model": info["model"] if info else None}, f)
|
| 89 |
+
app.stop_server()
|
| 90 |
+
subprocess.Popen([sys.executable, "-m", "onw.relaunch", str(os.getpid())],
|
| 91 |
+
cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
| 92 |
+
**({"creationflags": subprocess.CREATE_NO_WINDOW | subprocess.DETACHED_PROCESS} if os.name == "nt"
|
| 93 |
+
else {"start_new_session": True}))
|
| 94 |
+
quit_(icon)
|
| 95 |
+
|
| 96 |
+
def update_found(v):
|
| 97 |
+
try:
|
| 98 |
+
icon.notify(T("「更新」を押すと自動で入れ替えて再起動します。"), T("onw v{0} が使えます", v))
|
| 99 |
+
except Exception: # not every indicator backend can notify
|
| 100 |
+
pass
|
| 101 |
+
try:
|
| 102 |
+
icon.update_menu()
|
| 103 |
+
except Exception:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
def do_update(_=None, __=None):
|
| 107 |
+
r = manager.run_update()
|
| 108 |
+
if r.get("error"):
|
| 109 |
+
open_window("server")
|
| 110 |
+
|
| 111 |
+
manager.on_updated = lambda: restart_after_update()
|
| 112 |
+
manager.on_update_found = update_found
|
| 113 |
+
running = lambda _: state["s"] == "running"
|
| 114 |
+
menu = pystray.Menu(
|
| 115 |
+
pystray.MenuItem(status_text, None, enabled=False),
|
| 116 |
+
pystray.MenuItem(lambda _: T("onw を開���(モデル・サーバー・設定)"), lambda *_: open_window(), default=True),
|
| 117 |
+
pystray.MenuItem(lambda _: T("チャットを開く"), lambda *_: webbrowser.open(f"http://localhost:{cfg()['port']}/chat"), enabled=running),
|
| 118 |
+
pystray.MenuItem(lambda _: T("検証ページを開く"), lambda *_: webbrowser.open(f"http://localhost:{cfg()['port']}/check"), enabled=running),
|
| 119 |
+
pystray.MenuItem(lambda _: T("OpenAI API のURLをコピー"),
|
| 120 |
+
lambda *_: copy_text(app.api_url(cfg())) or open_window("server")), # no clipboard tool: shown there
|
| 121 |
+
pystray.MenuItem(lambda _: T("onw を更新(v{0})", manager.upd["latest"]), do_update,
|
| 122 |
+
visible=lambda _: bool(manager.upd["latest"]) and manager.upd["state"] != "updating"),
|
| 123 |
+
pystray.MenuItem(lambda _: T("モデルをロード"), start, visible=lambda _: state["s"] in ("stopped", "failed")),
|
| 124 |
+
pystray.MenuItem(lambda _: T("アンロード(サーバー停止)"), lambda *_: app.stop_server(), visible=lambda _: state["s"] in ("loading", "running")),
|
| 125 |
+
pystray.MenuItem(lambda _: T("終了(サーバーも停止)"), quit_))
|
| 126 |
+
icon = pystray.Icon("onw-amd", icon_image(state["s"]), app.title(), menu)
|
| 127 |
+
|
| 128 |
+
def refresh():
|
| 129 |
+
last = None
|
| 130 |
+
while True:
|
| 131 |
+
state["s"] = app.server_status()
|
| 132 |
+
if state["s"] != last:
|
| 133 |
+
last = state["s"]
|
| 134 |
+
icon.icon = icon_image(last)
|
| 135 |
+
icon.title = status_text()
|
| 136 |
+
try:
|
| 137 |
+
icon.update_menu()
|
| 138 |
+
except Exception:
|
| 139 |
+
pass
|
| 140 |
+
time.sleep(2)
|
| 141 |
+
|
| 142 |
+
c = cfg()
|
| 143 |
+
resume = os.path.join(app.config_dir(), "resume.json")
|
| 144 |
+
resumed = None
|
| 145 |
+
after_update = os.path.exists(resume)
|
| 146 |
+
if after_update: # just restarted by an update: reload that model
|
| 147 |
+
try:
|
| 148 |
+
resumed = json.load(open(resume)).get("model")
|
| 149 |
+
except (OSError, ValueError):
|
| 150 |
+
pass
|
| 151 |
+
os.remove(resume)
|
| 152 |
+
if not app.installed(c):
|
| 153 |
+
open_window("models") # first run: pick a model to download
|
| 154 |
+
elif resumed and state["s"] == "stopped" and resumed in app.installed(c):
|
| 155 |
+
try:
|
| 156 |
+
app.start_server(app.update_config(model=resumed))
|
| 157 |
+
except Exception:
|
| 158 |
+
open_window("server")
|
| 159 |
+
elif c["autostart_server"] and state["s"] == "stopped":
|
| 160 |
+
start()
|
| 161 |
+
if after_update and app.installed(c): # show the new version (an open window reopens itself
|
| 162 |
+
open_window("server", updated=__version__) # too; the single-instance lock keeps just one)
|
| 163 |
+
threading.Thread(target=refresh, daemon=True).start()
|
| 164 |
+
threading.Thread(target=app.refresh_shortcut, daemon=True).start()
|
| 165 |
+
icon.run()
|
onw/update.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Updates of onw AMD itself from Hugging Face (REPO below).
|
| 2 |
+
|
| 3 |
+
latest() newest released version (from the repo's v* tags), or None when offline
|
| 4 |
+
notes(since) the CHANGELOG.md sections newer than `since`
|
| 5 |
+
can_update() only installs made by the one-line installer (%LOCALAPPDATA%\\onw-amd, ~/onw-amd, or a folder with the
|
| 6 |
+
.onw-installed marker) are updated in place; a development checkout is never touched
|
| 7 |
+
apply(tag) download that version into a staging folder first (a broken download leaves the current install as
|
| 8 |
+
it is), then replace the files, and run pip only when pyproject.toml changed
|
| 9 |
+
|
| 10 |
+
Restarting afterwards is the tray's job (onw.tray): it stops the server, starts a fresh tray through onw.relaunch and
|
| 11 |
+
reloads the model that was running.
|
| 12 |
+
"""
|
| 13 |
+
import json, os, re, shutil, subprocess, sys, time, urllib.request
|
| 14 |
+
|
| 15 |
+
from . import __version__
|
| 16 |
+
from .i18n import T
|
| 17 |
+
|
| 18 |
+
REPO = "ryugyosoft/onwAMD"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def vtuple(v):
|
| 22 |
+
return tuple(int(x) for x in re.findall(r"\d+", v or "")[:4]) or (0,)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _get(url, tries=4, timeout=30):
|
| 26 |
+
req = urllib.request.Request(url, headers={"User-Agent": f"onw-amd/{__version__}"})
|
| 27 |
+
for i in range(tries):
|
| 28 |
+
try:
|
| 29 |
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
| 30 |
+
return r.read()
|
| 31 |
+
except Exception:
|
| 32 |
+
if i == tries - 1:
|
| 33 |
+
raise
|
| 34 |
+
time.sleep(2 * (i + 1))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def latest():
|
| 38 |
+
"""(version string like "0.8.1", tag) of the newest v* tag on the hub, or None."""
|
| 39 |
+
try:
|
| 40 |
+
refs = json.loads(_get(f"https://huggingface.co/api/models/{REPO}/refs", tries=2, timeout=15))
|
| 41 |
+
except Exception:
|
| 42 |
+
return None
|
| 43 |
+
tags = [t["name"] for t in refs.get("tags", []) if re.fullmatch(r"v\d+(\.\d+)*", t.get("name", ""))]
|
| 44 |
+
if not tags:
|
| 45 |
+
return None
|
| 46 |
+
tag = max(tags, key=vtuple)
|
| 47 |
+
return tag[1:], tag
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def newer(v, than=__version__):
|
| 51 |
+
return vtuple(v) > vtuple(than)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def notes(since=__version__, tag="main", lang="ja"):
|
| 55 |
+
"""The changelog entries for versions newer than `since` (markdown), or ""."""
|
| 56 |
+
name = "CHANGELOG.md" if lang == "ja" else "CHANGELOG_en.md"
|
| 57 |
+
try:
|
| 58 |
+
text = _get(f"https://huggingface.co/{REPO}/resolve/{tag}/{name}", tries=2, timeout=15).decode("utf8")
|
| 59 |
+
except Exception:
|
| 60 |
+
return ""
|
| 61 |
+
out = []
|
| 62 |
+
for sec in re.split(r"(?m)^## ", text)[1:]:
|
| 63 |
+
m = re.match(r"v(\d+(?:\.\d+)*)", sec)
|
| 64 |
+
if m and newer(m.group(1), since):
|
| 65 |
+
out.append("## " + sec.strip())
|
| 66 |
+
return "\n\n".join(out)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def install_dir():
|
| 70 |
+
"""The folder onw runs from (the editable install), or None if it is not an installer-made install."""
|
| 71 |
+
d = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 72 |
+
home = os.path.join(os.environ.get("LOCALAPPDATA", ""), "onw-amd") if os.name == "nt" else os.path.expanduser("~/onw-amd")
|
| 73 |
+
ok = os.path.exists(os.path.join(d, ".onw-installed")) or os.path.normcase(os.path.abspath(home)) == os.path.normcase(d)
|
| 74 |
+
if not ok or os.path.isdir(os.path.join(d, ".git")) or not os.path.exists(os.path.join(d, "pyproject.toml")):
|
| 75 |
+
return None
|
| 76 |
+
return d
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def can_update():
|
| 80 |
+
return install_dir() is not None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def apply(tag, progress=lambda text: None):
|
| 84 |
+
"""Install version `tag` over the current install. Returns the new version string."""
|
| 85 |
+
d = install_dir()
|
| 86 |
+
if d is None:
|
| 87 |
+
raise RuntimeError("this onw AMD is not an installer-made install (update it with git / hf instead)")
|
| 88 |
+
info = json.loads(_get(f"https://huggingface.co/api/models/{REPO}/revision/{tag}"))
|
| 89 |
+
files = [s["rfilename"] for s in info["siblings"] if s["rfilename"] != ".gitattributes"]
|
| 90 |
+
stage = os.path.join(d, ".update")
|
| 91 |
+
shutil.rmtree(stage, ignore_errors=True)
|
| 92 |
+
|
| 93 |
+
def fetch(f):
|
| 94 |
+
data = _get(f"https://huggingface.co/{REPO}/resolve/{tag}/{f}")
|
| 95 |
+
if f.endswith((".sh", ".py", ".toml", ".txt", ".md", ".html")):
|
| 96 |
+
data = data.replace(b"\r\n", b"\n") # scripts keep Unix line endings on every platform
|
| 97 |
+
if not data and f.endswith((".py", ".sh", ".bat", ".toml")) and not f.endswith("__init__.py"):
|
| 98 |
+
raise RuntimeError(f"{f} came down empty; update cancelled")
|
| 99 |
+
out = os.path.join(stage, f)
|
| 100 |
+
os.makedirs(os.path.dirname(out), exist_ok=True)
|
| 101 |
+
with open(out, "wb") as fh:
|
| 102 |
+
fh.write(data)
|
| 103 |
+
|
| 104 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 105 |
+
with ThreadPoolExecutor(8) as ex: # 8 at a time: a slow connection costs far less than one by one
|
| 106 |
+
jobs = [ex.submit(fetch, f) for f in files]
|
| 107 |
+
for i, j in enumerate(as_completed(jobs)):
|
| 108 |
+
j.result()
|
| 109 |
+
progress(T("ダウンロード中 {0}/{1}", i + 1, len(files)))
|
| 110 |
+
old_toml = open(os.path.join(d, "pyproject.toml"), "rb").read()
|
| 111 |
+
new_toml = open(os.path.join(stage, "pyproject.toml"), "rb").read()
|
| 112 |
+
progress(T("入れ替え中"))
|
| 113 |
+
for f in files: # replace file by file (a running Python keeps its loaded code)
|
| 114 |
+
dst = os.path.join(d, f)
|
| 115 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 116 |
+
for i in range(10): # Windows: a file being read right now (the page being served)
|
| 117 |
+
try: # cannot be replaced for that moment
|
| 118 |
+
os.replace(os.path.join(stage, f), dst)
|
| 119 |
+
break
|
| 120 |
+
except PermissionError:
|
| 121 |
+
if i == 9:
|
| 122 |
+
raise
|
| 123 |
+
time.sleep(0.5)
|
| 124 |
+
# modules the new version no longer has: stale code must not be imported by accident
|
| 125 |
+
keep = {os.path.normcase(os.path.join(d, f)) for f in files}
|
| 126 |
+
for root, dirs, names in os.walk(os.path.join(d, "onw")):
|
| 127 |
+
dirs[:] = [x for x in dirs if x != "__pycache__"]
|
| 128 |
+
for n in names:
|
| 129 |
+
p = os.path.join(root, n)
|
| 130 |
+
if n.endswith(".py") and os.path.normcase(p) not in keep:
|
| 131 |
+
try:
|
| 132 |
+
os.remove(p)
|
| 133 |
+
except OSError:
|
| 134 |
+
pass
|
| 135 |
+
shutil.rmtree(stage, ignore_errors=True)
|
| 136 |
+
open(os.path.join(d, ".onw-installed"), "w").write(tag + "\n")
|
| 137 |
+
if new_toml != old_toml: # new or changed dependencies
|
| 138 |
+
progress(T("パッケージを更新中(数分かかることがあります)"))
|
| 139 |
+
kw = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
|
| 140 |
+
r = subprocess.run([sys.executable, "-m", "pip", "install", "-e", ".[tray]"],
|
| 141 |
+
cwd=d, capture_output=True, text=True, encoding="utf8", errors="replace", **kw)
|
| 142 |
+
if r.returncode != 0:
|
| 143 |
+
raise RuntimeError("pip failed: " + " ".join(r.stdout.split()[-40:]))
|
| 144 |
+
return tag.lstrip("v")
|
onw/web/check.html
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="ja">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%2270 90 846 846%22%3E%3Crect x=%22332%22 y=%22256%22 width=%22512%22 height=%22511%22 rx=%2280%22 fill=%22%231868f0%22/%3E%3Cline x1=%22181%22 y1=%22360%22 x2=%22208%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22181%22 y1=%22664%22 x2=%22212%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22212%22 x2=%22436%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22815%22 x2=%22436%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22212%22 x2=%22512%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22815%22 x2=%22512%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22212%22 x2=%22588%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22815%22 x2=%22588%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22212%22 x2=%22664%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22815%22 x2=%22664%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22212%22 x2=%22740%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22815%22 x2=%22740%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22360%22 x2=%22800%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22436%22 x2=%22800%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22512%22 x2=%22800%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22588%22 x2=%22800%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22664%22 x2=%22800%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22268%22 y1=%22360%22 x2=%22380%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22124%22 y1=%22436%22 x2=%22380%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22209%22 y1=%22512%22 x2=%22380%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%2295%22 y1=%22588%22 x2=%22380%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22275%22 y1=%22664%22 x2=%22380%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%22120%22 ry=%22117%22 fill=%22%23fff%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%2257%22 ry=%2267%22 fill=%22%231868f0%22/%3E%3C/svg%3E">
|
| 7 |
+
<title>onw AMD 検証ページ</title>
|
| 8 |
+
<script>/*i18n*/</script>
|
| 9 |
+
<style>
|
| 10 |
+
:root { --bg: #f6f7f9; --fg: #1d2330; --muted: #5d6675; --card: #fff; --line: #dfe3ea; --ok: #1f8a4c; --bad: #c0392b; --accent: #2f6fde; }
|
| 11 |
+
@media (prefers-color-scheme: dark) { :root { --bg: #14171d; --fg: #e5e9f0; --muted: #9aa3b2; --card: #1c2029; --line: #2b313d; --ok: #3fbf74; --bad: #e0685a; --accent: #6b9cf0; } }
|
| 12 |
+
* { box-sizing: border-box; }
|
| 13 |
+
body { margin: 0; font: 15px/1.6 system-ui, "Segoe UI", "Hiragino Sans", "Noto Sans JP", sans-serif; background: var(--bg); color: var(--fg); }
|
| 14 |
+
main { max-width: 920px; margin: 0 auto; padding: 24px 16px 48px; }
|
| 15 |
+
h1 { font-size: 22px; margin: 0 0 4px; }
|
| 16 |
+
.sub { color: var(--muted); margin: 0 0 18px; }
|
| 17 |
+
.card { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; margin-bottom: 14px; }
|
| 18 |
+
code { background: rgba(127,127,127,.15); padding: 1px 5px; border-radius: 4px; }
|
| 19 |
+
button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid var(--accent); background: var(--accent); color: #fff; cursor: pointer; }
|
| 20 |
+
button:disabled { opacity: .5; cursor: default; }
|
| 21 |
+
table { width: 100%; border-collapse: collapse; }
|
| 22 |
+
th, td { text-align: left; padding: 7px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
|
| 23 |
+
th { color: var(--muted); font-weight: 600; font-size: 13px; }
|
| 24 |
+
td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
| 25 |
+
.ok { color: var(--ok); } .bad { color: var(--bad); }
|
| 26 |
+
.ans { color: var(--muted); font-size: 13px; max-width: 420px; }
|
| 27 |
+
#info td:first-child { color: var(--muted); width: 180px; }
|
| 28 |
+
</style>
|
| 29 |
+
</head>
|
| 30 |
+
<body>
|
| 31 |
+
<main>
|
| 32 |
+
<h1>onw AMD 検証ページ</h1>
|
| 33 |
+
<p class="sub">このサーバー(OpenAI互換API)に実際のリクエストを送って、動作と速度を確かめます。</p>
|
| 34 |
+
|
| 35 |
+
<div class="card">
|
| 36 |
+
<table id="info"><tbody><tr><td>読み込み中…</td><td></td></tr></tbody></table>
|
| 37 |
+
</div>
|
| 38 |
+
|
| 39 |
+
<div class="card">
|
| 40 |
+
<button id="run">検証を実行</button>
|
| 41 |
+
<span id="status" class="sub" style="margin-left:10px"></span>
|
| 42 |
+
<table style="margin-top:12px">
|
| 43 |
+
<thead><tr><th>項目</th><th>結果</th><th>プロンプト</th><th>応答開始</th><th>生成速度</th><th>回答</th></tr></thead>
|
| 44 |
+
<tbody id="rows"></tbody>
|
| 45 |
+
</table>
|
| 46 |
+
</div>
|
| 47 |
+
|
| 48 |
+
<div class="card sub" data-t>他のアプリからは <code id="base"></code> を OpenAI の base URL に、モデル名は <code id="mid"></code> を指定してください(APIキー設定時は <code>Authorization: Bearer キー</code>)。</div>
|
| 49 |
+
</main>
|
| 50 |
+
<script>
|
| 51 |
+
translate(document.body);
|
| 52 |
+
const $ = id => document.getElementById(id);
|
| 53 |
+
let INFO = {}, KEY = new URLSearchParams(location.search).get("key") || "";
|
| 54 |
+
const TEXT = T("東京は日本の首都であり、政治・経済・文化の中心地である。江戸時代には徳川幕府が置かれ、1868年の明治維新で東京と改称された。現在は約1400万人が暮らす世界有数の大都市で、多くの企業や大学が集まっている。");
|
| 55 |
+
|
| 56 |
+
// streamed, so the first-token time and the generation speed are measured here (the same for every NPU engine)
|
| 57 |
+
async function api(messages, max_tokens) {
|
| 58 |
+
const t0 = performance.now();
|
| 59 |
+
const r = await fetch("/v1/chat/completions", {
|
| 60 |
+
method: "POST",
|
| 61 |
+
headers: Object.assign({ "Content-Type": "application/json" }, KEY ? { Authorization: "Bearer " + KEY } : {}),
|
| 62 |
+
body: JSON.stringify({ model: INFO.model, messages, max_tokens, temperature: 0, stream: true, stream_options: { include_usage: true } })
|
| 63 |
+
});
|
| 64 |
+
if (!r.ok) throw new Error((await r.text()).slice(0, 200));
|
| 65 |
+
const reader = r.body.getReader(), dec = new TextDecoder();
|
| 66 |
+
let buf = "", text = "", usage = null, chunks = 0, first = 0, last = 0;
|
| 67 |
+
for (;;) {
|
| 68 |
+
const { value, done } = await reader.read(); if (done) break;
|
| 69 |
+
buf += dec.decode(value, { stream: true });
|
| 70 |
+
let i;
|
| 71 |
+
while ((i = buf.indexOf("\n")) >= 0) {
|
| 72 |
+
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
|
| 73 |
+
if (!line.startsWith("data:")) continue;
|
| 74 |
+
const data = line.slice(5).trim(); if (data === "[DONE]") continue;
|
| 75 |
+
const j = JSON.parse(data);
|
| 76 |
+
if (j.error) throw new Error(j.error.message);
|
| 77 |
+
const d = j.choices?.[0]?.delta?.content || j.choices?.[0]?.delta?.reasoning_content;
|
| 78 |
+
if (d) { if (!first) first = performance.now(); last = performance.now(); chunks++; text += j.choices[0].delta.content || ""; }
|
| 79 |
+
if (j.usage) usage = j.usage;
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
const n = usage ? usage.completion_tokens : chunks;
|
| 83 |
+
return { choices: [{ message: { content: text } }], usage: usage || { prompt_tokens: "—", completion_tokens: chunks },
|
| 84 |
+
ttft: ((first || performance.now()) - t0) / 1000, tps: n > 1 && last > first ? (n - 1) / ((last - first) / 1000) : 0 };
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
function row(name, j, err) {
|
| 88 |
+
const tr = document.createElement("tr");
|
| 89 |
+
if (err) {
|
| 90 |
+
tr.innerHTML = `<td>${name}</td><td class="bad">${T("失敗")}</td><td colspan="4" class="ans">${err}</td>`;
|
| 91 |
+
} else {
|
| 92 |
+
const u = j.usage || {};
|
| 93 |
+
const cached = u.prompt_tokens_details && u.prompt_tokens_details.cached_tokens ? T("(再利用 {0})", u.prompt_tokens_details.cached_tokens) : "";
|
| 94 |
+
const ans = (j.choices[0].message.content || "").replace(/[&<>]/g, c => ({ "&": "&", "<": "<", ">": ">" }[c]));
|
| 95 |
+
tr.innerHTML = `<td>${name}</td><td class="ok">OK</td><td class="num">${u.prompt_tokens}${cached}</td>` +
|
| 96 |
+
`<td class="num">${T("{0}秒", j.ttft.toFixed(2))}</td>` +
|
| 97 |
+
`<td class="num">${j.tps.toFixed(1)} tok/s</td><td class="ans">${ans}</td>`;
|
| 98 |
+
}
|
| 99 |
+
$("rows").appendChild(tr);
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
function testImage() { // drawn here, so no image file is needed
|
| 103 |
+
const c = document.createElement("canvas"); c.width = c.height = 512;
|
| 104 |
+
const g = c.getContext("2d");
|
| 105 |
+
g.fillStyle = "#ffffff"; g.fillRect(0, 0, 512, 512);
|
| 106 |
+
g.fillStyle = "#e53935"; g.beginPath(); g.arc(150, 170, 90, 0, Math.PI * 2); g.fill();
|
| 107 |
+
g.fillStyle = "#1e88e5"; g.fillRect(290, 90, 160, 160);
|
| 108 |
+
g.fillStyle = "#111111"; g.font = "bold 96px sans-serif"; g.fillText("NPU", 150, 430);
|
| 109 |
+
return c.toDataURL("image/png");
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
async function run() {
|
| 113 |
+
$("run").disabled = true; $("rows").innerHTML = "";
|
| 114 |
+
const steps = [
|
| 115 |
+
[T("テキスト生成"), () => api([{ role: "user", content: T("日本の四季について、それぞれ一文ずつ説明してください。") }], 160)],
|
| 116 |
+
[T("要約"), () => api([{ role: "user", content: T("次の文章を、元の表現をなるべく使って2文に要約してください。") + "\n\n" + TEXT }], 120)],
|
| 117 |
+
];
|
| 118 |
+
const t1 = [{ role: "user", content: T("日本の首都はどこですか?一文で。") }];
|
| 119 |
+
steps.push([T("2ターン会話: 1ターン目"), async () => { const j = await api(t1, 60); t1.push({ role: "assistant", content: j.choices[0].message.content }); return j; }]);
|
| 120 |
+
steps.push([T("2ターン会話: 2ターン目"), () => api(t1.concat([{ role: "user", content: T("その都市の人口は?一文で。") }]), 60)]);
|
| 121 |
+
if (INFO.vision) steps.push([T("画像入力"), () => api([{ role: "user", content: [
|
| 122 |
+
{ type: "image_url", image_url: { url: testImage() } },
|
| 123 |
+
{ type: "text", text: T("この画像に描かれている図形と文字を、色も含めて一文で答えてください。") }] }], 80)]);
|
| 124 |
+
for (const [name, f] of steps) {
|
| 125 |
+
$("status").textContent = name + " …";
|
| 126 |
+
try { row(name, await f()); } catch (e) { row(name, null, e.message); }
|
| 127 |
+
}
|
| 128 |
+
$("status").textContent = T("完了"); $("run").disabled = false;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
fetch("/api/info").then(r => r.json()).then(i => {
|
| 132 |
+
INFO = i;
|
| 133 |
+
const rows = [[T("モデル名"), i.model], [T("デバイス"), i.npu || "NPU"],
|
| 134 |
+
[T("NPU エンジン"), (i.engine_name || "") + " " + (i.engine_version || "")],
|
| 135 |
+
[T("コンテキスト長"), T("{0} トークン", i.context || i.max_context)], [T("画像入力"), i.vision ? T("対応") : T("なし")],
|
| 136 |
+
[T("思考モード"), i.think ? T("対応") : T("なし")]];
|
| 137 |
+
$("info").innerHTML = rows.map(([k, v]) => `<tr><td>${k}</td><td>${v}</td></tr>`).join("");
|
| 138 |
+
$("base").textContent = location.origin + "/v1"; $("mid").textContent = i.model;
|
| 139 |
+
}).catch(() => { $("info").innerHTML = `<tr><td class='bad'>${T("サーバーに接続できません")}</td></tr>`; });
|
| 140 |
+
$("run").onclick = run;
|
| 141 |
+
</script>
|
| 142 |
+
</body>
|
| 143 |
+
</html>
|
onw/web/i18n.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// UI strings (see onw/i18n.py). The pages are written in Japanese: T() looks a string up in I18N and fills {0} {1} ...;
|
| 2 |
+
// translate() swaps the page's own text, titles and placeholders ([data-t]: the element's whole HTML is one entry).
|
| 3 |
+
function T(s, ...a) {
|
| 4 |
+
const r = I18N[s] ?? s;
|
| 5 |
+
return a.length ? r.replace(/\{(\d+)\}/g, (_, i) => a[i]) : r;
|
| 6 |
+
}
|
| 7 |
+
function translate(root) {
|
| 8 |
+
if (LANG === "ja") return;
|
| 9 |
+
const norm = s => s.replace(/\s+/g, " ").trim();
|
| 10 |
+
root.querySelectorAll("[data-t]").forEach(e => { const k = norm(e.innerHTML); if (I18N[k]) e.innerHTML = I18N[k]; });
|
| 11 |
+
const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
| 12 |
+
for (let n; (n = w.nextNode());) {
|
| 13 |
+
if (n.parentElement.closest("script, style, [data-t]")) continue;
|
| 14 |
+
const k = norm(n.nodeValue);
|
| 15 |
+
if (k && I18N[k]) n.nodeValue = n.nodeValue.replace(n.nodeValue.trim(), I18N[k]);
|
| 16 |
+
}
|
| 17 |
+
root.querySelectorAll("[title], [placeholder]").forEach(e => {
|
| 18 |
+
for (const a of ["title", "placeholder"]) { const v = e.getAttribute(a); if (v && I18N[v]) e.setAttribute(a, I18N[v]); }
|
| 19 |
+
});
|
| 20 |
+
if (I18N[document.title]) document.title = I18N[document.title];
|
| 21 |
+
}
|
onw/web/icon.ico
ADDED
|
|
onw/web/icon.png
ADDED
|
|
onw/web/icon.svg
ADDED
|
|
onw/web/index.html
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="ja">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%2270 90 846 846%22%3E%3Crect x=%22332%22 y=%22256%22 width=%22512%22 height=%22511%22 rx=%2280%22 fill=%22%231868f0%22/%3E%3Cline x1=%22181%22 y1=%22360%22 x2=%22208%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22181%22 y1=%22664%22 x2=%22212%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22212%22 x2=%22436%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22815%22 x2=%22436%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22212%22 x2=%22512%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22815%22 x2=%22512%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22212%22 x2=%22588%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22815%22 x2=%22588%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22212%22 x2=%22664%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22815%22 x2=%22664%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22212%22 x2=%22740%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22815%22 x2=%22740%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22360%22 x2=%22800%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22436%22 x2=%22800%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22512%22 x2=%22800%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22588%22 x2=%22800%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22664%22 x2=%22800%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22268%22 y1=%22360%22 x2=%22380%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22124%22 y1=%22436%22 x2=%22380%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22209%22 y1=%22512%22 x2=%22380%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%2295%22 y1=%22588%22 x2=%22380%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22275%22 y1=%22664%22 x2=%22380%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%22120%22 ry=%22117%22 fill=%22%23fff%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%2257%22 ry=%2267%22 fill=%22%231868f0%22/%3E%3C/svg%3E">
|
| 7 |
+
<title>onw AMD chat</title>
|
| 8 |
+
<script>/*i18n*/</script>
|
| 9 |
+
<style>
|
| 10 |
+
:root {
|
| 11 |
+
--bg: #f7f7f5; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --border: #e2e2dc;
|
| 12 |
+
--accent: #2f6fdb; --accent-text: #ffffff; --user: #e8f0fd; --code: #f0f0ec; --danger: #c43d3d;
|
| 13 |
+
}
|
| 14 |
+
@media (prefers-color-scheme: dark) {
|
| 15 |
+
:root {
|
| 16 |
+
--bg: #151514; --panel: #1f1f1d; --text: #ecece8; --muted: #9a9a93; --border: #33332f;
|
| 17 |
+
--accent: #6b9bff; --accent-text: #0d0d0c; --user: #22304a; --code: #2a2a27; --danger: #ff7a7a;
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
* { box-sizing: border-box; }
|
| 21 |
+
html, body { height: 100%; margin: 0; }
|
| 22 |
+
body { background: var(--bg); color: var(--text); font: 15px/1.6 system-ui, -apple-system, "Segoe UI", "Hiragino Sans", "Noto Sans JP", sans-serif; display: flex; flex-direction: column; }
|
| 23 |
+
header { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--panel); }
|
| 24 |
+
header h1 { font-size: 16px; margin: 0; font-weight: 600; }
|
| 25 |
+
.badge { font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--border); color: var(--muted); }
|
| 26 |
+
.badge.ok { color: var(--accent); border-color: var(--accent); }
|
| 27 |
+
header .spacer { flex: 1; }
|
| 28 |
+
button { font: inherit; cursor: pointer; border-radius: 8px; border: 1px solid var(--border); background: var(--panel); color: var(--text); padding: 6px 12px; }
|
| 29 |
+
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
| 30 |
+
button:disabled { opacity: .5; cursor: default; }
|
| 31 |
+
#chat { flex: 1; overflow-y: auto; padding: 16px; }
|
| 32 |
+
.wrap { max-width: 820px; margin: 0 auto; }
|
| 33 |
+
.msg { margin: 0 0 14px; display: flex; }
|
| 34 |
+
.msg.user { justify-content: flex-end; }
|
| 35 |
+
.bubble { max-width: 90%; padding: 10px 14px; border-radius: 14px; background: var(--panel); border: 1px solid var(--border); overflow-wrap: anywhere; }
|
| 36 |
+
.msg.user .bubble { background: var(--user); border-color: transparent; }
|
| 37 |
+
.bubble img { max-width: 240px; max-height: 240px; border-radius: 8px; display: block; margin-bottom: 6px; }
|
| 38 |
+
.bubble pre { background: var(--code); padding: 10px; border-radius: 8px; overflow-x: auto; }
|
| 39 |
+
.bubble code { background: var(--code); padding: 1px 4px; border-radius: 4px; font-size: 13px; }
|
| 40 |
+
.bubble pre code { padding: 0; background: none; }
|
| 41 |
+
.bubble p { margin: 0 0 8px; } .bubble p:last-child { margin-bottom: 0; }
|
| 42 |
+
.stats { font-size: 12px; color: var(--muted); margin-top: 4px; }
|
| 43 |
+
.thought { font-size: 13px; color: var(--muted); margin-bottom: 8px; }
|
| 44 |
+
.thought summary { cursor: pointer; }
|
| 45 |
+
.thought div { white-space: pre-wrap; border-left: 2px solid var(--border); padding-left: 8px; margin-top: 4px; }
|
| 46 |
+
.empty { text-align: center; color: var(--muted); margin-top: 18vh; }
|
| 47 |
+
footer { border-top: 1px solid var(--border); background: var(--panel); padding: 10px 16px 14px; }
|
| 48 |
+
#thumbs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
|
| 49 |
+
#thumbs .t { position: relative; }
|
| 50 |
+
#thumbs img { width: 64px; height: 64px; object-fit: cover; border-radius: 8px; border: 1px solid var(--border); }
|
| 51 |
+
#thumbs .x { position: absolute; top: -6px; right: -6px; width: 20px; height: 20px; padding: 0; border-radius: 50%; font-size: 12px; line-height: 18px; }
|
| 52 |
+
.row { display: flex; gap: 8px; align-items: flex-end; }
|
| 53 |
+
textarea { flex: 1; resize: none; font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 10px; padding: 9px 12px; min-height: 44px; max-height: 200px; }
|
| 54 |
+
textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
| 55 |
+
.opts { display: flex; gap: 16px; flex-wrap: wrap; font-size: 13px; color: var(--muted); margin-top: 8px; }
|
| 56 |
+
.opts label { display: flex; align-items: center; gap: 6px; }
|
| 57 |
+
.opts input[type=number] { width: 70px; font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; }
|
| 58 |
+
.err { color: var(--danger); }
|
| 59 |
+
body.drag footer { outline: 2px dashed var(--accent); outline-offset: -6px; }
|
| 60 |
+
@media (max-width: 600px) { header h1 { font-size: 14px; } .bubble { max-width: 100%; } }
|
| 61 |
+
</style>
|
| 62 |
+
</head>
|
| 63 |
+
<body>
|
| 64 |
+
<header>
|
| 65 |
+
<h1 id="title">NPU</h1>
|
| 66 |
+
<span id="dev" class="badge">接続中…</span>
|
| 67 |
+
<span class="spacer"></span>
|
| 68 |
+
<button id="clear" title="会話をクリア">新しい会話</button>
|
| 69 |
+
</header>
|
| 70 |
+
<main id="chat"><div class="wrap" id="log"><div class="empty" id="empty">メッセージを入力するか、画像を添付・貼り付け・ドロップしてください。</div></div></main>
|
| 71 |
+
<footer><div class="wrap">
|
| 72 |
+
<div id="thumbs"></div>
|
| 73 |
+
<div class="row">
|
| 74 |
+
<button id="attach" title="画像を添付">📎</button>
|
| 75 |
+
<input id="file" type="file" accept="image/*" multiple hidden>
|
| 76 |
+
<textarea id="input" rows="1" placeholder="メッセージ(Enterで送信、Shift+Enterで改行)"></textarea>
|
| 77 |
+
<button id="send" class="primary">送信</button>
|
| 78 |
+
</div>
|
| 79 |
+
<div class="opts">
|
| 80 |
+
<label>温度 <input id="temp" type="number" min="0" max="2" step="0.1" value="0"></label>
|
| 81 |
+
<label>最大トークン <input id="maxtok" type="number" min="16" max="32768" step="16" value="512"></label>
|
| 82 |
+
<label>Top P <input id="topp" type="number" min="0.05" max="1" step="0.05" value="1"></label>
|
| 83 |
+
<label>Top K <input id="topk" type="number" min="0" max="1000" step="1" value="0" title="0 = 無効"></label>
|
| 84 |
+
<label>繰り返し抑制 <input id="rep" type="number" min="1" max="2" step="0.05" value="1" title="1 = 無効"></label>
|
| 85 |
+
<label id="thinkopt"><input id="think" type="checkbox"> 思考モード</label><span id="note">文脈は約1000トークン</span>
|
| 86 |
+
</div>
|
| 87 |
+
</div></footer>
|
| 88 |
+
<script>
|
| 89 |
+
translate(document.body);
|
| 90 |
+
const $ = id => document.getElementById(id);
|
| 91 |
+
const history = []; // OpenAI-format messages
|
| 92 |
+
let pending = []; // data: URLs of attached images
|
| 93 |
+
let controller = null;
|
| 94 |
+
|
| 95 |
+
fetch("/api/info").then(r => r.json()).then(i => {
|
| 96 |
+
$("dev").textContent = i.ready ? T("すべてNPUで実行中") + (i.engine_name ? " ・ " + i.engine_name : "") : T("NPU でロード中…");
|
| 97 |
+
$("dev").classList.toggle("ok", !!i.ready);
|
| 98 |
+
if (i.title) { $("title").textContent = i.title; document.title = i.title + " on AMD NPU"; }
|
| 99 |
+
if (i.vision === false) { $("attach").style.display = "none"; $("empty").textContent = T("メッセージを入力してください。"); }
|
| 100 |
+
if (i.think === false) $("thinkopt").style.display = "none";
|
| 101 |
+
if (i.context) $("note").textContent = T("文脈は約{0}トークン", i.context);
|
| 102 |
+
}).catch(() => { $("dev").textContent = T("サーバーに接続できません"); });
|
| 103 |
+
|
| 104 |
+
function escapeHtml(s) { return s.replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); }
|
| 105 |
+
function render(md) { // small, safe markdown: code blocks, inline code, bold, paragraphs
|
| 106 |
+
const parts = md.split(/```/);
|
| 107 |
+
return parts.map((p, i) => {
|
| 108 |
+
if (i % 2) return "<pre><code>" + escapeHtml(p.replace(/^[\w+-]*\n/, "")) + "</code></pre>";
|
| 109 |
+
return escapeHtml(p).replace(/`([^`\n]+)`/g, "<code>$1</code>").replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
|
| 110 |
+
.split(/\n{2,}/).map(x => x.trim() ? "<p>" + x.replace(/\n/g, "<br>") + "</p>" : "").join("");
|
| 111 |
+
}).join("");
|
| 112 |
+
}
|
| 113 |
+
function addMsg(role, text, images) {
|
| 114 |
+
$("empty")?.remove();
|
| 115 |
+
const m = document.createElement("div"); m.className = "msg " + role;
|
| 116 |
+
const b = document.createElement("div"); b.className = "bubble";
|
| 117 |
+
(images || []).forEach(src => { const im = new Image(); im.src = src; b.appendChild(im); });
|
| 118 |
+
const t = document.createElement("div"); t.innerHTML = role === "user" ? render(text) : text; b.appendChild(t);
|
| 119 |
+
m.appendChild(b); $("log").appendChild(m); $("chat").scrollTop = $("chat").scrollHeight;
|
| 120 |
+
return { bubble: b, body: t };
|
| 121 |
+
}
|
| 122 |
+
function showThumbs() {
|
| 123 |
+
$("thumbs").innerHTML = "";
|
| 124 |
+
pending.forEach((src, i) => {
|
| 125 |
+
const d = document.createElement("div"); d.className = "t";
|
| 126 |
+
d.innerHTML = `<img src="${src}"><button class="x" title="${T("削除")}">×</button>`;
|
| 127 |
+
d.querySelector("button").onclick = () => { pending.splice(i, 1); showThumbs(); };
|
| 128 |
+
$("thumbs").appendChild(d);
|
| 129 |
+
});
|
| 130 |
+
}
|
| 131 |
+
function addFiles(files) {
|
| 132 |
+
[...files].filter(f => f.type.startsWith("image/")).forEach(f => {
|
| 133 |
+
const r = new FileReader(); r.onload = () => { pending.push(r.result); showThumbs(); }; r.readAsDataURL(f);
|
| 134 |
+
});
|
| 135 |
+
}
|
| 136 |
+
$("attach").onclick = () => $("file").click();
|
| 137 |
+
$("file").onchange = e => { addFiles(e.target.files); e.target.value = ""; };
|
| 138 |
+
document.addEventListener("paste", e => addFiles(e.clipboardData.files));
|
| 139 |
+
document.addEventListener("dragover", e => { e.preventDefault(); document.body.classList.add("drag"); });
|
| 140 |
+
document.addEventListener("dragleave", () => document.body.classList.remove("drag"));
|
| 141 |
+
document.addEventListener("drop", e => { e.preventDefault(); document.body.classList.remove("drag"); addFiles(e.dataTransfer.files); });
|
| 142 |
+
$("input").addEventListener("input", e => { e.target.style.height = "auto"; e.target.style.height = e.target.scrollHeight + "px"; });
|
| 143 |
+
$("input").addEventListener("keydown", e => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); } });
|
| 144 |
+
$("clear").onclick = () => { if (controller) controller.abort(); history.length = 0; pending = []; showThumbs(); $("log").innerHTML = `<div class="empty" id="empty">${T("新しい会話です。")}</div>`; };
|
| 145 |
+
$("send").onclick = () => controller ? controller.abort() : send();
|
| 146 |
+
|
| 147 |
+
async function send() {
|
| 148 |
+
const text = $("input").value.trim();
|
| 149 |
+
if (!text && !pending.length) return;
|
| 150 |
+
const content = [...pending.map(u => ({ type: "image_url", image_url: { url: u } })), { type: "text", text: text || T("この画像を説明してください。") }];
|
| 151 |
+
addMsg("user", text || T("(画像)"), pending);
|
| 152 |
+
history.push({ role: "user", content });
|
| 153 |
+
$("input").value = ""; $("input").style.height = "auto"; pending = []; showThumbs();
|
| 154 |
+
const out = addMsg("assistant", "…");
|
| 155 |
+
let acc = "", usage = null, chunks = 0; const t0 = performance.now(); let first = 0;
|
| 156 |
+
controller = new AbortController(); $("send").textContent = T("停止");
|
| 157 |
+
try {
|
| 158 |
+
const r = await fetch("/v1/chat/completions", {
|
| 159 |
+
method: "POST", headers: { "Content-Type": "application/json" }, signal: controller.signal,
|
| 160 |
+
body: JSON.stringify({ model: "npu", messages: history, stream: true, stream_options: { include_usage: true },
|
| 161 |
+
temperature: +$("temp").value, max_tokens: +$("maxtok").value,
|
| 162 |
+
top_p: +$("topp").value, top_k: +$("topk").value, repetition_penalty: +$("rep").value,
|
| 163 |
+
chat_template_kwargs: { enable_thinking: $("think").checked } })
|
| 164 |
+
});
|
| 165 |
+
if (!r.ok) { const j = await r.json().catch(() => ({})); throw new Error(j.error?.message || j.detail || r.statusText); }
|
| 166 |
+
let think = "", tbox = null; // thinking (reasoning_content): a collapsible block above the answer
|
| 167 |
+
const reader = r.body.getReader(), dec = new TextDecoder(); let buf = "";
|
| 168 |
+
for (;;) {
|
| 169 |
+
const { value, done } = await reader.read(); if (done) break;
|
| 170 |
+
buf += dec.decode(value, { stream: true });
|
| 171 |
+
let i;
|
| 172 |
+
while ((i = buf.indexOf("\n\n")) >= 0) {
|
| 173 |
+
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 2);
|
| 174 |
+
if (!line.startsWith("data:")) continue;
|
| 175 |
+
const data = line.slice(5).trim(); if (data === "[DONE]") continue;
|
| 176 |
+
const j = JSON.parse(data);
|
| 177 |
+
if (j.error) throw new Error(j.error.message);
|
| 178 |
+
const rc = j.choices?.[0]?.delta?.reasoning_content;
|
| 179 |
+
if (rc) {
|
| 180 |
+
if (!first) first = performance.now();
|
| 181 |
+
if (!tbox) {
|
| 182 |
+
tbox = document.createElement("details"); tbox.className = "thought"; tbox.open = true;
|
| 183 |
+
tbox.innerHTML = `<summary>${escapeHtml(T("思考"))}</summary><div></div>`;
|
| 184 |
+
out.bubble.insertBefore(tbox, out.body); if (!acc) out.body.innerHTML = "";
|
| 185 |
+
}
|
| 186 |
+
think += rc; tbox.lastChild.textContent = think; $("chat").scrollTop = $("chat").scrollHeight;
|
| 187 |
+
}
|
| 188 |
+
const d = j.choices?.[0]?.delta?.content;
|
| 189 |
+
if (d) {
|
| 190 |
+
if (!first) first = performance.now();
|
| 191 |
+
if (tbox && !acc) tbox.open = false; // the answer starts: fold the thinking away
|
| 192 |
+
acc += d; chunks++; out.body.innerHTML = render(acc); $("chat").scrollTop = $("chat").scrollHeight;
|
| 193 |
+
}
|
| 194 |
+
if (j.usage) usage = j.usage;
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
history.push({ role: "assistant", content: acc });
|
| 198 |
+
if (!usage && chunks) usage = { completion_tokens: chunks, total_tokens: chunks }; // the engine sent no usage: count the chunks
|
| 199 |
+
if (usage) {
|
| 200 |
+
const s = document.createElement("div"); s.className = "stats";
|
| 201 |
+
const gen = (performance.now() - first) / 1000;
|
| 202 |
+
s.textContent = T("応答開始 {0}秒 · {1}トークン · {2} tok/s · 文脈 {3}{4}", ((first - t0) / 1000).toFixed(1), usage.completion_tokens,
|
| 203 |
+
(usage.completion_tokens / Math.max(gen, 1e-3)).toFixed(1), usage.total_tokens,
|
| 204 |
+
usage.prompt_tokens_details?.cached_tokens ? T("(再利用 {0})", usage.prompt_tokens_details.cached_tokens) : "");
|
| 205 |
+
out.bubble.appendChild(s);
|
| 206 |
+
}
|
| 207 |
+
} catch (e) {
|
| 208 |
+
if (e.name === "AbortError") { history.push({ role: "assistant", content: acc }); out.body.innerHTML = render(acc || T("(停止しました)")); }
|
| 209 |
+
else { out.body.innerHTML = `<span class="err">${escapeHtml(T("エラー: {0}", e.message))}</span>`; history.pop(); }
|
| 210 |
+
} finally { controller = null; $("send").textContent = T("送信"); $("input").focus(); }
|
| 211 |
+
}
|
| 212 |
+
</script>
|
| 213 |
+
</body>
|
| 214 |
+
</html>
|
onw/web/manage.html
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="ja">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%2270 90 846 846%22%3E%3Crect x=%22332%22 y=%22256%22 width=%22512%22 height=%22511%22 rx=%2280%22 fill=%22%231868f0%22/%3E%3Cline x1=%22181%22 y1=%22360%22 x2=%22208%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22181%22 y1=%22664%22 x2=%22212%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22212%22 x2=%22436%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22436%22 y1=%22815%22 x2=%22436%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22212%22 x2=%22512%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22512%22 y1=%22815%22 x2=%22512%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22212%22 x2=%22588%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22588%22 y1=%22815%22 x2=%22588%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22212%22 x2=%22664%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22664%22 y1=%22815%22 x2=%22664%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22212%22 x2=%22740%22 y2=%22300%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22740%22 y1=%22815%22 x2=%22740%22 y2=%22720%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22360%22 x2=%22800%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22436%22 x2=%22800%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22512%22 x2=%22800%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22588%22 x2=%22800%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22891%22 y1=%22664%22 x2=%22800%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22268%22 y1=%22360%22 x2=%22380%22 y2=%22360%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22124%22 y1=%22436%22 x2=%22380%22 y2=%22436%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22209%22 y1=%22512%22 x2=%22380%22 y2=%22512%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%2295%22 y1=%22588%22 x2=%22380%22 y2=%22588%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cline x1=%22275%22 y1=%22664%22 x2=%22380%22 y2=%22664%22 stroke=%22%231868f0%22 stroke-width=%2238%22 stroke-linecap=%22round%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%22120%22 ry=%22117%22 fill=%22%23fff%22/%3E%3Cellipse cx=%22588%22 cy=%22512%22 rx=%2257%22 ry=%2267%22 fill=%22%231868f0%22/%3E%3C/svg%3E">
|
| 7 |
+
<title>onw AMD</title>
|
| 8 |
+
<script>/*i18n*/</script>
|
| 9 |
+
<style>
|
| 10 |
+
:root {
|
| 11 |
+
--bg: #f4f5f7; --panel: #ffffff; --panel2: #eef0f3; --text: #1c1d21; --muted: #6a6d76; --border: #dfe2e7;
|
| 12 |
+
--accent: #2f6fdb; --accent-soft: #e6eefc; --accent-text: #ffffff; --ok: #1f8a4c; --ok-soft: #e3f4ea;
|
| 13 |
+
--warn: #b7791f; --warn-soft: #fbf0d9; --danger: #c43d3d; --danger-soft: #fbe5e5;
|
| 14 |
+
}
|
| 15 |
+
@media (prefers-color-scheme: dark) {
|
| 16 |
+
:root {
|
| 17 |
+
--bg: #141518; --panel: #1d1f24; --panel2: #262930; --text: #ebecef; --muted: #979aa3; --border: #31343b;
|
| 18 |
+
--accent: #6b9bff; --accent-soft: #22304a; --accent-text: #0d0f14; --ok: #4cc27a; --ok-soft: #173224;
|
| 19 |
+
--warn: #e0a83a; --warn-soft: #3a2e14; --danger: #ff7a7a; --danger-soft: #3d1f1f;
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
* { box-sizing: border-box; }
|
| 23 |
+
html, body { height: 100%; margin: 0; }
|
| 24 |
+
body { background: var(--bg); color: var(--text); font: 12.5px/1.45 system-ui, -apple-system, "Segoe UI", "Hiragino Sans", "Noto Sans JP", "Ubuntu", sans-serif; display: flex; flex-direction: column; overflow: hidden; }
|
| 25 |
+
header { display: flex; align-items: center; gap: 2px; padding: 4px 8px 0; background: var(--panel); border-bottom: 1px solid var(--border); flex: none; }
|
| 26 |
+
header .tab { font: inherit; background: none; border: 0; border-bottom: 2px solid transparent; color: var(--muted); padding: 5px 10px 6px; cursor: pointer; border-radius: 0; }
|
| 27 |
+
header .tab:hover { color: var(--text); background: none; }
|
| 28 |
+
header .tab.on { color: var(--accent); border-bottom-color: var(--accent); font-weight: 600; }
|
| 29 |
+
header .spacer { flex: 1; }
|
| 30 |
+
header .env { color: var(--muted); font-size: 11.5px; margin-right: 8px; white-space: nowrap; }
|
| 31 |
+
main { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; padding: 8px 10px 10px; }
|
| 32 |
+
.page { display: none; } .page.on { display: block; }
|
| 33 |
+
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin-bottom: 8px; }
|
| 34 |
+
.row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
| 35 |
+
.grow { flex: 1; min-width: 0; }
|
| 36 |
+
.muted { color: var(--muted); } .small { font-size: 11.5px; }
|
| 37 |
+
.mono { font-family: ui-monospace, Consolas, Menlo, monospace; font-size: 11.5px; }
|
| 38 |
+
.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 39 |
+
.err { color: var(--danger); }
|
| 40 |
+
button { font: inherit; cursor: pointer; border-radius: 6px; border: 1px solid var(--border); background: var(--panel); color: var(--text); padding: 3px 9px; line-height: 1.4; white-space: nowrap; }
|
| 41 |
+
button:hover { background: var(--panel2); }
|
| 42 |
+
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 600; }
|
| 43 |
+
button.primary:hover { filter: brightness(1.06); background: var(--accent); }
|
| 44 |
+
button.ghost { border-color: transparent; background: none; color: var(--accent); padding: 2px 5px; }
|
| 45 |
+
button.ghost:hover { background: var(--accent-soft); }
|
| 46 |
+
button.danger { color: var(--danger); } button.danger:hover { background: var(--danger-soft); }
|
| 47 |
+
button:disabled { opacity: .45; cursor: default; filter: none; }
|
| 48 |
+
select, input[type=text], input[type=number], input[type=password] { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--border); border-radius: 6px; padding: 3px 8px; min-width: 0; }
|
| 49 |
+
select { appearance: none; -webkit-appearance: none; padding-right: 24px; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%236a6d76' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>"); background-repeat: no-repeat; background-position: right 8px center; }
|
| 50 |
+
select option { background: var(--panel); color: var(--text); }
|
| 51 |
+
select:focus, input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
| 52 |
+
.switch { position: relative; width: 30px; height: 17px; flex: none; }
|
| 53 |
+
.switch input { opacity: 0; width: 0; height: 0; }
|
| 54 |
+
.switch i { position: absolute; inset: 0; background: var(--border); border-radius: 999px; transition: .15s; }
|
| 55 |
+
.switch i::after { content: ""; position: absolute; width: 13px; height: 13px; left: 2px; top: 2px; background: #fff; border-radius: 50%; transition: .15s; box-shadow: 0 1px 2px rgba(0,0,0,.2); }
|
| 56 |
+
.switch input:checked + i { background: var(--accent); }
|
| 57 |
+
.switch input:checked + i::after { transform: translateX(13px); }
|
| 58 |
+
.pill { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; font-weight: 600; padding: 1px 8px 1px 7px; border-radius: 999px; background: var(--panel2); color: var(--muted); white-space: nowrap; }
|
| 59 |
+
.pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
|
| 60 |
+
.pill.ok { background: var(--ok-soft); color: var(--ok); }
|
| 61 |
+
.pill.warn { background: var(--warn-soft); color: var(--warn); } .pill.warn::before { animation: blink 1.2s infinite; }
|
| 62 |
+
.pill.danger { background: var(--danger-soft); color: var(--danger); }
|
| 63 |
+
.pill.accent { background: var(--accent-soft); color: var(--accent); }
|
| 64 |
+
@keyframes blink { 50% { opacity: .35; } }
|
| 65 |
+
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 3px 12px; align-items: center; }
|
| 66 |
+
.kv .k { color: var(--muted); }
|
| 67 |
+
.kv code { font-family: ui-monospace, Consolas, Menlo, monospace; font-size: 12px; background: var(--panel2); padding: 1px 6px; border-radius: 4px; }
|
| 68 |
+
table { width: 100%; border-collapse: collapse; }
|
| 69 |
+
th { text-align: left; color: var(--muted); font-weight: 500; font-size: 11.5px; padding: 2px 6px 5px; border-bottom: 1px solid var(--border); white-space: nowrap; }
|
| 70 |
+
td { padding: 4px 6px; border-bottom: 1px solid var(--border); vertical-align: middle; white-space: nowrap; }
|
| 71 |
+
tr:last-child td { border-bottom: 0; }
|
| 72 |
+
tbody tr.live { background: var(--ok-soft); box-shadow: inset 3px 0 0 var(--ok); }
|
| 73 |
+
tbody tr.loading { background: var(--warn-soft); box-shadow: inset 3px 0 0 var(--warn); }
|
| 74 |
+
tbody tr.failed { background: var(--danger-soft); box-shadow: inset 3px 0 0 var(--danger); }
|
| 75 |
+
tbody tr.nofit { background: var(--danger-soft); }
|
| 76 |
+
tbody tr.downloading { background: linear-gradient(90deg, var(--accent-soft) var(--p), transparent var(--p)); }
|
| 77 |
+
td.name { font-weight: 600; }
|
| 78 |
+
td.name .sub { display: block; font-weight: 400; color: var(--muted); font-size: 11px; max-width: 240px; overflow: hidden; text-overflow: ellipsis; }
|
| 79 |
+
td.acts { text-align: right; }
|
| 80 |
+
td.acts button, td.name .acts2 button { padding: 1px 7px; font-size: 11.5px; margin-left: 3px; }
|
| 81 |
+
td.acts .more, td.name .acts2 .more { padding: 1px 6px; font-weight: 700; }
|
| 82 |
+
td.bad { color: var(--warn); }
|
| 83 |
+
td.name .acts2 { display: none; margin-top: 3px; text-align: right; }
|
| 84 |
+
.sw { display: inline-block; width: 12px; height: 12px; border-radius: 3px; vertical-align: -2px; margin-right: 4px; border: 1px solid var(--border); }
|
| 85 |
+
.sw.ok { background: var(--ok-soft); } .sw.dl { background: var(--accent-soft); } .sw.nofit { background: var(--danger-soft); }
|
| 86 |
+
.menu { position: fixed; background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 4px; box-shadow: 0 6px 20px rgba(0,0,0,.14); display: none; z-index: 5; min-width: 160px; }
|
| 87 |
+
.menu.show { display: block; }
|
| 88 |
+
.menu button { display: block; width: 100%; text-align: left; border: 0; border-radius: 5px; padding: 5px 10px; background: none; }
|
| 89 |
+
.menu button:hover { background: var(--panel2); }
|
| 90 |
+
.form { display: grid; grid-template-columns: max-content 1fr max-content 1fr; gap: 6px 10px; align-items: center; }
|
| 91 |
+
.form .k { color: var(--muted); }
|
| 92 |
+
.form .full { grid-column: 1 / -1; }
|
| 93 |
+
.toggles { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 16px; }
|
| 94 |
+
.toggles label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
| 95 |
+
.updcard { position: fixed; right: 12px; bottom: 12px; width: min(360px, calc(100vw - 24px)); background: var(--panel);
|
| 96 |
+
border: 1px solid var(--accent); border-radius: 10px; padding: 10px 12px; box-shadow: 0 8px 28px rgba(0,0,0,.18);
|
| 97 |
+
z-index: 6; transform: translateY(calc(100% + 24px)); transition: transform .25s ease; }
|
| 98 |
+
.updcard.show { transform: none; }
|
| 99 |
+
.updcard pre { white-space: pre-wrap; margin: 6px 0 0; max-height: 140px; overflow: auto; font: inherit; background: var(--panel2);
|
| 100 |
+
border-radius: 6px; padding: 6px 8px; }
|
| 101 |
+
.updcard .prog { height: 5px; border-radius: 999px; background: var(--panel2); overflow: hidden; margin-top: 6px; }
|
| 102 |
+
.updcard .prog i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }
|
| 103 |
+
.toast { position: fixed; bottom: 12px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg); padding: 5px 12px; border-radius: 999px; font-size: 12px; opacity: 0; transition: .2s; pointer-events: none; max-width: 90vw; }
|
| 104 |
+
.toast.show { opacity: 1; }
|
| 105 |
+
.dlg { position: fixed; inset: 0; background: rgba(0,0,0,.35); display: none; align-items: center; justify-content: center; z-index: 9; }
|
| 106 |
+
.dlg.show { display: flex; }
|
| 107 |
+
.dlg .box { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; width: min(420px, calc(100vw - 24px));
|
| 108 |
+
box-shadow: 0 10px 32px rgba(0,0,0,.25); }
|
| 109 |
+
.dlg .msg { white-space: pre-wrap; overflow-wrap: anywhere; margin-bottom: 10px; }
|
| 110 |
+
.dlg input, .dlg select { width: 100%; margin-bottom: 10px; }
|
| 111 |
+
.banner { background: var(--warn-soft); color: var(--warn); border-radius: 6px; padding: 4px 8px; margin: 0 2px 6px; }
|
| 112 |
+
@media (max-width: 640px) {
|
| 113 |
+
header .env { display: none; }
|
| 114 |
+
.c { display: none; }
|
| 115 |
+
td.acts { display: none; }
|
| 116 |
+
td.name .acts2 { display: block; }
|
| 117 |
+
td.name .sub { white-space: normal; max-width: none; }
|
| 118 |
+
td { white-space: normal; }
|
| 119 |
+
.form { grid-template-columns: max-content 1fr; }
|
| 120 |
+
.toggles { grid-template-columns: 1fr; }
|
| 121 |
+
}
|
| 122 |
+
</style>
|
| 123 |
+
</head>
|
| 124 |
+
<body>
|
| 125 |
+
<header>
|
| 126 |
+
<button class="tab on" data-page="server">サーバー</button>
|
| 127 |
+
<button class="tab" data-page="models">モデル</button>
|
| 128 |
+
<button class="tab" data-page="settings">設定</button>
|
| 129 |
+
<span class="spacer"></span>
|
| 130 |
+
<span class="env" id="env"></span>
|
| 131 |
+
<span class="pill accent" id="upill" style="display:none;cursor:pointer" onclick="openCard()">更新あり</span>
|
| 132 |
+
<span class="pill" id="hpill">…</span>
|
| 133 |
+
</header>
|
| 134 |
+
|
| 135 |
+
<main>
|
| 136 |
+
<section class="page on" id="page-server">
|
| 137 |
+
<div class="card">
|
| 138 |
+
<div class="row" style="margin-bottom:6px">
|
| 139 |
+
<span class="pill" id="spill">…</span>
|
| 140 |
+
<b style="font-size:14px" id="sname">—</b>
|
| 141 |
+
<span class="muted small" id="sinfo"></span>
|
| 142 |
+
<span class="grow"></span>
|
| 143 |
+
<button id="b-chat" onclick="post('open',{what:'chat'})">チャット</button>
|
| 144 |
+
<button id="b-check" onclick="post('open',{what:'check'})">検証ページ</button>
|
| 145 |
+
<button onclick="post('open',{what:'log'})">ログ</button>
|
| 146 |
+
<button class="danger" id="b-unload" onclick="post('unload')">アンロード</button>
|
| 147 |
+
</div>
|
| 148 |
+
<div class="kv">
|
| 149 |
+
<span class="k">NPU エンジン</span><span class="row" style="gap:6px"><span id="seng">FastFlowLM</span><span class="muted small">Powered by <a href="#" onclick="post('open',{what:'flm'});return false">FastFlowLM</a></span></span>
|
| 150 |
+
<span class="k">場所</span><span class="mono ellipsis" id="spath">—</span>
|
| 151 |
+
<span class="k">OpenAI API</span><span class="row" style="gap:6px"><code id="surl">—</code><span class="muted small">モデル名 <span class="mono" id="sid">—</span></span><button class="ghost" onclick="copyUrl()">コピー</button></span>
|
| 152 |
+
</div>
|
| 153 |
+
<div class="muted small" id="sbusy" style="margin-top:4px"></div>
|
| 154 |
+
</div>
|
| 155 |
+
<div class="card">
|
| 156 |
+
<div class="row">
|
| 157 |
+
<span class="muted">使うモデル</span>
|
| 158 |
+
<select class="grow" id="pick"></select>
|
| 159 |
+
<button class="primary" id="b-load" onclick="loadPicked()">ロード</button>
|
| 160 |
+
</div>
|
| 161 |
+
<div class="muted small" style="margin-top:5px">一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。モデルはすべて AMD NPU(XDNA2)の上だけで動きます(NPU 専用エンジン FastFlowLM)。</div>
|
| 162 |
+
</div>
|
| 163 |
+
</section>
|
| 164 |
+
|
| 165 |
+
<section class="page" id="page-models">
|
| 166 |
+
<div class="banner small" id="npuwarn" style="display:none">この PC には XDNA2 の NPU が見つかりません(Ryzen AI 300 シリーズ以降と NPU ドライバーが必要です)</div>
|
| 167 |
+
<div class="banner small" id="dirwarn" style="display:none"></div>
|
| 168 |
+
<div class="card" style="padding:6px 10px">
|
| 169 |
+
<div class="row small" id="engines"></div>
|
| 170 |
+
</div>
|
| 171 |
+
<div class="row small" style="margin:0 2px 6px">
|
| 172 |
+
<span class="muted">保存先</span><span class="mono ellipsis" id="savedir"></span><button class="ghost" onclick="changeSave()">変更…</button>
|
| 173 |
+
<span class="grow"></span>
|
| 174 |
+
<span class="muted" id="raminfo"></span>
|
| 175 |
+
</div>
|
| 176 |
+
<div class="card" style="padding:4px 6px">
|
| 177 |
+
<table>
|
| 178 |
+
<thead><tr><th>モデル</th><th class="c">画像</th><th class="c">サイズ</th><th class="c">メモリ目安</th><th class="c">状態</th><th></th></tr></thead>
|
| 179 |
+
<tbody id="rows"></tbody>
|
| 180 |
+
</table>
|
| 181 |
+
</div>
|
| 182 |
+
<div class="row small muted" style="margin:0 2px;gap:12px"><span><i class="sw ok"></i>使用中</span><span><i class="sw dl"></i>ダウンロード中(進み具合)</span><span><i class="sw nofit"></i>この PC ではメモリ不足の可能性</span></div>
|
| 183 |
+
</section>
|
| 184 |
+
|
| 185 |
+
<section class="page" id="page-settings">
|
| 186 |
+
<div class="card">
|
| 187 |
+
<div class="form" id="form">
|
| 188 |
+
<span class="k">ポート</span><input type="number" id="f-port" style="width:90px">
|
| 189 |
+
<span class="k">コンテキスト長</span><select id="f-context" style="width:110px"><option>1024</option><option>2048</option><option>4096</option><option>8192</option><option>16384</option><option>32768</option><option>65536</option><option>131072</option></select>
|
| 190 |
+
<span class="k">API キー(任意)</span><input type="password" id="f-api_key" placeholder="未設定なら何を入れても通ります">
|
| 191 |
+
<span class="k">言語</span><select id="f-lang" style="width:220px"><option value="auto">auto(OS に合わせる)</option><option value="ja">日本語</option><option value="en">English</option><option value="zh">简体中文</option></select>
|
| 192 |
+
<div class="full muted small">コンテキスト長は会話で使える最大の長さで、FastFlowLM に --ctx-len として渡します。長いほど使うメモリが増えます。変更はモデルの再ロード後に反映されます。</div>
|
| 193 |
+
</div>
|
| 194 |
+
</div>
|
| 195 |
+
<div class="card">
|
| 196 |
+
<div class="toggles" id="toggles">
|
| 197 |
+
<label><span class="switch"><input type="checkbox" id="f-autostart_server"><i></i></span>起動時に前回ロードしたモデルを自動でロードする</label>
|
| 198 |
+
<label><span class="switch"><input type="checkbox" id="f-login_start"><i></i></span>ログイン時にトレイを起動する</label>
|
| 199 |
+
<label><span class="switch"><input type="checkbox" id="f-lan"><i></i></span>LAN からの接続を許可する(API キー推奨)</label>
|
| 200 |
+
<label><span class="switch"><input type="checkbox" id="f-update_check"><i></i></span>起動時と 1 日ごとに更新を確認する</label>
|
| 201 |
+
<span class="row small"><button class="ghost" onclick="checkNow()">今すぐ確認</button><span class="muted" id="upd-checked"></span></span>
|
| 202 |
+
</div>
|
| 203 |
+
</div>
|
| 204 |
+
<div class="row"><span class="grow muted small" id="saved"></span><button class="primary" onclick="saveSettings()">保存</button></div>
|
| 205 |
+
</section>
|
| 206 |
+
</main>
|
| 207 |
+
<div class="toast" id="toast"></div>
|
| 208 |
+
<div class="updcard" id="upd">
|
| 209 |
+
<div class="row" style="align-items:flex-start;flex-wrap:nowrap">
|
| 210 |
+
<div class="grow">
|
| 211 |
+
<b id="upd-title">新しいバージョンがあります</b>
|
| 212 |
+
<div class="muted small" id="upd-msg"></div>
|
| 213 |
+
</div>
|
| 214 |
+
<button class="ghost" style="padding:0 4px" title="あとで" onclick="later()">✕</button>
|
| 215 |
+
</div>
|
| 216 |
+
<div class="prog" id="upd-prog" style="display:none"><i id="upd-bar"></i></div>
|
| 217 |
+
<pre id="upd-notes" class="small" style="display:none"></pre>
|
| 218 |
+
<div class="row" style="justify-content:flex-end;margin-top:6px">
|
| 219 |
+
<button class="ghost" id="b-notes" onclick="toggleNotes()">変更点</button>
|
| 220 |
+
<button id="b-later" onclick="later()">あとで</button>
|
| 221 |
+
<button class="primary" id="b-update" onclick="doUpdate()">更新する</button>
|
| 222 |
+
</div>
|
| 223 |
+
</div>
|
| 224 |
+
<div class="menu" id="menu"></div>
|
| 225 |
+
<div class="dlg" id="dlg"><div class="box">
|
| 226 |
+
<div class="msg" id="dlg-msg"></div>
|
| 227 |
+
<input type="text" id="dlg-in" style="display:none">
|
| 228 |
+
<select id="dlg-sel" style="display:none"></select>
|
| 229 |
+
<div class="row" style="justify-content:flex-end"><button id="dlg-no">キャンセル</button><button class="primary" id="dlg-ok">OK</button></div>
|
| 230 |
+
</div></div>
|
| 231 |
+
|
| 232 |
+
<script>
|
| 233 |
+
translate(document.body);
|
| 234 |
+
const TOKEN = new URLSearchParams(location.search).get("token") || "";
|
| 235 |
+
const $ = id => document.getElementById(id);
|
| 236 |
+
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c]));
|
| 237 |
+
let S = null, dirty = false, tt, lastRows = "", lastPick = "";
|
| 238 |
+
|
| 239 |
+
function show(page) {
|
| 240 |
+
document.querySelectorAll("header .tab").forEach(x => x.classList.toggle("on", x.dataset.page === page));
|
| 241 |
+
document.querySelectorAll(".page").forEach(p => p.classList.toggle("on", p.id === "page-" + page));
|
| 242 |
+
}
|
| 243 |
+
document.querySelectorAll("header .tab").forEach(b => b.onclick = () => show(b.dataset.page));
|
| 244 |
+
if (location.hash.length > 1) show(location.hash.slice(1));
|
| 245 |
+
|
| 246 |
+
function toast(t, err) {
|
| 247 |
+
const e = $("toast"); e.textContent = t;
|
| 248 |
+
e.style.background = err ? "var(--danger)" : ""; e.style.color = err ? "#fff" : "";
|
| 249 |
+
e.classList.add("show"); clearTimeout(tt); tt = setTimeout(() => e.classList.remove("show"), err ? 4000 : 1600);
|
| 250 |
+
}
|
| 251 |
+
async function post(action, body) {
|
| 252 |
+
const r = await fetch("/api/" + action, {method: "POST", headers: {"Content-Type": "application/json", "X-Onw-Token": TOKEN}, body: JSON.stringify(body || {})});
|
| 253 |
+
const j = await r.json().catch(() => ({}));
|
| 254 |
+
if (j.error) toast(j.error, true);
|
| 255 |
+
refresh();
|
| 256 |
+
return j;
|
| 257 |
+
}
|
| 258 |
+
// in-page dialogs: the WebKit view on Ubuntu may not show the browser's confirm() / prompt()
|
| 259 |
+
function ask(msg, opt) {
|
| 260 |
+
opt = opt || {};
|
| 261 |
+
return new Promise(done => {
|
| 262 |
+
const d = $("dlg"), inp = $("dlg-in"), sel = $("dlg-sel");
|
| 263 |
+
$("dlg-msg").textContent = msg;
|
| 264 |
+
inp.style.display = opt.input ? "" : "none"; inp.value = opt.value || "";
|
| 265 |
+
sel.style.display = opt.choices ? "" : "none";
|
| 266 |
+
sel.innerHTML = (opt.choices || []).map(c => `<option>${esc(c)}</option>`).join("");
|
| 267 |
+
$("dlg-no").style.display = opt.noCancel ? "none" : "";
|
| 268 |
+
const end = v => { d.classList.remove("show"); $("dlg-ok").onclick = $("dlg-no").onclick = null; document.removeEventListener("keydown", key); done(v); };
|
| 269 |
+
const key = e => { if (e.key === "Escape") end(null); else if (e.key === "Enter") $("dlg-ok").click(); };
|
| 270 |
+
$("dlg-ok").onclick = () => end(opt.input ? inp.value : opt.choices ? sel.value : true);
|
| 271 |
+
$("dlg-no").onclick = () => end(null);
|
| 272 |
+
document.addEventListener("keydown", key);
|
| 273 |
+
d.classList.add("show");
|
| 274 |
+
(opt.input ? inp : $("dlg-ok")).focus();
|
| 275 |
+
});
|
| 276 |
+
}
|
| 277 |
+
async function pickFolder(initial) {
|
| 278 |
+
if (window.pywebview && pywebview.api) return await pywebview.api.pick_folder(initial || "");
|
| 279 |
+
return await ask(T("フォルダのパスを入力してください"), {input: true, value: initial || ""});
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
// ---- render from /api/state
|
| 283 |
+
const PILL = {live: ["ok", T("使用中")], loading: ["warn", T("ロード中…")], failed: ["danger", T("ロード失敗")], ready: ["accent", T("取得済み")],
|
| 284 |
+
};
|
| 285 |
+
function render() {
|
| 286 |
+
const s = S, sv = s.server, st = sv.status;
|
| 287 |
+
$("env").textContent = `onw AMD ${s.version} ・ ${s.npu || ""}`;
|
| 288 |
+
renderUpdate(s.update || {});
|
| 289 |
+
const pl = {running: ["ok", T("動作中")], loading: ["warn", T("ロード中")], failed: ["danger", T("ロード失敗")], stopped: ["", T("停止中")]}[st] || ["", st];
|
| 290 |
+
for (const id of ["hpill", "spill"]) { $(id).className = "pill " + pl[0]; $(id).textContent = pl[1]; }
|
| 291 |
+
if (sv.model) {
|
| 292 |
+
$("sname").textContent = sv.title;
|
| 293 |
+
$("sinfo").textContent = ["NPU ・ FastFlowLM", sv.mem_gb ? T("メモリ 約{0} GB", Math.round(sv.mem_gb)) : ""].filter(Boolean).join(" ・ ");
|
| 294 |
+
$("spath").textContent = sv.path || ""; $("sid").textContent = sv.model.split("/").pop();
|
| 295 |
+
} else {
|
| 296 |
+
$("sname").textContent = T("モデルは読み込まれていません"); $("sinfo").textContent = ""; $("spath").textContent = "—"; $("sid").textContent = "—";
|
| 297 |
+
}
|
| 298 |
+
$("surl").textContent = s.api_url;
|
| 299 |
+
$("sbusy").textContent = s.busy || (st === "failed" && sv.error ? T("止まった理由: {0}", sv.error) : "");
|
| 300 |
+
$("sbusy").className = "small " + (s.busy_err || (!s.busy && st === "failed") ? "err" : "muted");
|
| 301 |
+
for (const id of ["b-chat", "b-check"]) $(id).disabled = st !== "running";
|
| 302 |
+
$("b-unload").disabled = !(st === "running" || st === "loading");
|
| 303 |
+
// model picker (keeps the user's choice)
|
| 304 |
+
const inst = s.models.filter(m => m.path), pick = $("pick");
|
| 305 |
+
const cur = (pick.value && inst.some(m => m.key === pick.value)) ? pick.value
|
| 306 |
+
: (sv.model && inst.some(m => m.key === sv.model) ? sv.model : (inst.find(m => m.key === s.config.model) || inst[0] || {}).key);
|
| 307 |
+
const pickHtml = inst.map(m => `<option value="${esc(m.key)}"${m.key === cur ? " selected" : ""}>${esc(m.title)} — ${esc(m.path)}${m.key === sv.model ? T("(ロード済み)") : ""}</option>`).join("");
|
| 308 |
+
if (pickHtml !== lastPick) { pick.innerHTML = pickHtml; lastPick = pickHtml; } // rebuild only on change: a rebuild eats clicks
|
| 309 |
+
const same = sv.model && pick.value === sv.model;
|
| 310 |
+
$("b-load").textContent = same ? T("ロード済み") : (sv.model ? T("切り替え") : T("ロード"));
|
| 311 |
+
$("b-load").disabled = same || !pick.value || st === "loading";
|
| 312 |
+
// models table
|
| 313 |
+
$("npuwarn").style.display = s.npu && !s.npu_ok ? "" : "none";
|
| 314 |
+
$("seng").textContent = "FastFlowLM " + (s.engine.installed || T("未インストール"));
|
| 315 |
+
const ed = s.engine_dl, e = s.engine;
|
| 316 |
+
let est;
|
| 317 |
+
if (ed && !ed.done) est = `<span class="pill warn">${esc(ed.text)}</span><button onclick="post('cancel_download')">${T("キャンセル")}</button>`;
|
| 318 |
+
else if (e.state === "ok") est = `<span class="pill ok">${esc(e.installed)}</span>`;
|
| 319 |
+
else est = `<span class="pill${e.state === "old" ? " warn" : ""}">${e.installed ? esc(e.installed) + " → " + esc(e.version) : T("未インストール")}</span>` +
|
| 320 |
+
`<button class="primary"${s.npu_ok ? "" : " disabled"} onclick="post('install_engine')">${e.installed ? T("更新") : T("入れる")}</button>`;
|
| 321 |
+
if (ed && ed.done && ed.error) est += `<span class="err" title="${esc(ed.error)}">${T("失敗")}</span>`;
|
| 322 |
+
const engHtml = `<span class="muted">${esc(s.npu || "NPU …")}</span><span style="margin-left:10px"><b>FastFlowLM</b></span>${est}` +
|
| 323 |
+
(e.state === "missing" ? `<span class="muted grow" style="min-width:200px">${T("モデルの一覧は、FastFlowLM(約 40 MB)を入れると出ます")}</span>` : "") +
|
| 324 |
+
(s.flm_error ? `<span class="err grow" title="${esc(s.flm_error)}">FastFlowLM: ${esc(s.flm_error.slice(0, 120))}</span>` : "");
|
| 325 |
+
if ($("engines").innerHTML !== engHtml) $("engines").innerHTML = engHtml;
|
| 326 |
+
$("savedir").textContent = s.save_dir;
|
| 327 |
+
$("dirwarn").style.display = s.models_dir_missing ? "" : "none";
|
| 328 |
+
$("dirwarn").textContent = s.models_dir_missing ? T("保存先 {0} が使えないため、既定のフォルダを使っています(「変更…」で選び直せます)", s.models_dir_missing) : "";
|
| 329 |
+
$("raminfo").textContent = s.ram_gb ? T("この PC のメモリ {0} GB ・ メモリ目安は今の設定での値", Math.round(s.ram_gb)) : "";
|
| 330 |
+
const rowsHtml = s.models.map(m => {
|
| 331 |
+
const cls = m.state + ((!m.fits && m.state !== "live") ? " nofit" : "");
|
| 332 |
+
const style = m.state === "downloading" ? ` style="--p:${Math.round((m.progress || 0) * 100)}%"` : "";
|
| 333 |
+
let note = m.note || "";
|
| 334 |
+
if (!m.fits && m.mem_gb && m.state !== "downloading") note += T("・メモリ 約{0} GB はこの PC では不足の可能性", Math.round(m.mem_gb));
|
| 335 |
+
const acts = actions(m);
|
| 336 |
+
let pill = "";
|
| 337 |
+
if (m.state === "downloading") pill = `<span class="pill accent">${Math.round((m.progress || 0) * 100)}%</span>`;
|
| 338 |
+
else if (m.state === "missing") pill = `<span class="muted small">${T("未取得")}</span>`;
|
| 339 |
+
else if (PILL[m.state]) pill = `<span class="pill ${PILL[m.state][0]}">${PILL[m.state][1]}</span>`;
|
| 340 |
+
const cols = `<td class="c${m.image ? "" : " muted"}">${m.image ? T("可") : "—"}</td><td class="c">${m.size_gb ? m.size_gb.toFixed(1) + " GB" : "—"}</td><td class="c${m.fits ? "" : " bad"}">${m.mem_gb ? T("約{0} GB", Math.round(m.mem_gb)) : "—"}</td>`;
|
| 341 |
+
return `<tr class="${cls}"${style}><td class="name">${esc(m.title)}<span class="sub" title="${esc(note)}">${esc(note)}</span><span class="acts2">${acts}</span></td>${cols}<td class="c">${pill}</td><td class="acts">${acts}</td></tr>`;
|
| 342 |
+
}).join("");
|
| 343 |
+
if (rowsHtml !== lastRows) { $("rows").innerHTML = rowsHtml; lastRows = rowsHtml; }
|
| 344 |
+
// settings (left alone while the user edits)
|
| 345 |
+
if (!dirty) {
|
| 346 |
+
const c = s.config;
|
| 347 |
+
$("f-port").value = c.port; $("f-context").value = String(c.context); $("f-api_key").value = c.api_key || "";
|
| 348 |
+
$("f-lang").value = c.lang || "auto";
|
| 349 |
+
for (const k of ["autostart_server", "login_start", "lan", "update_check"]) $("f-" + k).checked = c[k] !== false && !!(c[k] ?? true);
|
| 350 |
+
}
|
| 351 |
+
}
|
| 352 |
+
function actions(m) {
|
| 353 |
+
const k = esc(m.key), more = `<button class="more" onclick="menu(event,'${k}')">⋯</button>`;
|
| 354 |
+
switch (m.state) {
|
| 355 |
+
case "live": return `<button disabled>${T("ロード済み")}</button>${more}`;
|
| 356 |
+
case "loading": return `<button disabled>${T("ロード中…")}</button>${more}`;
|
| 357 |
+
case "downloading": return `<button onclick="post('cancel_download')">${T("キャンセル")}</button>`;
|
| 358 |
+
case "missing": return `<button class="primary"${S.npu_ok ? "" : " disabled"} onclick="post('download',{key:'${k}'})">${T("ダウンロード")}</button>`;
|
| 359 |
+
default: return `<button class="primary" onclick="post('load',{key:'${k}'})">${S.server.model ? T("切り替え") : T("ロード")}</button>${more}`;
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
function menu(ev, key) {
|
| 363 |
+
ev.stopPropagation();
|
| 364 |
+
const m = S.models.find(x => x.key === key), mn = $("menu");
|
| 365 |
+
const k = esc(key);
|
| 366 |
+
mn.innerHTML = `<button onclick="post('open',{what:'folder',key:'${k}'})">${T("フォルダを開く")}</button>` +
|
| 367 |
+
(m.deletable ? `<button class="danger" onclick="deleteModel('${k}')">${T("モデルを削除")}</button>`
|
| 368 |
+
: `<button disabled>${T("削除(onw が入れたモデルではありません)")}</button>`);
|
| 369 |
+
const r = ev.currentTarget.getBoundingClientRect();
|
| 370 |
+
mn.style.left = Math.max(4, Math.min(r.right - 170, innerWidth - 175)) + "px"; mn.style.top = (r.bottom + 4) + "px";
|
| 371 |
+
mn.classList.add("show");
|
| 372 |
+
}
|
| 373 |
+
addEventListener("click", () => $("menu").classList.remove("show"));
|
| 374 |
+
async function deleteModel(key) {
|
| 375 |
+
const m = S.models.find(x => x.key === key);
|
| 376 |
+
if (m && await ask(T("{0} を削除しますか?\n{1}", m.title, m.path))) post("delete", {key});
|
| 377 |
+
}
|
| 378 |
+
function loadPicked() { const k = $("pick").value; if (k) post("load", {key: k}); }
|
| 379 |
+
function copyUrl() { navigator.clipboard.writeText(S.api_url).then(() => toast(T("URL をコピーしました")), () => ask(T("コピーしてください"), {input: true, value: S.api_url, noCancel: true})); }
|
| 380 |
+
async function changeSave() {
|
| 381 |
+
const d = await pickFolder(S.save_dir);
|
| 382 |
+
if (d && await ask(T("保存先を {0} にしますか?\n今の保存先のモデルはそのまま残ります(新しい保存先には出ません)。", d))) post("save_dir", {path: d});
|
| 383 |
+
}
|
| 384 |
+
async function saveSettings() {
|
| 385 |
+
const body = {port: $("f-port").value, context: $("f-context").value, api_key: $("f-api_key").value.trim(), lang: $("f-lang").value};
|
| 386 |
+
for (const k of ["autostart_server", "login_start", "lan", "update_check"]) body[k] = $("f-" + k).checked;
|
| 387 |
+
const oldLang = S.config.lang || "auto";
|
| 388 |
+
const r = await post("settings", body);
|
| 389 |
+
if (r.error) return;
|
| 390 |
+
dirty = false;
|
| 391 |
+
$("saved").textContent = T("保存しました");
|
| 392 |
+
if (r.restart_needed && await ask(T("設定は保存しました。サーバーを新しい設定で今すぐ再起動しますか?(キャンセルしても、次にモデルを読み込むときから反映されます)"))) await post("restart");
|
| 393 |
+
if (oldLang !== body.lang) location.reload(); // the page is served in the new language
|
| 394 |
+
}
|
| 395 |
+
$("form").addEventListener("input", () => { dirty = true; $("saved").textContent = ""; });
|
| 396 |
+
for (const el of document.querySelectorAll(".toggles")) el.addEventListener("change", () => { dirty = true; $("saved").textContent = ""; });
|
| 397 |
+
|
| 398 |
+
// update card: slides in from the bottom right when a new version is found (or while updating);
|
| 399 |
+
// "later" hides it for that version until the pill in the header is clicked
|
| 400 |
+
let dismissed = (() => { try { return localStorage.getItem("onw-dismissed") || ""; } catch (e) { return ""; } })();
|
| 401 |
+
let forced = false;
|
| 402 |
+
function renderUpdate(u) {
|
| 403 |
+
const has = !!u.latest, busy = u.state === "updating" || u.state === "done" || u.state === "error";
|
| 404 |
+
$("upill").style.display = has ? "" : "none";
|
| 405 |
+
$("upill").textContent = has ? T("更新あり v{0}", u.latest) : "";
|
| 406 |
+
const show = busy || (has && (forced || dismissed !== u.latest));
|
| 407 |
+
$("upd").classList.toggle("show", show);
|
| 408 |
+
$("upd-title").textContent = u.state === "done" ? T("更新しました") : u.state === "error" ? T("更新できませんでした")
|
| 409 |
+
: has ? T("新しいバージョン v{0} があります", u.latest) : T("onw の更新");
|
| 410 |
+
$("upd-msg").textContent = u.msg || (has ? (u.can_update ? T("今は v{0}。「更新する」で入れ替えて再起動します", u.current)
|
| 411 |
+
: T("このフォルダは自動更新の対象外です(1 行インストーラーで入れ直してください)")) : "");
|
| 412 |
+
$("upd-msg").className = "small " + (u.state === "error" ? "err" : "muted");
|
| 413 |
+
const m = /(\d+)\/(\d+)/.exec(u.msg || "");
|
| 414 |
+
$("upd-prog").style.display = u.state === "updating" ? "" : "none";
|
| 415 |
+
$("upd-bar").style.width = u.state === "updating" ? (m ? Math.round(m[1] / m[2] * 90) : 95) + "%" : "0";
|
| 416 |
+
$("b-update").style.display = $("b-later").style.display = u.state === "updating" || u.state === "done" ? "none" : "";
|
| 417 |
+
$("b-update").disabled = !has || !u.can_update;
|
| 418 |
+
$("b-notes").style.display = u.notes ? "" : "none";
|
| 419 |
+
if ($("upd-notes").textContent !== (u.notes || "")) $("upd-notes").textContent = u.notes || "";
|
| 420 |
+
$("upd-checked").textContent = u.checking ? T("確認中…")
|
| 421 |
+
: u.checked ? T("最終確認 {0}", new Date(u.checked * 1000).toLocaleString()) : "";
|
| 422 |
+
if (waitCheck && !u.checking) {
|
| 423 |
+
waitCheck = false;
|
| 424 |
+
if (u.error) toast(u.error, true); else if (u.latest) openCard(); else toast(T("最新版です"));
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
function openCard() { forced = true; if (S) renderUpdate(S.update || {}); }
|
| 428 |
+
function later() {
|
| 429 |
+
forced = false;
|
| 430 |
+
const v = S && S.update && S.update.latest;
|
| 431 |
+
if (v) { dismissed = v; try { localStorage.setItem("onw-dismissed", v); } catch (e) {} }
|
| 432 |
+
$("upd").classList.remove("show");
|
| 433 |
+
}
|
| 434 |
+
function toggleNotes() { const n = $("upd-notes"); n.style.display = n.style.display === "none" ? "" : "none"; }
|
| 435 |
+
async function doUpdate() {
|
| 436 |
+
if (!await ask(T("onw を更新します。サーバーは一度止まり、更新後に同じモデルを読み込み直します。よろしいですか?"))) return;
|
| 437 |
+
post("update");
|
| 438 |
+
}
|
| 439 |
+
let waitCheck = false; // "Check now" pressed: say how it ended (renderUpdate)
|
| 440 |
+
async function checkNow() {
|
| 441 |
+
const r = await post("update_check");
|
| 442 |
+
if (r.error) return;
|
| 443 |
+
waitCheck = true;
|
| 444 |
+
toast(T("確認中…"));
|
| 445 |
+
}
|
| 446 |
+
// after an update the tray restarts with a new manager: the window reconnects (see app.window) and says so
|
| 447 |
+
const justUpdated = new URLSearchParams(location.search).get("updated");
|
| 448 |
+
if (justUpdated) setTimeout(() => toast(T("v{0} に更新しました", justUpdated)), 400);
|
| 449 |
+
|
| 450 |
+
async function refresh() {
|
| 451 |
+
try {
|
| 452 |
+
const r = await fetch("/api/state?token=" + encodeURIComponent(TOKEN), {cache: "no-store"});
|
| 453 |
+
if (r.status === 403) { $("env").textContent = T("この画面は onw のウィンドウかトレイから開いてください"); return; }
|
| 454 |
+
S = await r.json(); render();
|
| 455 |
+
} catch (e) { $("hpill").className = "pill danger"; $("hpill").textContent = T("接続なし"); }
|
| 456 |
+
}
|
| 457 |
+
refresh(); setInterval(refresh, 1000);
|
| 458 |
+
</script>
|
| 459 |
+
</body>
|
| 460 |
+
</html>
|
pyproject.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=64"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "onw-amd"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Ore no NPU ga konna ni ugoku wake nai - LLMs entirely on the AMD Ryzen AI NPU (FastFlowLM, as in Lemonade Server)"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = {text = "Apache-2.0"}
|
| 11 |
+
requires-python = ">=3.10"
|
| 12 |
+
dependencies = ["fastapi", "uvicorn", "httpx", "psutil"]
|
| 13 |
+
|
| 14 |
+
[project.optional-dependencies]
|
| 15 |
+
tray = ["pystray", "pywebview", "pillow"]
|
| 16 |
+
|
| 17 |
+
[project.scripts]
|
| 18 |
+
onw = "onw.__main__:main"
|
| 19 |
+
|
| 20 |
+
[tool.setuptools.packages.find]
|
| 21 |
+
include = ["onw*"]
|
| 22 |
+
|
| 23 |
+
[tool.setuptools.package-data]
|
| 24 |
+
onw = ["web/*", "*.json"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Same dependencies as pyproject.toml (pip install -e . is what start.bat / start.sh do).
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
httpx
|
| 5 |
+
psutil
|
setup.bat
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
rem onw AMD - Ore no NPU ga konna ni ugoku wake nai: install the resident tray app (Windows, AMD Ryzen AI NPU).
|
| 3 |
+
rem Finds Python 3.10+ (offers to install it with winget), creates .venv, installs onw + the tray, adds "onw" to
|
| 4 |
+
rem the Start menu and starts it in the task tray. FastFlowLM and the models are downloaded later from the
|
| 5 |
+
rem onw window (Models tab).
|
| 6 |
+
setlocal
|
| 7 |
+
cd /d "%~dp0"
|
| 8 |
+
set PYTHONUTF8=1
|
| 9 |
+
|
| 10 |
+
if not exist ".venv\installed-tray.txt" goto create
|
| 11 |
+
rem an older install has the tray but not the window's web view package: install it
|
| 12 |
+
".venv\Scripts\python.exe" -c "import webview" >nul 2>&1 && goto shortcut
|
| 13 |
+
:create
|
| 14 |
+
if exist ".venv\Scripts\python.exe" goto install
|
| 15 |
+
call "%~dp0find_python.bat"
|
| 16 |
+
if not defined PY (
|
| 17 |
+
pause
|
| 18 |
+
exit /b 1
|
| 19 |
+
)
|
| 20 |
+
echo [setup] creating Python environment in .venv ...
|
| 21 |
+
%PY% -m venv .venv
|
| 22 |
+
if errorlevel 1 (
|
| 23 |
+
echo [setup] could not create the Python environment.
|
| 24 |
+
pause
|
| 25 |
+
exit /b 1
|
| 26 |
+
)
|
| 27 |
+
:install
|
| 28 |
+
rem (the bundled pip is fine; a newer pip once failed to install packages that have scripts, so it is not upgraded)
|
| 29 |
+
".venv\Scripts\python.exe" -m pip install -e .[tray]
|
| 30 |
+
if not errorlevel 1 goto installed
|
| 31 |
+
if defined RETRIED (
|
| 32 |
+
echo [setup] package installation failed.
|
| 33 |
+
pause
|
| 34 |
+
exit /b 1
|
| 35 |
+
)
|
| 36 |
+
echo [setup] installation failed; rebuilding the Python environment once ...
|
| 37 |
+
set RETRIED=1
|
| 38 |
+
rmdir /s /q .venv
|
| 39 |
+
if not defined PY call "%~dp0find_python.bat"
|
| 40 |
+
%PY% -m venv .venv
|
| 41 |
+
goto install
|
| 42 |
+
:installed
|
| 43 |
+
echo ok> ".venv\installed.txt"
|
| 44 |
+
echo ok> ".venv\installed-tray.txt"
|
| 45 |
+
|
| 46 |
+
:shortcut
|
| 47 |
+
rem Start menu entry: pythonw -m onw tray (no console window)
|
| 48 |
+
set "PYW=%CD%\.venv\Scripts\pythonw.exe"
|
| 49 |
+
powershell -NoProfile -Command ^
|
| 50 |
+
"$s = (New-Object -ComObject WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Programs') + '\onw AMD.lnk');" ^
|
| 51 |
+
"$s.TargetPath = '%PYW%'; $s.Arguments = '-m onw tray'; $s.WorkingDirectory = '%CD%';" ^
|
| 52 |
+
"$s.Description = 'onw AMD - LLMs on the AMD Ryzen AI NPU'; $s.IconLocation = '%CD%\onw\web\icon.ico,0'; $s.Save()"
|
| 53 |
+
echo [setup] Start menu: onw AMD
|
| 54 |
+
|
| 55 |
+
echo [start] onw AMD is starting in the task tray. Pick a model to download in the window that opens.
|
| 56 |
+
start "" "%PYW%" -m onw tray
|
setup.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# onw AMD - Ore no NPU ga konna ni ugoku wake nai: install the resident top-bar app (Ubuntu, AMD Ryzen AI NPU).
|
| 3 |
+
# The NPU engine is FastFlowLM; the amdxdna driver must be loaded.
|
| 4 |
+
# Installs the system pieces the indicator and the window need (AppIndicator, WebKit; asks for sudo once), creates .venv,
|
| 5 |
+
# installs onw + the tray, adds "onw" to the application list and starts it in the top bar.
|
| 6 |
+
# GNOME shows indicators through the "Ubuntu AppIndicators" extension, which Ubuntu enables by default.
|
| 7 |
+
set -e
|
| 8 |
+
cd "$(dirname "$0")"
|
| 9 |
+
export PYTHONUTF8=1
|
| 10 |
+
|
| 11 |
+
if ! python3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" 2>/dev/null; then
|
| 12 |
+
echo "Python 3.10 or newer is needed (Ubuntu 22.04 and later ship it): sudo apt install python3"
|
| 13 |
+
exit 1
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
need=""
|
| 17 |
+
# the window is a WebKit web view (pywebview): 4.1 on Ubuntu 24.04 and later, 4.0 before
|
| 18 |
+
webkit=gir1.2-webkit2-4.1
|
| 19 |
+
apt-cache show $webkit >/dev/null 2>&1 || webkit=gir1.2-webkit2-4.0
|
| 20 |
+
# wl-clipboard / xclip: "Copy the OpenAI API URL" in the top-bar menu (Wayland / X11)
|
| 21 |
+
for p in python3-venv python3-gi gir1.2-ayatanaappindicator3-0.1 $webkit wl-clipboard xclip; do
|
| 22 |
+
dpkg -s "$p" >/dev/null 2>&1 || need="$need $p"
|
| 23 |
+
done
|
| 24 |
+
if [ -n "$need" ]; then
|
| 25 |
+
echo "[setup] installing system packages:$need"
|
| 26 |
+
sudo apt-get install -y $need
|
| 27 |
+
fi
|
| 28 |
+
|
| 29 |
+
install_onw() {
|
| 30 |
+
# the bundled pip is fine (a newer pip once failed to install packages that have scripts, so it is not upgraded)
|
| 31 |
+
.venv/bin/python -m pip install -e ".[tray]"
|
| 32 |
+
}
|
| 33 |
+
if [ ! -f .venv/installed-tray.txt ] || ! .venv/bin/python -c "import webview" >/dev/null 2>&1; then
|
| 34 |
+
if [ ! -f .venv/bin/python ]; then
|
| 35 |
+
echo "[setup] creating Python environment in .venv ..."
|
| 36 |
+
# system site packages: the GObject bindings for the indicator and WebKit come from apt (python3-gi)
|
| 37 |
+
python3 -m venv --system-site-packages .venv
|
| 38 |
+
fi
|
| 39 |
+
if ! install_onw; then
|
| 40 |
+
echo "[setup] installation failed; rebuilding the Python environment once ..."
|
| 41 |
+
rm -rf .venv
|
| 42 |
+
python3 -m venv --system-site-packages .venv
|
| 43 |
+
install_onw || exit 1
|
| 44 |
+
fi
|
| 45 |
+
echo ok > .venv/installed.txt
|
| 46 |
+
echo ok > .venv/installed-tray.txt
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
mkdir -p ~/.local/share/applications
|
| 50 |
+
cat > ~/.local/share/applications/onw-amd.desktop <<EOF
|
| 51 |
+
[Desktop Entry]
|
| 52 |
+
Type=Application
|
| 53 |
+
Name=onw AMD
|
| 54 |
+
Comment=LLMs on the AMD Ryzen AI NPU (俺のNPUがこんなに動くわけない)
|
| 55 |
+
Exec="$PWD/.venv/bin/onw" tray
|
| 56 |
+
Path=$PWD
|
| 57 |
+
Icon=$PWD/onw/web/icon.png
|
| 58 |
+
Terminal=false
|
| 59 |
+
Categories=Utility;
|
| 60 |
+
EOF
|
| 61 |
+
echo "[setup] application list: onw AMD"
|
| 62 |
+
|
| 63 |
+
echo "[start] onw AMD is starting in the top bar ..."
|
| 64 |
+
nohup .venv/bin/onw tray >/dev/null 2>&1 &
|
start.bat
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
rem onw AMD - Ore no NPU ga konna ni ugoku wake nai: run the server once from a console (Windows).
|
| 3 |
+
rem start.bat qwen3-it-4b-FLM (default)
|
| 4 |
+
rem start.bat llama3.2-3b-FLM any model name from "onw list"
|
| 5 |
+
rem start.bat MODEL --port 8080 further options go to "onw serve"
|
| 6 |
+
rem First run: finds / installs Python, creates .venv, downloads FastFlowLM and the model.
|
| 7 |
+
rem For the resident tray app with a model manager use setup.bat instead.
|
| 8 |
+
setlocal
|
| 9 |
+
cd /d "%~dp0"
|
| 10 |
+
set PYTHONUTF8=1
|
| 11 |
+
set "MODEL=qwen3-it-4b-FLM"
|
| 12 |
+
set "FIRST=%~1"
|
| 13 |
+
if not "%FIRST%"=="" if not "%FIRST:~0,1%"=="-" (
|
| 14 |
+
set "MODEL=%FIRST%"
|
| 15 |
+
shift
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
if exist ".venv\installed.txt" goto args
|
| 19 |
+
if exist ".venv\Scripts\python.exe" goto install
|
| 20 |
+
call "%~dp0find_python.bat"
|
| 21 |
+
if not defined PY (
|
| 22 |
+
pause
|
| 23 |
+
exit /b 1
|
| 24 |
+
)
|
| 25 |
+
echo [setup] creating Python environment in .venv ...
|
| 26 |
+
%PY% -m venv .venv
|
| 27 |
+
if errorlevel 1 (
|
| 28 |
+
echo [setup] could not create the Python environment.
|
| 29 |
+
pause
|
| 30 |
+
exit /b 1
|
| 31 |
+
)
|
| 32 |
+
:install
|
| 33 |
+
".venv\Scripts\python.exe" -m pip install -U pip
|
| 34 |
+
".venv\Scripts\python.exe" -m pip install -e .
|
| 35 |
+
if errorlevel 1 (
|
| 36 |
+
echo [setup] package installation failed.
|
| 37 |
+
pause
|
| 38 |
+
exit /b 1
|
| 39 |
+
)
|
| 40 |
+
echo ok> ".venv\installed.txt"
|
| 41 |
+
|
| 42 |
+
:args
|
| 43 |
+
set "ARGS="
|
| 44 |
+
:collect
|
| 45 |
+
if "%~1"=="" goto run
|
| 46 |
+
set "ARGS=%ARGS% %1"
|
| 47 |
+
shift
|
| 48 |
+
goto collect
|
| 49 |
+
:run
|
| 50 |
+
echo [start] %MODEL% (first time: NPU engine + model download, please wait) ...
|
| 51 |
+
".venv\Scripts\onw.exe" serve %MODEL% --open %ARGS%
|
| 52 |
+
pause
|
start.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# onw AMD - Ore no NPU ga konna ni ugoku wake nai: one-command start (Linux, FastFlowLM on the AMD NPU).
|
| 3 |
+
# ./start.sh qwen3-it-4b-FLM (default)
|
| 4 |
+
# ./start.sh llama3.2-3b-FLM any model name from "onw list"
|
| 5 |
+
# ./start.sh MODEL --port 8080 --host 0.0.0.0 further options go to "onw serve"
|
| 6 |
+
# First run: creates .venv, downloads FastFlowLM and the model.
|
| 7 |
+
# Afterwards: source .venv/bin/activate, then onw serve / onw list / onw npu.
|
| 8 |
+
set -e
|
| 9 |
+
cd "$(dirname "$0")"
|
| 10 |
+
export PYTHONUTF8=1
|
| 11 |
+
MODEL="qwen3-it-4b-FLM"
|
| 12 |
+
if [ $# -gt 0 ] && [ "${1#-}" = "$1" ]; then MODEL="$1"; shift; fi
|
| 13 |
+
|
| 14 |
+
if ! python3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" 2>/dev/null; then
|
| 15 |
+
echo "Python 3.10 or newer is needed (Ubuntu 22.04 and later ship it): sudo apt install python3"
|
| 16 |
+
exit 1
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
if [ ! -f .venv/installed.txt ]; then
|
| 20 |
+
echo "[setup] creating Python environment in .venv ..."
|
| 21 |
+
if ! python3 -m venv .venv; then
|
| 22 |
+
echo "python3-venv is missing: sudo apt install python3-venv"
|
| 23 |
+
exit 1
|
| 24 |
+
fi
|
| 25 |
+
.venv/bin/python -m pip install -U pip
|
| 26 |
+
.venv/bin/python -m pip install -e .
|
| 27 |
+
echo ok > .venv/installed.txt
|
| 28 |
+
fi
|
| 29 |
+
|
| 30 |
+
echo "[start] $MODEL (first time: NPU engine + model download, please wait) ..."
|
| 31 |
+
exec .venv/bin/onw serve "$MODEL" --open "$@"
|