diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml new file mode 100644 index 0000000..14079ee --- /dev/null +++ b/.github/workflows/android-ci.yml @@ -0,0 +1,63 @@ +name: 中文普通话 Android 持续集成 + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: android-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + name: 单元测试、代码检查与调试构建 + runs-on: ubuntu-latest + timeout-minutes: 30 + + steps: + - name: 检出仓库 + uses: actions/checkout@v6 + + - name: 配置 Java 17 + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + + - name: 验证 Gradle Wrapper + uses: gradle/actions/wrapper-validation@v6 + + - name: 配置 Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: 运行单元测试、Lint 与仅编译调试构建 + run: ./gradlew --no-daemon testDebugUnitTest lintDebug assembleDebug + + - name: 上传验证报告 + if: always() + uses: actions/upload-artifact@v6 + with: + name: android-verification-reports + path: | + app/build/reports/tests/ + app/build/reports/lint-results-debug.* + if-no-files-found: warn + retention-days: 14 + + dependency-review: + name: 依赖变更审查 + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + + steps: + - name: 检出仓库 + uses: actions/checkout@v6 + + - name: 审查依赖变更 + uses: actions/dependency-review-action@v5 + with: + fail-on-severity: high diff --git a/.github/workflows/signed-release.yml b/.github/workflows/signed-release.yml new file mode 100644 index 0000000..9c61504 --- /dev/null +++ b/.github/workflows/signed-release.yml @@ -0,0 +1,110 @@ +name: 中文普通话 Android 签名发布 + +on: + workflow_dispatch: + inputs: + publish_github_release: + description: "将已签名的 APK/AAB 发布为 GitHub Release" + required: true + type: boolean + default: true + release_tag: + description: "Release 标签,例如 v0.5.0-beta.1" + required: true + type: string + default: "v0.5.0-beta.1" + +permissions: + contents: write + +jobs: + signed-release: + name: 构建并验证中文普通话实时字幕发行包 + runs-on: windows-latest + timeout-minutes: 60 + + steps: + - name: 检出仓库 + uses: actions/checkout@v6 + + - name: 配置 Java 17 + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + + - name: 验证 Gradle Wrapper + uses: gradle/actions/wrapper-validation@v6 + + - name: 配置 Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: 检查签名密钥配置 + shell: pwsh + env: + RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} + RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} + RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} + RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} + run: | + $names = @( + "RELEASE_KEYSTORE_BASE64", + "RELEASE_STORE_PASSWORD", + "RELEASE_KEY_ALIAS", + "RELEASE_KEY_PASSWORD" + ) + foreach ($name in $names) { + if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) { + throw "缺少必需的 GitHub Actions Secret:$name" + } + } + + - name: 恢复签名密钥库 + shell: pwsh + env: + RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} + run: | + $bytes = [Convert]::FromBase64String($env:RELEASE_KEYSTORE_BASE64) + [IO.File]::WriteAllBytes("$env:RUNNER_TEMP\localcaption-release.jks", $bytes) + + - name: 下载并校验运行时资源 + shell: pwsh + run: .\tools\setup-runtime-assets.ps1 + + - name: 构建并验证已签名 APK/AAB + shell: pwsh + env: + LOCALCAPTION_STORE_FILE: ${{ runner.temp }}\localcaption-release.jks + LOCALCAPTION_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} + LOCALCAPTION_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} + LOCALCAPTION_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} + run: .\tools\build-signed-release.ps1 -PublicRelease + + - name: 上传已签名发行产物 + uses: actions/upload-artifact@v6 + with: + name: LocalCaption-${{ inputs.release_tag }} + path: dist/release/* + if-no-files-found: error + retention-days: 30 + + - name: 发布 GitHub Release + if: inputs.publish_github_release + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + gh release create $env:RELEASE_TAG ` + .\dist\release\LocalCaption-release.apk ` + .\dist\release\LocalCaption-release.aab ` + .\dist\release\SHA256SUMS.txt ` + .\dist\release\THIRD_PARTY_NOTICES.md ` + .\dist\release\license-review.md ` + .\dist\release\Apache-2.0.txt ` + .\dist\release\MIT.txt ` + --repo $env:GITHUB_REPOSITORY ` + --target $env:GITHUB_SHA ` + --title "LocalCaption 中文普通话实时字幕 $env:RELEASE_TAG" ` + --prerelease ` + --notes-file .\docs\releases\v0.5.0-beta.1.md diff --git a/.gitignore b/.gitignore index 5e94a8b..e9a2d5e 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,10 @@ app/schemas/ .runtime-cache/ .toolchain/ dist/ -local.properties +artifacts/ +.secrets/ +*.jks +*.keystore # Large runtime assets are copied locally when testing; do not commit model binaries. app/src/main/assets/sherpa-onnx-*/ diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..cc86343 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,19 @@ +MIT License + +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..d827d2b --- /dev/null +++ b/README.en.md @@ -0,0 +1,46 @@ +# LocalCaption | Offline Mandarin Live Captions for Deaf and Hard-of-Hearing People + +[简体中文主页 / Chinese home page](README.md) + +LocalCaption is an Android communication aid built specifically for Mandarin Chinese speech recognition. A nearby speaker talks into the phone microphone; on-device streaming ASR turns the speech into large, high-contrast captions for a deaf or hard-of-hearing reader. + +Audio is processed in memory and is neither uploaded nor saved as a recording. Sessions containing text are saved automatically in the local Room database when recognition stops, and individual records can be copied, favorited, or deleted. + +> [!IMPORTANT] +> This is a proof of concept for Android 8.0+ on `arm64-v8a`. Download the signed `v0.5.0-beta.1` prerelease APK from [GitHub Releases](https://github.com/Johnnycn1213/LocalCaption/releases). The new model has not received device validation, so this is not a stable release. LocalCaption is not a medical device and must not be the only communication channel in emergency, medical, or other safety-critical situations. + +## Scope and current limits + +- Recognition is intended for Mandarin Chinese, not multiple languages or Chinese dialects such as Cantonese or Wu. +- “Short-pause mode” and “long-pause mode” use the same Mandarin Zipformer 14M (INT8) model. They differ only in how quickly a pause ends a caption segment; the mode names do not claim different recognition accuracy. +- The app captures nearby microphone audio only. It does not directly capture calls or system media audio. +- Large captions, high contrast, large touch targets, and basic TalkBack semantics are implemented, but accessibility has not received systematic device testing. +- Recognition can continue through a foreground service after pressing Home; removing the app from Recent Apps stops it. +- Existing device evidence is limited to the previous 2025 CTC configuration on a OnePlus PHB110 running Android 16; it does not validate the current 14M Transducer model. There are no WER, latency, noise, accent, power, 30-minute stability, multi-device, or complete TalkBack results. No further device testing is currently available. + +See the [device validation record](docs/device-validation.md) for the exact evidence and limitations. + +## Download and build + +The `v0.5.0-beta.1` GitHub prerelease includes a signed `arm64-v8a` APK as the primary installable file. An AAB may also be attached for store-oriented workflows. Checksums and third-party notices accompany the release artifacts. This prerelease does not claim that the newly migrated model has been tested on a physical device. + +To build from source on Windows PowerShell, run: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\setup-build-toolchain.ps1 +powershell -ExecutionPolicy Bypass -File .\tools\setup-runtime-assets.ps1 +powershell -ExecutionPolicy Bypass -File .\tools\verify-runtime-assets.ps1 +powershell -ExecutionPolicy Bypass -File .\tools\build-debug-apk.ps1 +``` + +The Debug APK is written to `app/build/outputs/apk/debug/app-debug.apk`. + +When the sherpa-onnx AAR is absent, the project uses compile-only stubs under `app/src/stub/java`. CI uses this path to run JVM unit tests, Android Lint, and a Debug build; it does not validate real ASR behavior. + +## Privacy and distribution + +The installed app does not request Internet permission. Runtime microphone audio stays in memory and is not written as PCM, WAV, or another recording format. Preparing the Android toolchain, sherpa-onnx AAR, and Mandarin model for a first source build still requires downloads. + +The release uses `csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23`, whose model repository declares Apache-2.0. It may be redistributed inside the APK/AAB provided that the required copyright attribution, license, and third-party notices accompany the distribution. The reproducible signed-release process runs tests and Release Lint, verifies APK/AAB signatures, and generates SHA-256 checksums. + +See the [license review](docs/license-review.md), [third-party notices](THIRD_PARTY_NOTICES.md), and [signed release guide](docs/release-signing.md). diff --git a/README.md b/README.md index b77a654..2db844b 100644 --- a/README.md +++ b/README.md @@ -1,298 +1,154 @@
-LocalCaption — private, on-device live captions for Android +# LocalCaption|面向听障人士的中文普通话离线实时字幕 -# LocalCaption · 本地实时字幕 +**把身边的普通话,在 Android 手机上实时显示为大字字幕。** -**让每一句话都看得见。** -**Private, on-device live captions for Android.** +本项目只面向中文普通话语音识别,不是多语言字幕应用。 -[简体中文](#简体中文) · [English](#english) +[功能与边界](#功能与边界) · [真机画面](#真机画面) · [自行构建](#自行构建) · [English](README.en.md) ![Android 8.0+](https://img.shields.io/badge/Android-8.0%2B-3DDC84?style=flat-square&logo=android&logoColor=white) -![Kotlin 2.0.21](https://img.shields.io/badge/Kotlin-2.0.21-7F52FF?style=flat-square&logo=kotlin&logoColor=white) -![Jetpack Compose](https://img.shields.io/badge/UI-Jetpack%20Compose-4285F4?style=flat-square&logo=jetpackcompose&logoColor=white) -![Offline first](https://img.shields.io/badge/ASR-Offline--first-12B886?style=flat-square) +![中文普通话](https://img.shields.io/badge/识别语言-中文普通话-D93025?style=flat-square) +![本机识别](https://img.shields.io/badge/音频-本机处理-12B886?style=flat-square) ![arm64-v8a](https://img.shields.io/badge/ABI-arm64--v8a-5C7CFA?style=flat-square) +[![Android 自动化检查](https://github.com/Johnnycn1213/LocalCaption/actions/workflows/android-ci.yml/badge.svg)](https://github.com/Johnnycn1213/LocalCaption/actions/workflows/android-ci.yml)
---- - -## 简体中文 - -LocalCaption 是一款面向听力辅助场景的 Android 离线实时字幕应用。它在手机本地完成音频采集和中文语音识别,将对话持续转换成大字、高对比度字幕;音频不会上传到服务器,也不会保存为录音文件。 +LocalCaption 为听障人士和有听力损失的用户提供面对面沟通辅助:说话者靠近手机麦克风说普通话,应用在手机本地完成流式语音识别,屏幕持续显示高对比度字幕。运行时不上传或保存音频;有文字的会话会自动保存在本机,并可逐条删除。 > [!IMPORTANT] -> 项目目前处于真机 POC 阶段,仅支持 `arm64-v8a`。它是辅助沟通工具,不是医疗器械,也不应作为紧急信息或安全关键场景中的唯一沟通方式。 - -### 为什么选择 LocalCaption - -- **真正离线**:基于 sherpa-onnx 流式 Zipformer CTC,在设备端完成识别。 -- **隐私优先**:不上传音频,不保存 PCM、WAV 或其他录音文件。 -- **双模式识别**:快速模式优先低延迟,精准模式优先识别效果。 -- **无障碍设计**:大字号、高对比、大触控区域、少层级,并提供基础 TalkBack 语义。 -- **记录可控**:每次会话保存为一条纯文本记录,可复制、收藏或删除。 -- **后台可用**:通过麦克风前景服务和持续通知维持识别任务。 +> 当前版本仍处于 POC 阶段,仅支持 `arm64-v8a`。[GitHub Releases](https://github.com/Johnnycn1213/LocalCaption/releases) 提供 `v0.5.0-beta.1` 预发行版的已签名 APK;AAB 可作为附加产物提供。新模型尚未完成真机验证,因此它不是稳定版。LocalCaption 不是医疗器械,也不能作为急救、医疗或其他安全关键场景中的唯一沟通方式。 -### 功能一览 +## 功能与边界 -| 能力 | 当前实现 | +| 项目 | 当前情况 | | --- | --- | -| 实时字幕 | partial 持续刷新,final 结果写入会话 | -| 快速模式 | 约 25 MB Zipformer Small,低延迟优先 | -| 精准模式 | 约 155 MB Zipformer,准确率优先 | -| 字幕显示 | 标准 / 大 / 超大三档字号,自动滚动 | -| 本地记录 | Room 纯文本历史、收藏、复制与删除 | -| 隐私 | 音频仅在内存中处理,不上传、不落盘 | -| 无障碍 | TalkBack 标签、状态播报、清晰的焦点顺序 | -| 系统支持 | Android 8.0+,当前仅构建 `arm64-v8a` | - -### 识别链路 - -```text -麦克风 - └─ AudioRecord · 16 kHz · PCM 16-bit · Mono - └─ sherpa-onnx Streaming Zipformer CTC - ├─ partial → 实时字幕 - └─ final → 会话文本 → Room -``` - -### 快速开始 - -#### 环境要求 - -- Windows PowerShell 5.1 或更高版本 -- 可联网下载 Android 构建工具、sherpa-onnx AAR 与模型 -- 一台 Android 8.0+ 的 arm64 真机 - -仓库提供了完整的本地准备脚本。大体积模型、AAR、Android SDK 和 JDK 都不会提交到 Git: - -```powershell -# 1. 准备 JDK 17、Gradle 8.10.2 和 Android SDK 35 -powershell -ExecutionPolicy Bypass -File .\tools\setup-build-toolchain.ps1 - -# 2. 下载 sherpa-onnx AAR 与快速/精准模型 -powershell -ExecutionPolicy Bypass -File .\tools\setup-runtime-assets.ps1 - -# 3. 检查运行资产 -powershell -ExecutionPolicy Bypass -File .\tools\verify-runtime-assets.ps1 - -# 4. 构建 Debug APK -powershell -ExecutionPolicy Bypass -File .\tools\build-debug-apk.ps1 -``` - -构建完成后,APK 位于: - -```text -app/build/outputs/apk/debug/app-debug.apk -``` - -如已配置 `adb`,可安装到设备: - -```powershell -adb install -r .\app\build\outputs\apk\debug\app-debug.apk -``` - -> [!NOTE] -> 缺少官方 AAR 时,工程会使用 `app/src/stub/java` 中的编译 stub,方便同步和检查 UI;stub 不能执行真实语音识别。 - -### 模型与运行资产 - -运行脚本后,文件应位于以下目录: - -```text -app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar - -app/src/main/assets/ -├─ sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01/ -│ ├─ model.int8.onnx -│ └─ tokens.txt -└─ sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30/ - ├─ model.int8.onnx - └─ tokens.txt -``` - -这些二进制文件体积较大,并可能受各自许可证约束,因此已通过 `.gitignore` 排除。请不要直接提交到源码仓库。 - -### 项目结构 - -```text -app/src/main/java/com/johnny/localcaption/ -├─ asr/ # 模型管理、流式识别、端点检测与终稿修正 -├─ audio/ # AudioRecord 采集与音频分块 -├─ data/ # Room 数据库、DAO 与仓库 -├─ service/ # 前景服务、通知与识别状态 -├─ ui/ # Compose 页面、组件与主题 -└─ util/ # 权限、时间与调度器工具 - -tools/ # 构建工具链、运行资产、校验与 APK 构建脚本 -docs/ # 真机 POC 检查单与项目图片 -``` - -### 隐私说明 +| 识别语言 | 中文普通话;没有针对粤语、吴语等方言或其他语言优化 | +| 实时字幕 | 流式 partial 字幕持续刷新,final 文本写入当前会话 | +| 显示方式 | 标准、大、超大三档字号;高对比度;自动滚动 | +| 识别模式 | “短停顿模式”和“长停顿模式”共用同一套中文普通话 Zipformer 14M(INT8)模型,仅采用不同的停顿切分策略;模式名称不代表准确率高低 | +| 本地记录 | 有文本的会话结束时自动保存到 Room,可复制、收藏或逐条删除 | +| 音频隐私 | 运行时只在内存中处理麦克风音频,不上传、不生成录音文件 | +| 无障碍 | 已实现大触控区域和基础 TalkBack 语义;尚未完成系统化真机验证 | +| 后台行为 | 按 Home 后前景服务可继续;从最近任务中划掉应用会停止识别 | +| 音频来源 | 只采集手机麦克风附近声音,不直接捕获电话或系统媒体音频 | +| 系统支持 | Android 8.0 及以上,目前只构建 `arm64-v8a` | -LocalCaption 默认只在设备本地处理语音。应用不会把音频上传到服务器,也不会保存原始音频、PCM 或 WAV 缓存。用户选择保留的转写文本和元数据存储在本机 Room 数据库中,并可随时删除。 +## 真机画面 -### 当前状态与路线图 +以下画面来自 OnePlus PHB110(Android 16)上的既有离线 POC。该设备完成了 Debug APK 安装、应用启动、旧版 2025 CTC 模型加载和简短普通话出字检查。当前发行版已经迁移到 Apache-2.0 的 14M Transducer 模型;由于已无法继续连接这台设备,本次迁移只完成桌面构建、签名和静态检查,没有完成新模型的真机运行验证。历史画面不能作为当前模型已经通过真机验证的证据,也不能代表识别准确率、复杂环境效果或多机型兼容性。 -- [x] Compose + Material 3 主界面 -- [x] 流式识别、前景服务与持续通知 -- [x] 快速 / 精准双模型切换与模式持久化 -- [x] 历史记录、收藏与字号设置 -- [x] 基础 TalkBack 支持 -- [ ] 完成多机型 30 分钟稳定性与功耗测试 -- [ ] 补充真实设备截图和演示视频 -- [ ] 增加自动化测试与 GitHub Actions -- [ ] 完成依赖、模型及发行包许可证审查 -- [ ] 建立可重复的签名 Release 构建流程 +

+ OnePlus PHB110 上的中文普通话实时字幕 + OnePlus PHB110 上的旧版普通话模型选择 + OnePlus PHB110 上的字幕显示设置 +

-详细真机验证步骤见 [第二阶段 POC 检查单](docs/phase2-poc-checklist.md)。 +

+ 由真实设备截图帧组成的 LocalCaption 演示 +

-### 许可证 +由于该设备的 OxygenOS 阻止 ADB `screenrecord`,上方 GIF 是真实截图帧轮播,不是连续录屏。截图未使用生成式界面或设备模型。详细记录见[真机验证报告](docs/device-validation.md)。 -仓库暂未附加开源许可证。在许可证正式确定前,源码默认保留全部权利。sherpa-onnx、ONNX Runtime 和语音模型分别受其上游许可证与模型卡约束;分发 APK 或模型前,请逐项核验。 - ---- - -## English - -LocalCaption is an offline live-caption app for Android, designed for hearing-assistance scenarios. It captures speech and performs Chinese streaming ASR entirely on the device, presenting the conversation as large, high-contrast captions. Audio is never uploaded or stored as a recording. - -> [!IMPORTANT] -> This project is currently a device-POC and supports `arm64-v8a` only. It is an assistive communication tool, not a medical device, and should not be the sole communication channel for emergencies or safety-critical situations. +目前没有 WER、端到端延迟、噪声、口音、30 分钟稳定性、功耗、多机型或完整 TalkBack 真机数据;这些项目不列为已完成能力。 -### Why LocalCaption +## 为什么在本机识别 -- **Fully on-device** — streaming Zipformer CTC inference powered by sherpa-onnx. -- **Privacy first** — no audio uploads and no PCM, WAV, or recording files written to disk. -- **Two recognition modes** — Quick favors lower latency; Accurate favors recognition quality. -- **Accessible by design** — large type, high contrast, generous touch targets, shallow navigation, and basic TalkBack semantics. -- **User-controlled history** — sessions are stored as plain text and can be copied, favorited, or deleted. -- **Background continuity** — a microphone foreground service keeps recognition active with a persistent notification. +- 应用清单不申请网络权限,识别时不会把音频发送到服务器。 +- 原始音频只用于内存中的流式识别,不写入 PCM、WAV 或其他录音文件。 +- 转写文本和时间等会话信息保存在本机 Room 数据库中。 +- 有文本的会话停止时会自动保存;历史页面支持复制、收藏和逐条删除。 +- 首次准备构建工具、sherpa-onnx AAR 和普通话模型时仍需联网下载文件。 -### Feature overview - -| Capability | Current implementation | -| --- | --- | -| Live captions | Continuously updated partial results and finalized session text | -| Quick mode | ~25 MB Zipformer Small model, optimized for latency | -| Accurate mode | ~155 MB Zipformer model, optimized for accuracy | -| Caption display | Standard / Large / Extra Large text with auto-scroll | -| Local history | Room-backed text history, favorites, copy, and delete | -| Privacy | In-memory audio processing; no upload and no audio persistence | -| Accessibility | TalkBack labels, status announcements, and ordered focus | -| Platform | Android 8.0+; `arm64-v8a` builds only for now | - -### Recognition pipeline +## 中文普通话识别链路 ```text -Microphone - └─ AudioRecord · 16 kHz · PCM 16-bit · Mono - └─ sherpa-onnx Streaming Zipformer CTC - ├─ partial → live caption - └─ final → session text → Room +手机麦克风 + └─ AudioRecord · 16 kHz · PCM 16-bit · 单声道 + └─ sherpa-onnx Streaming Zipformer Transducer 14M(中文普通话) + ├─ partial → 屏幕实时字幕 + └─ final → 会话文本 → Room 本地数据库 ``` -### Quick start +## 自行构建 -#### Requirements +需要直接安装时,请从 [GitHub Releases](https://github.com/Johnnycn1213/LocalCaption/releases) 下载 `v0.5.0-beta.1` 预发行版的已签名 APK。它用于在明确知晓“新模型尚未真机验证”的前提下试用,不是稳定版。仓库同时保留完整的源代码构建路径,开发者可以下载经过 SHA-256 固定的运行资产并自行构建。 -- Windows PowerShell 5.1 or later -- Network access for the Android toolchain, sherpa-onnx AAR, and model downloads -- An arm64 device running Android 8.0 or later +### 环境要求 -The repository includes scripts for a reproducible local setup. Large models, the AAR, Android SDK, and JDK remain outside Git: +- Windows PowerShell 5.1 或更高版本 +- 可联网下载 Android 构建工具、sherpa-onnx AAR 和 14M 中文普通话模型 +- JDK 17、Android SDK 35;也可由仓库脚本准备 ```powershell -# 1. Prepare JDK 17, Gradle 8.10.2, and Android SDK 35 +# 1. 准备 JDK 17、Gradle 8.10.2 和 Android SDK 35 powershell -ExecutionPolicy Bypass -File .\tools\setup-build-toolchain.ps1 -# 2. Download the sherpa-onnx AAR and both ASR models +# 2. 下载 sherpa-onnx AAR 和 14M 中文普通话模型 powershell -ExecutionPolicy Bypass -File .\tools\setup-runtime-assets.ps1 -# 3. Verify runtime assets +# 3. 校验运行资产和 SHA-256 powershell -ExecutionPolicy Bypass -File .\tools\verify-runtime-assets.ps1 -# 4. Build a debug APK +# 4. 构建 Debug APK powershell -ExecutionPolicy Bypass -File .\tools\build-debug-apk.ps1 ``` -The resulting APK is written to: +APK 输出到 `app/build/outputs/apk/debug/app-debug.apk`。 -```text -app/build/outputs/apk/debug/app-debug.apk -``` +> [!NOTE] +> 本地缺少 sherpa-onnx AAR 时,工程会启用 `app/src/stub/java` 中的编译 stub。stub 只用于 CI、界面编译和静态检查,不能执行语音识别。 -Install it with `adb` if available: +## 自动化检查 + +仓库包含 10 个 JVM 单元测试,覆盖端点控制、模型模式恢复、终稿修正和时间格式化。`main` 分支提交与 Pull Request 会运行单元测试、Android Lint 和 Debug 编译;Pull Request 还会执行依赖变更审查。 ```powershell -adb install -r .\app\build\outputs\apk\debug\app-debug.apk +.\gradlew.bat testDebugUnitTest lintDebug assembleDebug ``` -> [!NOTE] -> When the official AAR is missing, the project falls back to compile-only stubs under `app/src/stub/java`. This keeps source and UI checks available, but the stubs cannot perform real speech recognition. - -### Runtime assets - -After setup, the expected local layout is: +GitHub Actions 不下载 AAR 或大模型,因此生成的是编译验证用 stub APK。CI 通过只说明代码、测试、Lint 和 stub 构建通过,不代表真实普通话识别效果。 -```text -app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar - -app/src/main/assets/ -├─ sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01/ -│ ├─ model.int8.onnx -│ └─ tokens.txt -└─ sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30/ - ├─ model.int8.onnx - └─ tokens.txt -``` +## 签名发行与许可证 -These binaries are intentionally excluded by `.gitignore` because of their size and separate licensing requirements. +仓库已经建立可重复的签名 APK/AAB 构建流程,包括单元测试、Release Lint、签名验证和 SHA-256 清单。签名凭据只通过本地环境变量或 GitHub Actions Secrets 注入,不提交到 Git。 -### Project layout +常规 Android/Kotlin 依赖、sherpa-onnx、ONNX Runtime 和随包提供的 14M 中文普通话模型均已完成许可证审查。模型仓库 `csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23` 标注为 Apache-2.0,可随 APK/AAB 再分发;发行包必须同时保留相应的版权归属、许可证与第三方声明。 -```text -app/src/main/java/com/johnny/localcaption/ -├─ asr/ # Model management, streaming ASR, endpointing, correction -├─ audio/ # AudioRecord capture and chunking -├─ data/ # Room database, DAO, and repository -├─ service/ # Foreground service, notification, recognition state -├─ ui/ # Compose screens, components, and theme -└─ util/ # Permissions, time, and dispatcher utilities - -tools/ # Toolchain, runtime-asset, verification, and build scripts -docs/ # Device POC checklist and project artwork -``` +详见[许可证审查](docs/license-review.md)、[第三方声明](THIRD_PARTY_NOTICES.md)和[签名发布流程](docs/release-signing.md)。 -### Privacy +## 项目状态 -LocalCaption processes speech locally by default. It does not upload audio or persist raw audio, PCM, or WAV caches. Transcript text and metadata that the user chooses to keep are stored in the on-device Room database and can be deleted at any time. +- [x] 中文普通话流式识别、前景服务和持续通知 +- [x] 单一 14M 本机普通话模型与两种停顿切分策略 +- [x] 大字字幕、高对比度、本地历史和基础无障碍语义 +- [x] 旧版模型配置在单台 OnePlus PHB110 上的有限链路 POC、真实截图和真实帧 GIF +- [x] JVM 单元测试、Android Lint、GitHub Actions 和依赖审查 +- [x] 依赖、模型、发行包许可证审查 +- [x] 可重复并可验证的签名 APK/AAB 构建流程 +- [ ] 普通话 WER、延迟、噪声与口音基准 +- [ ] 多机型、30 分钟稳定性、功耗和完整 TalkBack 真机验证 -### Status and roadmap +## 项目文档 -- [x] Compose + Material 3 interface -- [x] Streaming recognition, foreground service, and persistent notification -- [x] Quick / Accurate model switching with persisted mode selection -- [x] History, favorites, and caption-size settings -- [x] Basic TalkBack support -- [ ] Complete 30-minute stability and power tests across multiple devices -- [ ] Add real-device screenshots and a demo video -- [ ] Add automated tests and GitHub Actions -- [ ] Review all dependency, model, and distribution licenses -- [ ] Create a reproducible signed release pipeline +- [真机验证事实](docs/device-validation.md) +- [中文普通话真机 POC 检查单](docs/phase2-poc-checklist.md) +- [依赖与发行许可证审查](docs/license-review.md) +- [签名 Release 构建流程](docs/release-signing.md) +- [第三方软件与模型声明](THIRD_PARTY_NOTICES.md) -See the [Phase 2 device POC checklist](docs/phase2-poc-checklist.md) for the current test plan (Chinese). +## English summary -### License +LocalCaption is an offline Android live-caption app built specifically for Mandarin Chinese speech recognition and hearing accessibility. It turns nearby microphone speech into large on-screen captions without uploading or recording audio. Signed APKs are distributed through [GitHub Releases](https://github.com/Johnnycn1213/LocalCaption/releases). The app uses one Apache-2.0-licensed 14M Mandarin model with two pause-segmentation modes; this does not imply an accuracy ranking. -No open-source license has been attached to this repository yet; all rights are reserved until one is selected. sherpa-onnx, ONNX Runtime, and the ASR models are governed by their respective upstream licenses and model cards. Review each one before distributing an APK or model assets. +Read the attached [English introduction](README.en.md) for details. ---
-Built for clearer conversations · 为更清晰的沟通而设计 +为听障沟通而做,专注中文普通话识别。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..d16a075 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,65 @@ +# 第三方软件与中文普通话模型声明 + +LocalCaption 是面向听障人士的离线中文普通话识别与实时字幕应用。本声明必须随公开的 APK/AAB 发行产物一同提供,不得从 Release 中删除。 + +## 中文普通话 Zipformer 14M 模型 + +- 项目:`csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23` +- 贡献者与发布者:`csukuangfj` 及该模型仓库贡献者 +- 用途:本机流式中文普通话语音识别 +- 许可证:Apache License 2.0(模型仓库元数据明确标注 `apache-2.0`) +- 模型来源:https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23 +- 随包许可证全文:[`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt) +- 官方许可证来源:https://www.apache.org/licenses/LICENSE-2.0.txt + +发行包使用该仓库的 INT8 encoder、decoder、joiner 与 `tokens.txt`。应用中的“短停顿模式”和“长停顿模式”共用同一套模型,只调整停顿切分策略。旧的 2025 CTC 模型不属于当前发行包。 + +Apache-2.0 允许复制与再分发,但发行者仍须向接收者提供许可证、保留来源与归属,并标示自己对上游文件所做的修改。本项目不使用模型作者或贡献者的名称为 LocalCaption 背书,也不对识别准确率作出承诺。 + +## sherpa-onnx + +- 版权所有:sherpa-onnx contributors +- 许可证:Apache License 2.0 +- 源代码:https://github.com/k2-fsa/sherpa-onnx +- 随包许可证全文:[`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt) +- 上游许可证:https://github.com/k2-fsa/sherpa-onnx/blob/master/LICENSE + +## ONNX Runtime + +- 版权所有:Copyright (c) Microsoft Corporation +- 许可证:MIT License +- 源代码:https://github.com/microsoft/onnxruntime +- 随包许可证全文:[`LICENSES/MIT.txt`](LICENSES/MIT.txt) +- 上游许可证:https://github.com/microsoft/onnxruntime/blob/main/LICENSE + +## AndroidX + +- 版权所有:Android Open Source Project +- 许可证:Apache License 2.0 +- 源代码:https://android.googlesource.com/platform/frameworks/support/ +- 随包许可证全文:[`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt) + +## Kotlin 与 kotlinx.coroutines + +- 版权所有:JetBrains s.r.o. and Kotlin contributors +- 许可证:Apache License 2.0 +- 源代码: + - https://github.com/JetBrains/kotlin + - https://github.com/Kotlin/kotlinx.coroutines +- 随包许可证全文:[`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt) + +## 发行要求 + +GitHub Release 必须同时提供: + +1. 可直接安装的已签名 APK; +2. `SHA256SUMS.txt`; +3. 本文件 `THIRD_PARTY_NOTICES.md`; +4. `license-review.md`; +5. `LICENSES/Apache-2.0.txt` 与 `LICENSES/MIT.txt` 两份完整许可证文本。 + +AAB 可作为附加产物提供。关于版本、校验和与审查边界,见 `docs/license-review.md`。 + +## English summary + +LocalCaption redistributes the Apache-2.0-licensed `csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23` model for offline Mandarin speech recognition. Both pause-segmentation modes use this one model. Public releases must preserve the model source and attribution and accompany the signed APK with the applicable license texts, third-party notices, and SHA-256 checksums. The previous unlicensed 2025 CTC models are not part of the current release. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index dca6e0a..7ab17e7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,6 +5,22 @@ plugins { alias(libs.plugins.ksp) } +fun secret(name: String): String? { + return providers.gradleProperty(name).orNull?.takeIf { it.isNotBlank() } + ?: System.getenv(name)?.takeIf { it.isNotBlank() } +} + +val releaseStoreFile = secret("LOCALCAPTION_STORE_FILE") +val releaseStorePassword = secret("LOCALCAPTION_STORE_PASSWORD") +val releaseKeyAlias = secret("LOCALCAPTION_KEY_ALIAS") +val releaseKeyPassword = secret("LOCALCAPTION_KEY_PASSWORD") +val hasReleaseSigning = listOf( + releaseStoreFile, + releaseStorePassword, + releaseKeyAlias, + releaseKeyPassword, +).all { it != null } + android { namespace = "com.johnny.localcaption" compileSdk = 35 @@ -14,8 +30,8 @@ android { applicationId = "com.johnny.localcaption" minSdk = 26 targetSdk = 35 - versionCode = 1 - versionName = "0.4.1-mode-persist" + versionCode = 2 + versionName = "0.5.0-beta.1" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" @@ -24,6 +40,21 @@ android { } } + signingConfigs { + if (hasReleaseSigning) { + create("release") { + storeFile = file(releaseStoreFile!!) + storePassword = releaseStorePassword!! + keyAlias = releaseKeyAlias!! + keyPassword = releaseKeyPassword!! + enableV1Signing = true + enableV2Signing = true + enableV3Signing = true + enableV4Signing = true + } + } + } + buildTypes { debug { isMinifyEnabled = false @@ -31,6 +62,9 @@ android { release { isMinifyEnabled = true isShrinkResources = true + if (hasReleaseSigning) { + signingConfig = signingConfigs.getByName("release") + } proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", @@ -91,3 +125,21 @@ dependencies { androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(platform(libs.androidx.compose.bom)) } + +tasks.register("verifyReleaseSigning") { + group = "verification" + description = "Fails unless all release-signing values are configured." + doLast { + check(hasReleaseSigning) { + "Release signing requires LOCALCAPTION_STORE_FILE, LOCALCAPTION_STORE_PASSWORD, " + + "LOCALCAPTION_KEY_ALIAS, and LOCALCAPTION_KEY_PASSWORD." + } + check(file(releaseStoreFile!!).isFile) { + "Release keystore does not exist: $releaseStoreFile" + } + } +} + +tasks.matching { it.name == "assembleRelease" || it.name == "bundleRelease" }.configureEach { + dependsOn("verifyReleaseSigning") +} diff --git a/app/src/main/assets/MODEL_FILES_GO_HERE.txt b/app/src/main/assets/MODEL_FILES_GO_HERE.txt index 1af1e88..e0c4073 100644 --- a/app/src/main/assets/MODEL_FILES_GO_HERE.txt +++ b/app/src/main/assets/MODEL_FILES_GO_HERE.txt @@ -1,13 +1,21 @@ -Place the default high-accuracy model files here: +请把中文普通话流式模型放在以下目录: -app/src/main/assets/sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30/ - model.int8.onnx +app/src/main/assets/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/ + encoder-epoch-99-avg-1.int8.onnx + decoder-epoch-99-avg-1.int8.onnx + joiner-epoch-99-avg-1.int8.onnx tokens.txt -app/src/main/assets/sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01/ - model.int8.onnx - tokens.txt +模型来源: +https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23 +许可证:Apache-2.0 +固定版本:204ad334e2e683fd295359930cc16fc0432a23ac -Native runtime files are packaged by the official static-link AAR. Put it under: +原生运行库请放在: app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar + +建议直接运行 tools/setup-runtime-assets.ps1;脚本会下载固定版本并校验全部 SHA-256。 + +English: Place the pinned Apache-2.0 Mandarin model files and the official +sherpa-onnx AAR at the paths above, or run tools/setup-runtime-assets.ps1. diff --git a/app/src/main/java/com/johnny/localcaption/asr/ModelManager.kt b/app/src/main/java/com/johnny/localcaption/asr/ModelManager.kt index bd8f650..ae07b15 100644 --- a/app/src/main/java/com/johnny/localcaption/asr/ModelManager.kt +++ b/app/src/main/java/com/johnny/localcaption/asr/ModelManager.kt @@ -7,7 +7,7 @@ import com.k2fsa.sherpa.onnx.EndpointRule import com.k2fsa.sherpa.onnx.FeatureConfig import com.k2fsa.sherpa.onnx.OnlineModelConfig import com.k2fsa.sherpa.onnx.OnlineRecognizerConfig -import com.k2fsa.sherpa.onnx.OnlineZipformer2CtcModelConfig +import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig class ModelManager( private val assetManager: AssetManager, @@ -33,8 +33,10 @@ class ModelManager( dither = 0.0f, ), modelConfig = OnlineModelConfig( - zipformer2Ctc = OnlineZipformer2CtcModelConfig( - model = "${mode.modelDir}/model.int8.onnx", + transducer = OnlineTransducerModelConfig( + encoder = "${mode.modelDir}/encoder-epoch-99-avg-1.int8.onnx", + decoder = "${mode.modelDir}/decoder-epoch-99-avg-1.int8.onnx", + joiner = "${mode.modelDir}/joiner-epoch-99-avg-1.int8.onnx", ), tokens = "${mode.modelDir}/tokens.txt", numThreads = mode.numThreads, @@ -54,7 +56,9 @@ class ModelManager( companion object { fun requiredAssets(mode: RecognitionMode) = listOf( - "${mode.modelDir}/model.int8.onnx", + "${mode.modelDir}/encoder-epoch-99-avg-1.int8.onnx", + "${mode.modelDir}/decoder-epoch-99-avg-1.int8.onnx", + "${mode.modelDir}/joiner-epoch-99-avg-1.int8.onnx", "${mode.modelDir}/tokens.txt", ) } diff --git a/app/src/main/java/com/johnny/localcaption/asr/RecognitionMode.kt b/app/src/main/java/com/johnny/localcaption/asr/RecognitionMode.kt index b257c1a..81c32ef 100644 --- a/app/src/main/java/com/johnny/localcaption/asr/RecognitionMode.kt +++ b/app/src/main/java/com/johnny/localcaption/asr/RecognitionMode.kt @@ -8,18 +8,18 @@ enum class RecognitionMode( val numThreads: Int, ) { Quick( - title = "快速模式", - description = "出字更快,适合日常对话", - modelName = "Zipformer Small CTC 25MB", - modelDir = "sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01", + title = "短停顿模式", + description = "较短停顿后分段,适合节奏较快的对话", + modelName = "中文普通话 Zipformer 14M(INT8)", + modelDir = "sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23", numThreads = 4, ), Accurate( - title = "精准模式", - description = "识别更稳,适合重要内容", - modelName = "Zipformer CTC 155MB", - modelDir = "sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30", - numThreads = 3, + title = "长停顿模式", + description = "等待更长停顿后分段,减少短暂停顿造成的断句", + modelName = "中文普通话 Zipformer 14M(INT8)", + modelDir = "sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23", + numThreads = 4, ); companion object { diff --git a/app/src/main/java/com/johnny/localcaption/asr/VadWrapper.kt b/app/src/main/java/com/johnny/localcaption/asr/VadWrapper.kt index 04e79eb..ef4e560 100644 --- a/app/src/main/java/com/johnny/localcaption/asr/VadWrapper.kt +++ b/app/src/main/java/com/johnny/localcaption/asr/VadWrapper.kt @@ -4,7 +4,7 @@ import com.johnny.localcaption.audio.AudioChunk class VadWrapper { fun allow(chunk: AudioChunk): Boolean { - // Phase 1 keeps VAD disabled so real-time behavior comes from the streaming CTC model. + // VAD stays disabled so endpoint behavior comes from the streaming recognizer. return chunk.samples.isNotEmpty() } } diff --git a/app/src/main/java/com/johnny/localcaption/service/RecognitionStateStore.kt b/app/src/main/java/com/johnny/localcaption/service/RecognitionStateStore.kt index 35847db..3b55c21 100644 --- a/app/src/main/java/com/johnny/localcaption/service/RecognitionStateStore.kt +++ b/app/src/main/java/com/johnny/localcaption/service/RecognitionStateStore.kt @@ -25,7 +25,7 @@ object RecognitionStateStore { modeTitle = mode.title, modelName = mode.modelName, ) - announce("${mode.title},正在监听麦克风") + announce("${mode.title},正在聆听普通话语音") } fun updatePartial(text: String) { @@ -49,7 +49,7 @@ object RecognitionStateStore { latestSegmentEndedAtMillis = endedAtMillis, ) } - announce("已生成一段最终转写") + announce("已生成一段普通话字幕") } fun stop() { @@ -60,7 +60,7 @@ object RecognitionStateStore { isRunning = false, ) } - announce("已停止实时字幕") + announce("已停止普通话实时字幕") } fun error(message: String) { diff --git a/app/src/main/java/com/johnny/localcaption/service/RecognitionUiState.kt b/app/src/main/java/com/johnny/localcaption/service/RecognitionUiState.kt index 157c7f8..dcd48de 100644 --- a/app/src/main/java/com/johnny/localcaption/service/RecognitionUiState.kt +++ b/app/src/main/java/com/johnny/localcaption/service/RecognitionUiState.kt @@ -16,6 +16,6 @@ data class RecognitionUiState( val isRunning: Boolean = false, val startedAtMillis: Long? = null, val latestSegmentEndedAtMillis: Long? = null, - val modeTitle: String = "快速模式", - val modelName: String = "Zipformer Small CTC 25MB", + val modeTitle: String = "短停顿模式", + val modelName: String = "中文普通话 Zipformer 14M(INT8)", ) diff --git a/app/src/main/java/com/johnny/localcaption/ui/component/RecordingControls.kt b/app/src/main/java/com/johnny/localcaption/ui/component/RecordingControls.kt index c2d986c..5ccd17c 100644 --- a/app/src/main/java/com/johnny/localcaption/ui/component/RecordingControls.kt +++ b/app/src/main/java/com/johnny/localcaption/ui/component/RecordingControls.kt @@ -28,7 +28,7 @@ fun RecordingControls( .heightIn(min = 60.dp) .semantics { contentDescription = label - stateDescription = if (isRunning) "当前正在实时转写" else "当前未开始" + stateDescription = if (isRunning) "正在将普通话语音转为字幕" else "普通话识别尚未开始" }, ) { Text(label, fontSize = 20.sp, fontWeight = FontWeight.Bold) diff --git a/app/src/main/java/com/johnny/localcaption/ui/component/StatusBanner.kt b/app/src/main/java/com/johnny/localcaption/ui/component/StatusBanner.kt index 45b5c48..da7148e 100644 --- a/app/src/main/java/com/johnny/localcaption/ui/component/StatusBanner.kt +++ b/app/src/main/java/com/johnny/localcaption/ui/component/StatusBanner.kt @@ -32,7 +32,7 @@ fun StatusBanner( Surface( modifier = modifier .fillMaxWidth() - .semantics { contentDescription = "实时字幕,当前状态:$statusText" }, + .semantics { contentDescription = "普通话实时字幕,当前状态:$statusText" }, color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.large, ) { @@ -40,7 +40,7 @@ fun StatusBanner( modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, ) { - Text("实时字幕", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("普通话实时字幕", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) Text(statusText, style = MaterialTheme.typography.bodyMedium) } } diff --git a/app/src/main/java/com/johnny/localcaption/ui/screen/HomeScreen.kt b/app/src/main/java/com/johnny/localcaption/ui/screen/HomeScreen.kt index 1ae4e8c..d0100fe 100644 --- a/app/src/main/java/com/johnny/localcaption/ui/screen/HomeScreen.kt +++ b/app/src/main/java/com/johnny/localcaption/ui/screen/HomeScreen.kt @@ -219,9 +219,9 @@ private fun CompactStatusHeader( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp), ) { - Text("实时字幕", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Text("中文普通话实时字幕", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) Text( - "全部离线处理,不保存音频", + "离线识别普通话,不保存音频", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -313,7 +313,7 @@ private fun LiveCaptionPanel( modifier = modifier .fillMaxWidth() .semantics { - contentDescription = "实时字幕内容" + contentDescription = "中文普通话实时字幕内容" }, shape = RoundedCornerShape(24.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), @@ -324,7 +324,7 @@ private fun LiveCaptionPanel( .padding(18.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { - Text("实时字幕", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("字幕内容", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) if (!hasText) { Box( @@ -332,7 +332,11 @@ private fun LiveCaptionPanel( contentAlignment = Alignment.Center, ) { Text( - "点击下方按钮开始实时字幕", + if (state.isRunning) { + "正在聆听,请说普通话" + } else { + "点击下方按钮开始普通话字幕" + }, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, @@ -448,7 +452,7 @@ private fun RecognitionModeSheet( ) { Text("识别模式", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) Text( - if (recognitionRunning) "实时字幕运行中,停止后可切换模式。" else "选择速度或准确率优先。", + if (recognitionRunning) "实时字幕运行中,停止后可切换模式。" else "选择普通话字幕的停顿分段方式。", color = MaterialTheme.colorScheme.onSurfaceVariant, ) RecognitionMode.entries.forEach { mode -> @@ -551,15 +555,12 @@ private enum class SettingsSheet { } private fun RecognitionMode.compactModelName(): String { - return when (this) { - RecognitionMode.Quick -> "Zipformer Small" - RecognitionMode.Accurate -> "Zipformer 155MB" - } + return "Zipformer 14M" } private fun RecognitionMode.userFacingDescription(): String { return when (this) { - RecognitionMode.Quick -> "使用 25MB Zipformer Small,低延迟。" - RecognitionMode.Accurate -> "使用 155MB 模型,准确率优先。" + RecognitionMode.Quick -> "使用同一普通话模型,短暂停顿后尽快完成一段字幕。" + RecognitionMode.Accurate -> "使用同一普通话模型,等待更长停顿,减少短暂停顿造成的断句。" } } diff --git a/app/src/main/java/com/johnny/localcaption/ui/screen/SettingsScreen.kt b/app/src/main/java/com/johnny/localcaption/ui/screen/SettingsScreen.kt index 9e2c2a0..5d8780b 100644 --- a/app/src/main/java/com/johnny/localcaption/ui/screen/SettingsScreen.kt +++ b/app/src/main/java/com/johnny/localcaption/ui/screen/SettingsScreen.kt @@ -56,7 +56,7 @@ fun SettingsScreen( SettingsSection(title = "识别模式") { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( - if (recognitionRunning) "实时字幕运行中,停止后可切换模式。" else "选择速度或准确率优先。", + if (recognitionRunning) "实时字幕运行中,停止后可切换模式。" else "选择普通话字幕的停顿分段方式。", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -75,7 +75,7 @@ fun SettingsScreen( item { SettingsSection(title = "隐私") { Text( - "全部离线处理,不保存音频。", + "中文普通话在设备上离线识别,不上传或保存音频。", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 52c2edc..f3186df 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,10 +1,10 @@ - 本地实时字幕 + 普通话实时字幕 开始实时字幕 停止实时字幕 - 正在监听麦克风 - 正在识别 + 正在聆听普通话语音 + 正在识别普通话 未开始 暂无转写记录 已收藏 @@ -15,14 +15,14 @@ 超大 麦克风权限被拒绝 请前往系统设置开启麦克风权限 - 实时字幕 + 中文普通话实时字幕 历史记录 收藏夹 收藏 取消收藏 删除 复制文本 - 全部离线处理,不保存音频 - 实时字幕服务 - 正在运行实时字幕 + 中文普通话离线识别,不保存音频 + 普通话实时字幕服务 + 正在识别普通话并生成字幕 diff --git a/app/src/stub/java/com/k2fsa/sherpa/onnx/SherpaOnnxStubs.kt b/app/src/stub/java/com/k2fsa/sherpa/onnx/SherpaOnnxStubs.kt index 6829373..e84ce51 100644 --- a/app/src/stub/java/com/k2fsa/sherpa/onnx/SherpaOnnxStubs.kt +++ b/app/src/stub/java/com/k2fsa/sherpa/onnx/SherpaOnnxStubs.kt @@ -24,7 +24,14 @@ data class OnlineZipformer2CtcModelConfig( var model: String = "", ) +data class OnlineTransducerModelConfig( + var encoder: String = "", + var decoder: String = "", + var joiner: String = "", +) + data class OnlineModelConfig( + var transducer: OnlineTransducerModelConfig = OnlineTransducerModelConfig(), var zipformer2Ctc: OnlineZipformer2CtcModelConfig = OnlineZipformer2CtcModelConfig(), var tokens: String = "", var numThreads: Int = 2, @@ -47,8 +54,8 @@ data class OnlineRecognizerResult( ) class OnlineStream { - fun acceptWaveform(samples: FloatArray, sampleRate: Int) = missingRuntime() - fun inputFinished() = missingRuntime() + fun acceptWaveform(samples: FloatArray, sampleRate: Int): Unit = missingRuntime() + fun inputFinished(): Unit = missingRuntime() fun release() = Unit } diff --git a/app/src/test/kotlin/com/johnny/localcaption/asr/EndpointControllerTest.kt b/app/src/test/kotlin/com/johnny/localcaption/asr/EndpointControllerTest.kt new file mode 100644 index 0000000..235bf93 --- /dev/null +++ b/app/src/test/kotlin/com/johnny/localcaption/asr/EndpointControllerTest.kt @@ -0,0 +1,41 @@ +package com.johnny.localcaption.asr + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class EndpointControllerTest { + private val controller = EndpointController() + + @Test + fun `persists a non-empty final result at an endpoint`() { + val update = RecognitionUpdate( + partialText = "", + finalText = "测试完成", + endpointReached = true, + ) + + assertTrue(controller.shouldPersist(update)) + } + + @Test + fun `does not persist partial results`() { + val update = RecognitionUpdate( + partialText = "正在识别", + endpointReached = false, + ) + + assertFalse(controller.shouldPersist(update)) + } + + @Test + fun `does not persist a blank final result`() { + val update = RecognitionUpdate( + partialText = "", + finalText = " ", + endpointReached = true, + ) + + assertFalse(controller.shouldPersist(update)) + } +} diff --git a/app/src/test/kotlin/com/johnny/localcaption/asr/RecognitionModeTest.kt b/app/src/test/kotlin/com/johnny/localcaption/asr/RecognitionModeTest.kt new file mode 100644 index 0000000..c5574a2 --- /dev/null +++ b/app/src/test/kotlin/com/johnny/localcaption/asr/RecognitionModeTest.kt @@ -0,0 +1,24 @@ +package com.johnny.localcaption.asr + +import org.junit.Assert.assertEquals +import org.junit.Test + +class RecognitionModeTest { + @Test + fun `restores a persisted mode`() { + assertEquals(RecognitionMode.Accurate, RecognitionMode.fromName("Accurate")) + } + + @Test + fun `falls back to quick mode for missing or unknown values`() { + assertEquals(RecognitionMode.Quick, RecognitionMode.fromName(null)) + assertEquals(RecognitionMode.Quick, RecognitionMode.fromName("unknown")) + } + + @Test + fun `modes share the same Mandarin model and runtime settings`() { + assertEquals(RecognitionMode.Quick.modelDir, RecognitionMode.Accurate.modelDir) + assertEquals(RecognitionMode.Quick.modelName, RecognitionMode.Accurate.modelName) + assertEquals(RecognitionMode.Quick.numThreads, RecognitionMode.Accurate.numThreads) + } +} diff --git a/app/src/test/kotlin/com/johnny/localcaption/asr/SecondPassCorrectorTest.kt b/app/src/test/kotlin/com/johnny/localcaption/asr/SecondPassCorrectorTest.kt new file mode 100644 index 0000000..11c5c0c --- /dev/null +++ b/app/src/test/kotlin/com/johnny/localcaption/asr/SecondPassCorrectorTest.kt @@ -0,0 +1,22 @@ +package com.johnny.localcaption.asr + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SecondPassCorrectorTest { + @Test + fun `normalizes whitespace phrases and Chinese punctuation`() { + val result = SecondPassCorrector().correct( + " sherpa onnx , zip former ! ", + ) + + assertEquals("sherpa-onnx, Zipformer!", result) + } + + @Test + fun `supports a custom correction dictionary`() { + val corrector = SecondPassCorrector(mapOf("本地字幕" to "LocalCaption")) + + assertEquals("LocalCaption。", corrector.correct("本地字幕.")) + } +} diff --git a/app/src/test/kotlin/com/johnny/localcaption/util/TimeUtilsTest.kt b/app/src/test/kotlin/com/johnny/localcaption/util/TimeUtilsTest.kt new file mode 100644 index 0000000..3dd608e --- /dev/null +++ b/app/src/test/kotlin/com/johnny/localcaption/util/TimeUtilsTest.kt @@ -0,0 +1,18 @@ +package com.johnny.localcaption.util + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TimeUtilsTest { + @Test + fun `formats elapsed time to one decimal place`() { + assertEquals("1.5 秒", TimeUtils.durationSeconds(1_000, 2_500)) + } + + @Test + fun `returns zero for incomplete or reversed ranges`() { + assertEquals("0.0 秒", TimeUtils.durationSeconds(null, 2_000)) + assertEquals("0.0 秒", TimeUtils.durationSeconds(2_000, null)) + assertEquals("0.0 秒", TimeUtils.durationSeconds(2_000, 1_000)) + } +} diff --git a/docs/assets/device/oneplus-phb110-demo.gif b/docs/assets/device/oneplus-phb110-demo.gif new file mode 100644 index 0000000..df05b69 Binary files /dev/null and b/docs/assets/device/oneplus-phb110-demo.gif differ diff --git a/docs/assets/device/oneplus-phb110-home.png b/docs/assets/device/oneplus-phb110-home.png new file mode 100644 index 0000000..46613cd Binary files /dev/null and b/docs/assets/device/oneplus-phb110-home.png differ diff --git a/docs/assets/device/oneplus-phb110-live-caption.png b/docs/assets/device/oneplus-phb110-live-caption.png new file mode 100644 index 0000000..9b732fc Binary files /dev/null and b/docs/assets/device/oneplus-phb110-live-caption.png differ diff --git a/docs/assets/device/oneplus-phb110-mode-sheet.png b/docs/assets/device/oneplus-phb110-mode-sheet.png new file mode 100644 index 0000000..df17dda Binary files /dev/null and b/docs/assets/device/oneplus-phb110-mode-sheet.png differ diff --git a/docs/assets/device/oneplus-phb110-settings.png b/docs/assets/device/oneplus-phb110-settings.png new file mode 100644 index 0000000..3a1a185 Binary files /dev/null and b/docs/assets/device/oneplus-phb110-settings.png differ diff --git a/docs/device-validation.md b/docs/device-validation.md new file mode 100644 index 0000000..10bd6d3 --- /dev/null +++ b/docs/device-validation.md @@ -0,0 +1,41 @@ +# 中文普通话实时字幕真机验证 + +本项目面向听障人群,在 Android 设备上提供离线中文普通话语音识别与实时字幕。本页仅记录已经完成的单机 POC 事实,不将单台设备的结果外推为多机型兼容性、识别准确率、无障碍效果或性能结论。当前已无法继续使用该实机,因此不会安排或暗示已完成新的真机验证。 + +验证日期:2026-07-23 + +> [!IMPORTANT] +> 本页记录的是迁移前 2025 CTC 模型配置的历史 POC。当前 Release 已改用 Apache-2.0 的 `sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23` Transducer 模型;由于实机已无法连接,新模型只完成桌面构建、签名和静态验证,未做新的真机运行验证。以下旧配置结果不得外推为当前模型已经通过真机验证。 + +| 验证项 | 结果 | +| --- | --- | +| 设备 | OnePlus PHB110 | +| Android 版本 | Android 16 | +| ABI | `arm64-v8a` | +| 当时使用的模型配置 | 旧版 2025 CTC 模型,不是当前 14M Transducer 模型 | +| Debug APK 安装 | 通过;使用 `adb install -r` | +| 应用启动 | 通过 | +| 旧版大模型启动(当时界面称“精准模式”) | 通过 | +| 实时识别状态 | 通过 | +| 真机观察到的中文转写 | `那` / `那呢` | +| Debug APK SHA-256 | `c551d4b985d7634a52dcf88c046c0278b1c04db42c5b9eea2229e1981652b3d2` | +| 30 分钟多机型稳定性与功耗测试 | 未执行;当前无可用实机 | +| 性能、功耗与无障碍效果的真机量化验证 | 未执行 | + +## 验证边界 + +现有证据只能说明上述旧配置 Debug APK 曾在一台 OnePlus PHB110 上完成安装、启动、模型启动并观察到短文本转写。它不能证明当前 14M Transducer 模型在这台设备上可运行。尚未执行多机型覆盖、连续 30 分钟运行、耗电与温升测量、识别延迟统计、准确率评测,也未邀请听障用户进行可用性或无障碍效果验证。后续若重新具备合适的设备与测试参与条件,应另行制定测试方案;本次项目收尾不把这些未完成项计为已验证能力。 + +## 真机截图与演示 + +- `oneplus-phb110-home.png` — 中文实时字幕待机界面 +- `oneplus-phb110-live-caption.png` — 真机离线中文普通话识别结果 +- `oneplus-phb110-mode-sheet.png` — 识别模式选择界面 +- `oneplus-phb110-settings.png` — 无障碍与模型设置界面 +- `oneplus-phb110-demo.gif` — 仅使用上述真机截图制作、可直接在 GitHub 展示的动态演示 + +该设备的 OxygenOS 安全策略拒绝了 ADB `screenrecord`,返回 `Permission denied`;系统录屏授权界面也不会暴露给 ADB 截图。因此,仓库使用基于真实设备截图制作的动态演示,不包含模拟界面或生成式截图。 + +## 英文摘要 + +LocalCaption completed a limited single-device proof of concept on one OnePlus PHB110 using the previous 2025 CTC model configuration. The current release uses a different Apache-2.0 Mandarin Zipformer 14M Transducer model and has received desktop build, signing, and static validation only; it has not been run on the unavailable device. Multi-device, 30-minute, performance, power, accessibility, and user-outcome validation were not performed. diff --git a/docs/license-review.md b/docs/license-review.md new file mode 100644 index 0000000..61d1095 --- /dev/null +++ b/docs/license-review.md @@ -0,0 +1,60 @@ +# 中文普通话语音识别项目依赖与发行许可证审查 + +审查更新日期:2026-08-01 + +审查范围:源代码依赖、Android 运行时 AAR、随发行包提供的中文普通话 ASR 模型,以及 APK/AAB 分发。 + +> 本文是工程合规审查记录,不构成法律意见。 + +## 审查结论 + +**当前使用的 14M 中文普通话模型可随签名 APK/AAB 公开分发,不再需要“另行取得模型再分发权利”的人工确认闸门。** + +项目已统一使用 `csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23`。该模型仓库的许可证元数据明确标注为 Apache-2.0,因此允许复制和再分发,包括放入公开的 APK/AAB。发行时必须保留模型来源和作者归属,并随发行产物提供 Apache-2.0 许可证及本项目的第三方声明。 + +旧的两套无明确再分发条款模型不再用于当前实现,也不得误放入发行包。运行时资源校验脚本固定实际模型文件的 SHA-256;签名 Release 工作流在构建前执行校验,避免混入未审查资产。 + +## 已审查组件 + +| 组件 | 版本或来源 | 许可证审查结果 | 发行处理 | +| --- | --- | --- | --- | +| sherpa-onnx Android AAR | `1.13.4`,k2-fsa release | Apache-2.0 | 保留上游归属与 Apache-2.0 许可证 | +| ONNX Runtime(静态链接在 AAR 中) | 由 sherpa-onnx 捆绑 | MIT | 保留 Microsoft 版权与 MIT 许可证 | +| Kotlin / Kotlin Gradle plugin | `2.0.21` | Apache-2.0 | 保留声明 | +| KSP | `2.0.21-1.0.27` | Apache-2.0 | 仅构建时使用 | +| Android Gradle Plugin | `8.7.3` | Apache-2.0 | 仅构建时使用 | +| Gradle Wrapper/distribution | `8.10.2` | Apache-2.0 | 仅构建时使用;校验和已固定 | +| AndroidX Core、Activity、Lifecycle、Room、Compose、Test | 版本见 `libs.versions.toml` | Apache-2.0 | 保留 AndroidX 声明 | +| kotlinx.coroutines | `1.9.0` | Apache-2.0 | 保留声明 | +| JUnit 4 | `4.13.2` | EPL-1.0 | 仅测试使用,不打包进 Release APK | +| 中文普通话 ASR 模型 | `csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23` | Apache-2.0;模型仓库元数据已明确标注 | 可随 APK/AAB 再分发;保留模型来源、归属、许可证和第三方声明 | +| LocalCaption 源代码与美术资源 | 本仓库 | 尚未选择公开项目许可证 | 不影响项目所有者发布二进制;第三方不得据此推定获得源代码再许可 | + +## 已核查的一手来源 + +- [14M 中文普通话模型仓库与 Apache-2.0 元数据](https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23) +- [模型文件清单](https://huggingface.co/csukuangfj/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/tree/main) +- [Apache License 2.0 全文](https://www.apache.org/licenses/LICENSE-2.0) +- [sherpa-onnx 许可证](https://github.com/k2-fsa/sherpa-onnx/blob/master/LICENSE) +- [ONNX Runtime 许可证](https://github.com/microsoft/onnxruntime/blob/main/LICENSE) +- [AndroidX 源代码仓库](https://android.googlesource.com/platform/frameworks/support/) +- [Android Gradle Plugin 源代码与许可证](https://android.googlesource.com/platform/tools/base/) +- [Gradle 许可证](https://github.com/gradle/gradle/blob/master/LICENSE) +- [Kotlin 许可证](https://github.com/JetBrains/kotlin/blob/master/license/LICENSE.txt) +- [kotlinx.coroutines 许可证](https://github.com/Kotlin/kotlinx.coroutines/blob/master/LICENSE.txt) +- [KSP 许可证](https://github.com/google/ksp/blob/main/LICENSE) +- [JUnit 4 许可证](https://github.com/junit-team/junit4/blob/main/LICENSE-junit.txt) + +## 每次公开发行必须满足 + +1. 发行包只包含当前已审查的 14M 中文普通话模型,不包含旧模型或其他未审查模型。 +2. 通过 `tools/verify-runtime-assets.ps1` 核对 AAR 与全部模型文件的 SHA-256。 +3. 随 Release 提供 `THIRD_PARTY_NOTICES.md`、`license-review.md` 和 `SHA256SUMS.txt`;不得删除模型来源、Apache-2.0 许可证或必需归属。 +4. 完成 Release 单元测试、Lint、APK/AAB 签名和签名验证。 +5. GitHub Release 至少提供可直接安装的已签名 APK;AAB 可作为附加产物提供。 + +Apache-2.0 许可解决的是复制与分发权利,不代表识别准确率、适用场景或训练数据质量得到本项目背书。项目仍需如实保留 POC、设备覆盖和安全用途限制。 + +## English summary + +The release now uses one Mandarin Zipformer 14M model whose repository explicitly declares Apache-2.0. It may be redistributed in signed APK/AAB files when the model attribution, Apache-2.0 license, third-party notices, and verified checksums accompany the release. The previous manual “separately obtained model rights” gate is no longer required. diff --git a/docs/phase2-poc-checklist.md b/docs/phase2-poc-checklist.md index 96310ea..e63f110 100644 --- a/docs/phase2-poc-checklist.md +++ b/docs/phase2-poc-checklist.md @@ -1,4 +1,6 @@ -# 第二阶段真机 POC 检查单 +# 中文普通话真机 POC 检查单 + +> 当前没有可用实机,本次 `v0.5.0-beta.1` 发布不执行本检查单。本文仅保留为以后重新具备设备条件时的验证模板,任何未执行项目都不得记为已通过。 ## 运行资产 @@ -8,13 +10,13 @@ powershell -ExecutionPolicy Bypass -File .\tools\verify-runtime-assets.ps1 ``` -期望三项均为 `OK`: +期望以下五项均为 `OK`: - `app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar` -- `app/src/main/assets/sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30/model.int8.onnx` -- `app/src/main/assets/sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30/tokens.txt` -- `app/src/main/assets/sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01/model.int8.onnx` -- `app/src/main/assets/sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01/tokens.txt` +- `app/src/main/assets/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/encoder-epoch-99-avg-1.int8.onnx` +- `app/src/main/assets/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/decoder-epoch-99-avg-1.int8.onnx` +- `app/src/main/assets/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/joiner-epoch-99-avg-1.int8.onnx` +- `app/src/main/assets/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23/tokens.txt` ## 构建 @@ -29,15 +31,15 @@ powershell -ExecutionPolicy Bypass -File .\tools\verify-runtime-assets.ps1 ## 首次启动 1. 安装 Debug APK。 -2. 打开应用,确认主屏显示“本地实时字幕”。 -3. 点击“开始实时转写”。 +2. 打开应用,确认主屏显示“普通话实时字幕”。 +3. 点击“开始实时字幕”。 4. 授权麦克风权限。 5. Android 13 及以上授权通知权限。 -6. 确认系统通知栏出现“正在实时转写”常驻通知。 +6. 确认系统通知栏出现普通话实时字幕常驻通知。 ## 识别链路 -1. 正常说一段中文,例如“大家好,我们正在测试本地实时字幕”。 +1. 使用标准中文普通话说一段话,例如“大家好,我们正在测试普通话实时字幕”。当前版本不验证方言或其他语言。 2. 观察临时字幕区域是否持续更新 partial。 3. 停顿 1 到 3 秒,观察最终字幕区域是否出现 final。 4. 停止转写,打开历史记录,确认本次开始到停止的整段文本只生成一条历史。 diff --git a/docs/release-signing.md b/docs/release-signing.md new file mode 100644 index 0000000..0c73759 --- /dev/null +++ b/docs/release-signing.md @@ -0,0 +1,98 @@ +# 中文普通话实时字幕签名发布流程 + +## 发布结论 + +LocalCaption 面向听障人士提供离线中文普通话识别与实时字幕。项目使用单一 Apache-2.0 中文普通话 Zipformer 14M(INT8)模型,本地和 GitHub Actions 两条路径都可生成可公开分发的签名 APK/AAB。 + +本次发布目标为 `v0.5.0-beta.1` 预发行版,至少提供一个可直接安装的 `arm64-v8a` 签名 APK。AAB 可一并附带,供应用商店或后续分发流程使用。新模型尚未完成真机验证,因此不得把该版本标为稳定版。两条构建路径都会执行运行资产 SHA-256 校验、单元测试、Release Lint、APK/AAB 构建、签名验证和发行文件校验和生成。 + +模型仓库已经明确标注 Apache-2.0,因此不再设置“另行取得模型权利”的人工确认项。发行者仍必须随包保留模型归属、许可证与 `THIRD_PARTY_NOTICES.md`。 + +## 创建上传密钥 + +推荐按照 [Android 官方签名文档](https://developer.android.com/studio/publish/app-signing)创建独立的上传密钥,并使用 Play App Signing 管理正式应用签名密钥。 + +```powershell +keytool -genkeypair ` + -keystore .secrets/localcaption-upload.jks ` + -alias localcaption-upload ` + -keyalg RSA ` + -keysize 4096 ` + -validity 10000 +``` + +`.secrets/`、`*.jks` 和 `*.keystore` 已被 Git 忽略。不要把私钥或密码提交到仓库。 + +## 本地构建与验证 + +先准备并校验 sherpa-onnx AAR 与 14M 中文普通话模型,再设置签名变量: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\setup-runtime-assets.ps1 + +$env:LOCALCAPTION_STORE_FILE = ".secrets/localcaption-upload.jks" +$env:LOCALCAPTION_STORE_PASSWORD = "" +$env:LOCALCAPTION_KEY_ALIAS = "localcaption-upload" +$env:LOCALCAPTION_KEY_PASSWORD = "" +``` + +仅验证构建、签名和校验链路,不生成公开发行目录: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\build-signed-release.ps1 ` + -PrivateValidationOnly +``` + +生成可公开发布的发行目录: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\build-signed-release.ps1 ` + -PublicRelease +``` + +公开发行输出包括: + +```text +dist/release/ +├─ LocalCaption-release.apk +├─ LocalCaption-release.aab +├─ SHA256SUMS.txt +├─ THIRD_PARTY_NOTICES.md +├─ license-review.md +├─ Apache-2.0.txt +└─ MIT.txt +``` + +其中 APK 是 GitHub Release 必须提供的直接安装文件;AAB 是可选的附加发行格式。`SHA256SUMS.txt` 用于核对下载文件,许可证审查和第三方声明必须与二进制一起保留。 + +## GitHub Actions 签名密钥 + +在仓库 `Settings → Secrets and variables → Actions` 中配置: + +| Secret | 内容 | +| --- | --- | +| `RELEASE_KEYSTORE_BASE64` | JKS 文件的 Base64 内容 | +| `RELEASE_STORE_PASSWORD` | keystore 密码 | +| `RELEASE_KEY_ALIAS` | 上传密钥别名 | +| `RELEASE_KEY_PASSWORD` | 上传密钥密码 | + +Windows 可用以下命令生成 Base64: + +```powershell +[Convert]::ToBase64String( + [IO.File]::ReadAllBytes(".secrets/localcaption-upload.jks") +) | Set-Clipboard +``` + +随后从 Actions 页面手动运行 **中文普通话 Android 签名发布**: + +1. 填写唯一的 Release 标签;本次使用 `v0.5.0-beta.1`。 +2. 保持“发布为 GitHub Release”为启用状态。 +3. 工作流下载并校验 AAR 与 14M 模型,构建和验证签名产物。 +4. 工作流上传短期 Actions artifact,并创建包含签名 APK、AAB、SHA-256 清单和许可证文件的 GitHub 预发行版。 + +工作流不会在普通 push 或 pull request 中接触签名密钥。公开 Release 不依赖任何实机步骤;当前无法进行的新实机验证不阻塞发行,但既有单机 POC 的限制必须继续如实披露。 + +## English summary + +LocalCaption provides reproducible local and GitHub-hosted signed builds for its offline Mandarin live-caption app. The release uses one Apache-2.0 Mandarin Zipformer 14M model, so no separate model-rights confirmation is required. Every public GitHub Release must include a signed APK; an AAB may also be attached. Tests, Release Lint, runtime checksums, signature verification, and third-party notices remain mandatory. diff --git a/docs/releases/v0.5.0-beta.1.md b/docs/releases/v0.5.0-beta.1.md new file mode 100644 index 0000000..55d9df2 --- /dev/null +++ b/docs/releases/v0.5.0-beta.1.md @@ -0,0 +1,46 @@ +# LocalCaption v0.5.0-beta.1|中文普通话实时字幕预发行版 + +这是首个提供可安装 APK 的 GitHub 预发行版。LocalCaption 面向听障人士和有听力损失的用户,把手机麦克风附近的中文普通话实时显示为大字字幕;识别在设备本地完成,不上传或保存音频。 + +## 下载与安装 + +下载 `LocalCaption-release.apk`,在 Android 8.0 及以上的 `arm64-v8a` 设备上安装。首次启动时需要授予麦克风权限;Android 13 及以上还会请求通知权限。 + +同时提供: + +- `LocalCaption-release.aab`:供后续应用商店发布使用的签名 App Bundle。 +- `SHA256SUMS.txt`:APK 与 AAB 的 SHA-256 校验值。 +- `THIRD_PARTY_NOTICES.md`:第三方软件、模型署名与许可证。 +- `license-review.md`:本次发行的许可证审查记录。 +- `Apache-2.0.txt` 与 `MIT.txt`:随发行包提供的许可证全文。 + +Windows PowerShell 校验示例: + +```powershell +Get-FileHash -Algorithm SHA256 .\LocalCaption-release.apk +``` + +请将结果与 `SHA256SUMS.txt` 中的 APK 记录逐字比对。 + +## 本版内容 + +- 中文普通话流式语音识别与大字、高对比度字幕。 +- 使用明确标注 Apache-2.0 的 14M 中文 Zipformer 模型,可随发行包再分发。 +- 短停顿与长停顿两种分段方式;两者使用同一个模型,不代表准确率高低。 +- 本机文本历史、复制、收藏、逐条删除与三档字幕字号。 +- 普通话语境的中文界面、通知和基础 TalkBack 语义。 +- 完整单元测试、Android Lint、签名校验和 SHA-256 产物清单。 + +## 预发行说明 + +本版迁移到了许可证清晰的新模型,但当前无法继续连接实机验证,因此只完成了无实机的代码测试、构建、Lint 和签名验证。仓库中的 OnePlus PHB110 截图来自旧模型配置,只能作为历史界面和链路记录,不能证明本版模型已经在该设备上运行。 + +尚未完成普通话 WER、端到端延迟、噪声与口音基准,以及多机型、30 分钟稳定性、功耗和完整 TalkBack 真机验证。请勿把本应用作为急救、医疗或其他安全关键场景中的唯一沟通方式。 + +## 隐私 + +应用不申请网络权限。麦克风音频只在内存中用于识别,不生成 PCM、WAV 或其他录音文件;有文字的会话停止时会自动保存在本机,可在历史页面逐条删除。 + +## English summary + +This is the first installable prerelease of LocalCaption, an offline Android live-caption app for Mandarin Chinese and hearing accessibility. It ships an Apache-2.0-licensed 14M Mandarin model. The new model has passed non-device tests, builds, lint, signing verification, and checksum generation, but could not receive a new physical-device test; treat this build as beta software. diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..65d16d5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +distributionSha256Sum=31c55713e40233a8303827ceb42ca48a47267a0ad4bab9177123121e71524c26 +networkTimeout=60000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/tools/build-signed-release.ps1 b/tools/build-signed-release.ps1 new file mode 100644 index 0000000..be87e6d --- /dev/null +++ b/tools/build-signed-release.ps1 @@ -0,0 +1,137 @@ +param( + [Alias("ConfirmModelDistributionRights")] + [switch]$PublicRelease, + [switch]$PrivateValidationOnly +) + +$ErrorActionPreference = "Stop" +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +if ($PublicRelease -eq $PrivateValidationOnly) { + throw "Choose exactly one mode: -PublicRelease or -PrivateValidationOnly." +} + +$root = Split-Path -Parent $PSScriptRoot +$requiredSecrets = @( + "LOCALCAPTION_STORE_FILE", + "LOCALCAPTION_STORE_PASSWORD", + "LOCALCAPTION_KEY_ALIAS", + "LOCALCAPTION_KEY_PASSWORD" +) + +foreach ($name in $requiredSecrets) { + $value = [Environment]::GetEnvironmentVariable($name) + if ([string]::IsNullOrWhiteSpace($value)) { + throw "Missing release-signing value: $name" + } +} + +$storeFile = [Environment]::GetEnvironmentVariable("LOCALCAPTION_STORE_FILE") +if (-not [IO.Path]::IsPathRooted($storeFile)) { + $storeFile = Join-Path $root $storeFile + $env:LOCALCAPTION_STORE_FILE = $storeFile +} +if (-not (Test-Path -LiteralPath $storeFile -PathType Leaf)) { + throw "Release keystore does not exist: $storeFile" +} + +$localJdk = Join-Path $root ".toolchain/jdk-17" +$localSdk = Join-Path $root ".toolchain/android-sdk" +if ((Test-Path (Join-Path $localJdk "bin/java.exe")) -and [string]::IsNullOrWhiteSpace($env:JAVA_HOME)) { + $env:JAVA_HOME = $localJdk +} +if ((Test-Path (Join-Path $localSdk "platforms/android-35/android.jar")) -and [string]::IsNullOrWhiteSpace($env:ANDROID_HOME)) { + $env:ANDROID_HOME = $localSdk + $env:ANDROID_SDK_ROOT = $localSdk +} + +& (Join-Path $PSScriptRoot "verify-runtime-assets.ps1") + +$localGradle = Join-Path $root ".toolchain/gradle/bin/gradle.bat" +$gradle = if (Test-Path $localGradle) { + $localGradle +} else { + Join-Path $root "gradlew.bat" +} +if (-not (Test-Path $gradle)) { + throw "Neither the local Gradle toolchain nor Gradle Wrapper is available." +} + +Push-Location $root +try { + & $gradle --no-daemon clean testDebugUnitTest lintRelease assembleRelease bundleRelease + if ($LASTEXITCODE -ne 0) { + throw "Signed release build failed." + } +} finally { + Pop-Location +} + +$apk = Join-Path $root "app/build/outputs/apk/release/app-release.apk" +$bundle = Join-Path $root "app/build/outputs/bundle/release/app-release.aab" +if (-not (Test-Path $apk) -or -not (Test-Path $bundle)) { + throw "Release output is incomplete. Expected both APK and AAB." +} + +$sdkRoot = if (-not [string]::IsNullOrWhiteSpace($env:ANDROID_HOME)) { + $env:ANDROID_HOME +} else { + $env:ANDROID_SDK_ROOT +} +$apksigner = Get-ChildItem -LiteralPath (Join-Path $sdkRoot "build-tools") -Directory | + Sort-Object Name -Descending | + ForEach-Object { Join-Path $_.FullName "apksigner.bat" } | + Where-Object { Test-Path $_ } | + Select-Object -First 1 +if ($null -eq $apksigner) { + throw "Could not find apksigner in Android SDK build-tools." +} + +& $apksigner verify --verbose --print-certs $apk +if ($LASTEXITCODE -ne 0) { + throw "APK signature verification failed." +} + +$jarsigner = Join-Path $env:JAVA_HOME "bin/jarsigner.exe" +$jar = Join-Path $env:JAVA_HOME "bin/jar.exe" +$bundleEntries = & $jar tf $bundle +if ( + $LASTEXITCODE -ne 0 -or + -not ($bundleEntries -match "^META-INF/[^/]+\.(RSA|DSA|EC)$") -or + -not ($bundleEntries -match "^META-INF/[^/]+\.SF$") +) { + throw "AAB does not contain the expected JAR signing blocks." +} + +$jarsignerOutput = & $jarsigner -verify $bundle 2>&1 +if ($LASTEXITCODE -ne 0) { + $jarsignerOutput | ForEach-Object { Write-Host $_ } + throw "AAB signature verification failed." +} +Write-Host "AAB JAR signature verified." + +$outputDir = if ($PublicRelease) { + Join-Path $root "dist/release" +} else { + Join-Path $root "artifacts/private-release-validation" +} +New-Item -ItemType Directory -Force -Path $outputDir | Out-Null +Get-ChildItem -LiteralPath $outputDir -File -ErrorAction SilentlyContinue | Remove-Item -Force + +$outputApk = Join-Path $outputDir "LocalCaption-release.apk" +$outputBundle = Join-Path $outputDir "LocalCaption-release.aab" +Copy-Item -LiteralPath $apk -Destination $outputApk +Copy-Item -LiteralPath $bundle -Destination $outputBundle +Copy-Item -LiteralPath (Join-Path $root "THIRD_PARTY_NOTICES.md") -Destination $outputDir +Copy-Item -LiteralPath (Join-Path $root "docs/license-review.md") -Destination $outputDir +Copy-Item -LiteralPath (Join-Path $root "LICENSES/Apache-2.0.txt") -Destination $outputDir +Copy-Item -LiteralPath (Join-Path $root "LICENSES/MIT.txt") -Destination $outputDir + +$hashes = Get-FileHash -Algorithm SHA256 -LiteralPath $outputApk, $outputBundle +$hashLines = $hashes | ForEach-Object { "$($_.Hash.ToLowerInvariant()) $(Split-Path -Leaf $_.Path)" } +$hashLines | Set-Content -LiteralPath (Join-Path $outputDir "SHA256SUMS.txt") -Encoding UTF8 + +Write-Host "Signed release verified." +Write-Host "Mode: $(if ($PrivateValidationOnly) { 'private validation only' } else { 'public Apache-2.0 model release' })" +Write-Host "Output: $outputDir" +$hashLines | ForEach-Object { Write-Host $_ } diff --git a/tools/capture-device-media.ps1 b/tools/capture-device-media.ps1 new file mode 100644 index 0000000..3f3c251 --- /dev/null +++ b/tools/capture-device-media.ps1 @@ -0,0 +1,48 @@ +param( + [string]$OutputDirectory = "docs/assets/device", + [int]$VideoSeconds = 20 +) + +$ErrorActionPreference = "Stop" +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +$root = Split-Path -Parent $PSScriptRoot +$adb = Join-Path $root ".toolchain/android-sdk/platform-tools/adb.exe" +if (-not (Test-Path $adb)) { + $adbCommand = Get-Command adb -ErrorAction SilentlyContinue + if ($null -eq $adbCommand) { + throw "adb was not found. Run tools/setup-build-toolchain.ps1 first." + } + $adb = $adbCommand.Source +} + +$devices = & $adb devices | + Select-Object -Skip 1 | + Where-Object { $_ -match "\tdevice$" } +if ($devices.Count -ne 1) { + throw "Exactly one authorized Android device is required; found $($devices.Count)." +} + +$output = Join-Path $root $OutputDirectory +New-Item -ItemType Directory -Force -Path $output | Out-Null +$stamp = Get-Date -Format "yyyyMMdd-HHmmss" +$model = (& $adb shell getprop ro.product.model).Trim() -replace "[^A-Za-z0-9._-]", "-" +$screenshot = Join-Path $output "$model-$stamp.png" +$video = Join-Path $output "$model-$stamp.mp4" + +$remoteScreenshot = "/sdcard/localcaption-$stamp.png" +& $adb shell screencap -p $remoteScreenshot +& $adb pull $remoteScreenshot $screenshot +& $adb shell rm -f $remoteScreenshot + +$remoteVideo = "/sdcard/Download/localcaption-$stamp.mp4" +& $adb shell screenrecord --time-limit $VideoSeconds $remoteVideo +if ($LASTEXITCODE -eq 0) { + & $adb pull $remoteVideo $video + & $adb shell rm -f $remoteVideo + Write-Host "Video: $video" +} else { + Write-Warning "This device blocks ADB screenrecord. Use the phone's system recorder and copy the MP4 into $OutputDirectory." +} + +Write-Host "Screenshot: $screenshot" diff --git a/tools/setup-runtime-assets.ps1 b/tools/setup-runtime-assets.ps1 index 5a8d3d3..1fcee3e 100644 --- a/tools/setup-runtime-assets.ps1 +++ b/tools/setup-runtime-assets.ps1 @@ -1,132 +1,115 @@ param( - [switch]$Force, - [switch]$UseHuggingFaceModel + [switch]$Force ) $ErrorActionPreference = "Stop" [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $root = Split-Path -Parent $PSScriptRoot -$cacheDir = Join-Path $root ".runtime-cache" $libsDir = Join-Path $root "app/libs" $assetsDir = Join-Path $root "app/src/main/assets" -$modelName = "sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30" -$quickModelName = "sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01" - -$modelUrl = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/$modelName.tar.bz2" -$hfBaseUrl = "https://huggingface.co/csukuangfj/$modelName/resolve/main" -$quickHfBaseUrl = "https://huggingface.co/csukuangfj/$quickModelName/resolve/main" +$modelName = "sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23" +$modelRevision = "204ad334e2e683fd295359930cc16fc0432a23ac" +$modelBaseUrl = "https://huggingface.co/csukuangfj/$modelName/resolve/$modelRevision" +$modelTarget = Join-Path $assetsDir $modelName $aarName = "sherpa-onnx-static-link-onnxruntime-1.13.4.aar" -$aarUrl = "https://github.com/k2-fsa/sherpa-onnx/releases/download/v1.13.4/$aarName" -New-Item -ItemType Directory -Force -Path $cacheDir, $libsDir, $assetsDir | Out-Null +New-Item -ItemType Directory -Force -Path $libsDir, $modelTarget | Out-Null -function Download-File { +function Install-VerifiedFile { param( [Parameter(Mandatory=$true)][string]$Url, - [Parameter(Mandatory=$true)][string]$OutFile + [Parameter(Mandatory=$true)][string]$OutFile, + [Parameter(Mandatory=$true)][string]$ExpectedSha256 ) if ((Test-Path $OutFile) -and -not $Force) { - $existing = Get-Item $OutFile - if ($existing.Length -gt 0) { - Write-Host "Already exists: $OutFile" + $existingHash = (Get-FileHash -LiteralPath $OutFile -Algorithm SHA256).Hash + if ($existingHash -eq $ExpectedSha256) { + Write-Host "Already verified: $OutFile" return } - Remove-Item -LiteralPath $OutFile -Force + } + + $downloadFile = "$OutFile.download" + if (Test-Path $downloadFile) { + Remove-Item -LiteralPath $downloadFile -Force } Write-Host "Downloading $Url" $curlOk = $false if (Get-Command curl.exe -ErrorAction SilentlyContinue) { - & curl.exe -L --fail --retry 3 --retry-delay 2 --connect-timeout 30 -o $OutFile $Url + & curl.exe -L --fail --retry 3 --retry-delay 2 --connect-timeout 30 -o $downloadFile $Url $curlOk = ($LASTEXITCODE -eq 0) } if (-not $curlOk) { Write-Host "curl download failed or unavailable; trying Invoke-WebRequest" try { - Invoke-WebRequest -Uri $Url -OutFile $OutFile -TimeoutSec 300 -Headers @{ "User-Agent" = "Codex" } + Invoke-WebRequest -Uri $Url -OutFile $downloadFile -TimeoutSec 300 -Headers @{ "User-Agent" = "LocalCaption" } } catch { - throw "Download failed: $Url. You can manually download it and place it at $OutFile. Original error: $($_.Exception.Message)" + if (Test-Path $downloadFile) { + Remove-Item -LiteralPath $downloadFile -Force + } + throw "Download failed: $Url. Original error: $($_.Exception.Message)" } } -} - -$aarOut = Join-Path $libsDir $aarName -Download-File -Url $aarUrl -OutFile $aarOut -$modelArchive = Join-Path $cacheDir "$modelName.tar.bz2" -if (-not $UseHuggingFaceModel) { - try { - Download-File -Url $modelUrl -OutFile $modelArchive - } catch { - Write-Host "GitHub model archive download failed; will try Hugging Face file download. $($_.Exception.Message)" + $actualHash = (Get-FileHash -LiteralPath $downloadFile -Algorithm SHA256).Hash + if ($actualHash -ne $ExpectedSha256) { + Remove-Item -LiteralPath $downloadFile -Force + throw "Checksum mismatch for $Url. Expected $ExpectedSha256, got $actualHash." } -} -$extractDir = Join-Path $cacheDir "model-extract" -if ((Test-Path $extractDir) -and $Force) { - Remove-Item -LiteralPath $extractDir -Recurse -Force + Move-Item -LiteralPath $downloadFile -Destination $OutFile -Force + Write-Host "SHA256 $OutFile $actualHash" } -New-Item -ItemType Directory -Force -Path $extractDir | Out-Null -$modelTarget = Join-Path $assetsDir $modelName -if ((Test-Path $modelTarget) -and -not $Force) { - Write-Host "Model already installed: $modelTarget" -} else { - if (Test-Path $modelTarget) { - Remove-Item -LiteralPath $modelTarget -Recurse -Force +$runtimeFiles = @( + @{ + Url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/v1.13.4/$aarName" + Path = (Join-Path $libsDir $aarName) + Sha256 = "DC5AC19A28DEE3BFFC5E5A5D50CB6AFA977703FC4A7EE535A308506990FDD295" + }, + @{ + Url = "$modelBaseUrl/encoder-epoch-99-avg-1.int8.onnx?download=true" + Path = (Join-Path $modelTarget "encoder-epoch-99-avg-1.int8.onnx") + Sha256 = "1C556EA57CEC304E55EC4B72E52C1CC098BB01476ED7D90F3DE939FE126487B1" + }, + @{ + Url = "$modelBaseUrl/decoder-epoch-99-avg-1.int8.onnx?download=true" + Path = (Join-Path $modelTarget "decoder-epoch-99-avg-1.int8.onnx") + Sha256 = "22F123BB8CBA9B38974B3DF18A3F45E7081F4985EBB2E075D9F21F618C468BBF" + }, + @{ + Url = "$modelBaseUrl/joiner-epoch-99-avg-1.int8.onnx?download=true" + Path = (Join-Path $modelTarget "joiner-epoch-99-avg-1.int8.onnx") + Sha256 = "A7CF9D82757BDCF786059454495A9CA95E4BD7347F72473FC08D794475C36169" + }, + @{ + Url = "$modelBaseUrl/tokens.txt?download=true" + Path = (Join-Path $modelTarget "tokens.txt") + Sha256 = "8B294DB9045D6E5F94647F4C1EEC1AF4DA143A75053C399611444B378FF966AC" } +) - if ((Test-Path $modelArchive) -and ((Get-Item $modelArchive).Length -gt 0)) { - Write-Host "Extracting model archive" - & tar.exe -xjf $modelArchive -C $extractDir - if ($LASTEXITCODE -eq 0) { - $sourceDir = Get-ChildItem -LiteralPath $extractDir -Directory | - Where-Object { $_.Name -eq $modelName } | - Select-Object -First 1 - if ($null -ne $sourceDir) { - New-Item -ItemType Directory -Force -Path $modelTarget | Out-Null - Copy-Item -LiteralPath (Join-Path $sourceDir.FullName "model.int8.onnx") -Destination $modelTarget -Force - Copy-Item -LiteralPath (Join-Path $sourceDir.FullName "tokens.txt") -Destination $modelTarget -Force - } - } - } - -if (-not (Test-Path $modelTarget)) { - New-Item -ItemType Directory -Force -Path $modelTarget | Out-Null - Download-File -Url "$hfBaseUrl/model.int8.onnx?download=true" -OutFile (Join-Path $modelTarget "model.int8.onnx") - Download-File -Url "$hfBaseUrl/tokens.txt?download=true" -OutFile (Join-Path $modelTarget "tokens.txt") - } -} - -$quickModelTarget = Join-Path $assetsDir $quickModelName -if ((Test-Path $quickModelTarget) -and -not $Force) { - Write-Host "Quick model already installed: $quickModelTarget" -} else { - if (Test-Path $quickModelTarget) { - Remove-Item -LiteralPath $quickModelTarget -Recurse -Force - } - New-Item -ItemType Directory -Force -Path $quickModelTarget | Out-Null - Download-File -Url "$quickHfBaseUrl/model.int8.onnx?download=true" -OutFile (Join-Path $quickModelTarget "model.int8.onnx") - Download-File -Url "$quickHfBaseUrl/tokens.txt?download=true" -OutFile (Join-Path $quickModelTarget "tokens.txt") +foreach ($file in $runtimeFiles) { + Install-VerifiedFile -Url $file.Url -OutFile $file.Path -ExpectedSha256 $file.Sha256 } -$requiredFiles = @( - (Join-Path $libsDir $aarName), - (Join-Path $modelTarget "model.int8.onnx"), - (Join-Path $modelTarget "tokens.txt"), - (Join-Path $quickModelTarget "model.int8.onnx"), - (Join-Path $quickModelTarget "tokens.txt") +# These legacy CTC directories have unclear redistribution terms and must never +# be included in a public release package. +$legacyModelNames = @( + "sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30", + "sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01" ) - -foreach ($path in $requiredFiles) { - if (-not (Test-Path $path)) { - throw "Missing required runtime asset: $path" +foreach ($legacyModelName in $legacyModelNames) { + $legacyModelPath = Join-Path $assetsDir $legacyModelName + if (Test-Path $legacyModelPath) { + Write-Host "Removing legacy model from release assets: $legacyModelPath" + Remove-Item -LiteralPath $legacyModelPath -Recurse -Force } } -Write-Host "Runtime assets are ready." -Write-Host "AAR: $aarOut" -Write-Host "Model: $modelTarget" +& (Join-Path $PSScriptRoot "verify-runtime-assets.ps1") +Write-Host "Runtime assets are ready for a publicly distributable build." diff --git a/tools/verify-runtime-assets.ps1 b/tools/verify-runtime-assets.ps1 index 8388dc0..50dc40a 100644 --- a/tools/verify-runtime-assets.ps1 +++ b/tools/verify-runtime-assets.ps1 @@ -2,22 +2,25 @@ $ErrorActionPreference = "Stop" [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $root = Split-Path -Parent $PSScriptRoot -$modelName = "sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30" -$quickModelName = "sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01" -$paths = @( - "app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar", - "app/src/main/assets/$modelName/model.int8.onnx", - "app/src/main/assets/$modelName/tokens.txt", - "app/src/main/assets/$quickModelName/model.int8.onnx", - "app/src/main/assets/$quickModelName/tokens.txt" -) +$modelName = "sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23" +$expectedHashes = [ordered]@{ + "app/libs/sherpa-onnx-static-link-onnxruntime-1.13.4.aar" = "DC5AC19A28DEE3BFFC5E5A5D50CB6AFA977703FC4A7EE535A308506990FDD295" + "app/src/main/assets/$modelName/encoder-epoch-99-avg-1.int8.onnx" = "1C556EA57CEC304E55EC4B72E52C1CC098BB01476ED7D90F3DE939FE126487B1" + "app/src/main/assets/$modelName/decoder-epoch-99-avg-1.int8.onnx" = "22F123BB8CBA9B38974B3DF18A3F45E7081F4985EBB2E075D9F21F618C468BBF" + "app/src/main/assets/$modelName/joiner-epoch-99-avg-1.int8.onnx" = "A7CF9D82757BDCF786059454495A9CA95E4BD7347F72473FC08D794475C36169" + "app/src/main/assets/$modelName/tokens.txt" = "8B294DB9045D6E5F94647F4C1EEC1AF4DA143A75053C399611444B378FF966AC" +} $missing = @() -foreach ($relative in $paths) { +foreach ($relative in $expectedHashes.Keys) { $path = Join-Path $root $relative if (Test-Path $path) { $item = Get-Item $path - Write-Host "OK $relative ($($item.Length) bytes)" + $actual = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash + if ($actual -ne $expectedHashes[$relative]) { + throw "Checksum mismatch for $relative. Expected $($expectedHashes[$relative]), got $actual." + } + Write-Host "OK $relative ($($item.Length) bytes, SHA256 $actual)" } else { Write-Host "MISSING $relative" $missing += $relative @@ -28,4 +31,15 @@ if ($missing.Count -gt 0) { throw "Runtime assets are incomplete. Run tools/setup-runtime-assets.ps1 or copy the files manually." } -Write-Host "Runtime assets are complete." +$legacyModelNames = @( + "sherpa-onnx-streaming-zipformer-ctc-zh-int8-2025-06-30", + "sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01" +) +foreach ($legacyModelName in $legacyModelNames) { + $legacyModelPath = Join-Path $root "app/src/main/assets/$legacyModelName" + if (Test-Path $legacyModelPath) { + throw "Legacy model must not be packaged in a public release: $legacyModelPath" + } +} + +Write-Host "Runtime assets are complete, Apache-2.0-compatible, and checksum-verified."