Add Java API examples with gradle (#3784)

This commit is contained in:
Fangjun Kuang authored and GitHub committed 2026-07-22 19:36:59 +08:00
1 parent a3b58a159e
commit 9d15a282aa
20 files changed
+1341

No files matched your search

+475
View File
@@ -662,3 +662,478 @@ jobs:
run: |
cd java-api-examples/maven-examples
java -jar target/sherpa-onnx-maven-example-1.0-SNAPSHOT.jar
run_gradle_test:
runs-on: ${{ matrix.os }}
name: gradle-${{ matrix.os }} ${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
arch: "x64"
native_lib: linux-x64
- os: ubuntu-24.04-arm
arch: "arm64"
native_lib: linux-aarch64
- os: macos-latest
arch: "arm64"
native_lib: osx-aarch64
- os: macos-15-intel
arch: "x64"
native_lib: osx-x64
- os: windows-2022
arch: "x64"
native_lib: win-x64
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
- name: Show java version
shell: bash
run: |
java --version
javac --version
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Update build.gradle for this platform
shell: bash
run: |
cd java-api-examples/gradle-examples
native_lib=${{ matrix.native_lib }}
python3 << 'PYEOF'
import re
native_lib = "${{ matrix.native_lib }}"
target_artifact = f"sherpa-onnx-native-lib-{native_lib}"
with open("build.gradle", "r") as f:
content = f.read()
# Comment out all active native lib lines
def comment_active_lines(content):
lines = content.split('\n')
result = []
for line in lines:
stripped = line.strip()
if stripped.startswith("implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-"):
if target_artifact in stripped:
# This is our target - ensure it's uncommented
result.append(line)
else:
# Comment it out
result.append(' // ' + stripped)
else:
result.append(line)
return '\n'.join(result)
# Uncomment the target line if it's commented
def uncomment_target(content):
lines = content.split('\n')
result = []
for line in lines:
stripped = line.strip()
if stripped.startswith("// implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-"):
if target_artifact in stripped:
# Uncomment this line
result.append(' ' + stripped[3:])
else:
result.append(line)
else:
result.append(line)
return '\n'.join(result)
content = comment_active_lines(content)
content = uncomment_target(content)
with open("build.gradle", "w") as f:
f.write(content)
PYEOF
- name: Show build.gradle for debugging
shell: bash
run: |
cat java-api-examples/gradle-examples/build.gradle
- name: Build gradle example
shell: bash
run: |
cd java-api-examples/gradle-examples
./gradlew build --info
ls -lh build/libs/*.jar
- name: Verify jar contents
shell: bash
run: |
cd java-api-examples/gradle-examples
echo "=== Jar size ==="
ls -lh build/libs/sherpa-onnx-gradle-example.jar
echo "=== Native libs in jar ==="
unzip -l build/libs/sherpa-onnx-gradle-example.jar | grep -E "\.so$|\.dylib$|\.dll$" || true
- name: Run gradle example
shell: bash
run: |
cd java-api-examples/gradle-examples
./gradlew run --info
run_gradle_test_approach1:
runs-on: ${{ matrix.os }}
name: gradle-approach1-${{ matrix.os }} ${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
arch: "x64"
- os: ubuntu-24.04-arm
arch: "arm64"
- os: macos-latest
arch: "arm64"
- os: macos-15-intel
arch: "x64"
- os: windows-2022
arch: "x64"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
- name: Show java version
shell: bash
run: |
java --version
javac --version
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Write build.gradle for Approach 1
shell: bash
run: |
cd java-api-examples/gradle-examples
cat > build.gradle << 'EOF'
plugins {
id 'application'
id 'java'
}
application {
mainClass = 'com.k2fsa.sherpa.onnx.example.VersionTest'
}
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT'
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.named('jar') {
manifest {
attributes(
'Main-Class': 'com.k2fsa.sherpa.onnx.example.VersionTest'
)
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
EOF
- name: Show build.gradle for debugging
shell: bash
run: |
cat java-api-examples/gradle-examples/build.gradle
- name: Build gradle example (Approach 1)
shell: bash
run: |
cd java-api-examples/gradle-examples
./gradlew build --info
ls -lh build/libs/*.jar
- name: Verify jar contents
shell: bash
run: |
cd java-api-examples/gradle-examples
echo "=== Jar size ==="
ls -lh build/libs/sherpa-onnx-gradle-example.jar
echo "=== Native libs in jar ==="
unzip -l build/libs/sherpa-onnx-gradle-example.jar | grep -E "\.so$|\.dylib$|\.dll$" || true
- name: Run gradle example
shell: bash
run: |
cd java-api-examples/gradle-examples
./gradlew run --info
run_gradle_kts_test:
runs-on: ${{ matrix.os }}
name: gradle-kts-${{ matrix.os }} ${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
arch: "x64"
native_lib: linux-x64
- os: ubuntu-24.04-arm
arch: "arm64"
native_lib: linux-aarch64
- os: macos-latest
arch: "arm64"
native_lib: osx-aarch64
- os: macos-15-intel
arch: "x64"
native_lib: osx-x64
- os: windows-2022
arch: "x64"
native_lib: win-x64
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
- name: Show java version
shell: bash
run: |
java --version
javac --version
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Update build.gradle.kts for this platform
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
native_lib=${{ matrix.native_lib }}
python3 << 'PYEOF'
import re
native_lib = "${{ matrix.native_lib }}"
target_artifact = f"sherpa-onnx-native-lib-{native_lib}"
with open("build.gradle.kts", "r") as f:
content = f.read()
# Comment out all active native lib lines
def comment_active_lines(content):
lines = content.split('\n')
result = []
for line in lines:
stripped = line.strip()
if stripped.startswith('implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-'):
if target_artifact in stripped:
result.append(line)
else:
result.append(' // ' + stripped)
else:
result.append(line)
return '\n'.join(result)
# Uncomment the target line if it's commented
def uncomment_target(content):
lines = content.split('\n')
result = []
for line in lines:
stripped = line.strip()
if stripped.startswith('// implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-'):
if target_artifact in stripped:
result.append(' ' + stripped[3:])
else:
result.append(line)
else:
result.append(line)
return '\n'.join(result)
content = comment_active_lines(content)
content = uncomment_target(content)
with open("build.gradle.kts", "w") as f:
f.write(content)
PYEOF
- name: Show build.gradle.kts for debugging
shell: bash
run: |
cat java-api-examples/gradle-kts-examples/build.gradle.kts
- name: Build gradle kts example
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
./gradlew build --info
ls -lh build/libs/*.jar
- name: Verify jar contents
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
echo "=== Jar size ==="
ls -lh build/libs/sherpa-onnx-gradle-kts-example.jar
echo "=== Native libs in jar ==="
unzip -l build/libs/sherpa-onnx-gradle-kts-example.jar | grep -E "\.so$|\.dylib$|\.dll$" || true
- name: Run gradle kts example
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
./gradlew run --info
run_gradle_kts_test_approach1:
runs-on: ${{ matrix.os }}
name: gradle-kts-approach1-${{ matrix.os }} ${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
arch: "x64"
- os: ubuntu-24.04-arm
arch: "arm64"
- os: macos-latest
arch: "arm64"
- os: macos-15-intel
arch: "x64"
- os: windows-2022
arch: "x64"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
- name: Show java version
shell: bash
run: |
java --version
javac --version
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Write build.gradle.kts for Approach 1
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
cat > build.gradle.kts << 'EOF'
plugins {
application
java
}
application {
mainClass.set("com.k2fsa.sherpa.onnx.example.VersionTest")
}
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
dependencies {
implementation("com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT")
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.jar {
manifest {
attributes("Main-Class" to "com.k2fsa.sherpa.onnx.example.VersionTest")
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
}
EOF
- name: Show build.gradle.kts for debugging
shell: bash
run: |
cat java-api-examples/gradle-kts-examples/build.gradle.kts
- name: Build gradle kts example (Approach 1)
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
./gradlew build --info
ls -lh build/libs/*.jar
- name: Verify jar contents
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
echo "=== Jar size ==="
ls -lh build/libs/sherpa-onnx-gradle-kts-example.jar
echo "=== Native libs in jar ==="
unzip -l build/libs/sherpa-onnx-gradle-kts-example.jar | grep -E "\.so$|\.dylib$|\.dll$" || true
- name: Run gradle kts example
shell: bash
run: |
cd java-api-examples/gradle-kts-examples
./gradlew run --info
+1
View File
@@ -148,6 +148,7 @@ voices.bin
kitten-nano-en-v0_1-fp16
*.egg-info
*.jar
!gradle-wrapper.jar
vocab.json
*.so
sherpa-onnx-streaming-t-one-russian-2025-09-08
@@ -0,0 +1 @@
.gradle
+123
View File
@@ -0,0 +1,123 @@
# sherpa-onnx Gradle Example
This directory demonstrates how to use [sherpa-onnx](https://github.com/k2-fsa/sherpa-onnx) via Gradle.
## Prerequisites
- JDK 8 or above
- Gradle 8.x (or use the included Gradle wrapper)
## Dependencies
The project uses [JitPack](https://jitpack.io/) to fetch sherpa-onnx artifacts.
There are two ways to declare the dependencies.
### Approach 1: Simple (single dependency)
This is the easiest way — one dependency pulls in everything:
```groovy
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT'
}
```
### Approach 2: Multi-module (recommended)
This is the recommended way for production use. It splits the JVM API and native libs
so you only ship the platform you need, keeping the final jar lightweight:
```groovy
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
// 1. JVM core API
implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-jvm:refactor-jar-SNAPSHOT'
// 2. Platform native lib — pick ONE for your target platform
implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-aarch64:refactor-jar-SNAPSHOT'
}
```
Available native lib artifacts for each platform:
| Platform | Artifact |
|---|---|
| macOS ARM64 | `sherpa-onnx-native-lib-osx-aarch64` |
| macOS x64 | `sherpa-onnx-native-lib-osx-x64` |
| Linux x64 | `sherpa-onnx-native-lib-linux-x64` |
| Linux ARM64 | `sherpa-onnx-native-lib-linux-aarch64` |
| Windows x64 | `sherpa-onnx-native-lib-win-x64` |
> **Note:** The `build.gradle` in this directory uses Approach 2 by default. Approach 1 is
> included as a comment for reference.
## Build
```bash
cd java-api-examples/gradle-examples
# Using Gradle wrapper (recommended)
./gradlew build
# Or using system Gradle
gradle build
```
## Run
```bash
# Using Gradle wrapper (recommended)
./gradlew run
# Or using system Gradle
gradle run
```
Expected output:
```
sherpa-onnx version: x.y.z
sherpa-onnx gitSha1: ...
sherpa-onnx gitDate: ...
```
## Appendix: Approach 1 vs Approach 2 comparison (advanced)
The two approaches produce **very different** fat jars:
| | Approach 1 (simple) | Approach 2 (multi-module) |
|---|---|---|
| Jar size (compressed) | **~95 MB** | **~9 MB** |
| Uncompressed size | **~286 MB** | **~33 MB** |
| Total files | ~295 | ~253 |
| JVM class files | ~236 | ~236 |
| Native libs included | ALL platforms | macOS ARM64 only |
### Why Approach 2 is recommended
Approach 2 is **~10x smaller** (~9 MB vs ~95 MB) because it only ships the native libs for
your target platform. This matters for:
- **Download size**: users only download what they need
- **Startup time**: the JVM loads fewer native libraries
- **Disk space**: especially important for CI/CD and container images
### Verify it yourself
```bash
# Build and check the jar
./gradlew build
ls -lh build/libs/*.jar
# List native libs in the jar
unzip -l build/libs/sherpa-onnx-gradle-example.jar | grep -E "\.so$|\.dylib$|\.dll$"
```
@@ -0,0 +1,62 @@
plugins {
id 'application'
id 'java'
}
application {
mainClass = 'com.k2fsa.sherpa.onnx.example.VersionTest'
}
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
// ============================================================
// Approach 1: Simple — one dependency pulls in everything.
// ============================================================
// implementation 'com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT'
// ============================================================
// Approach 2 (recommended): Multi-module — split JVM API and
// native libs so you only ship the platform you need.
// ============================================================
// 1. JVM core API Jar
implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-jvm:refactor-jar-SNAPSHOT'
// 2. Platform native lib — uncomment ONE for your target platform
// macOS ARM64 (Apple Silicon)
implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-aarch64:refactor-jar-SNAPSHOT'
// macOS x64 (Intel)
// implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-x64:refactor-jar-SNAPSHOT'
// Linux x64
// implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-linux-x64:refactor-jar-SNAPSHOT'
// Linux ARM64
// implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-linux-aarch64:refactor-jar-SNAPSHOT'
// Windows x64
// implementation 'com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-win-x64:refactor-jar-SNAPSHOT'
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.named('jar') {
manifest {
attributes(
'Main-Class': 'com.k2fsa.sherpa.onnx.example.VersionTest'
)
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+144
View File
@@ -0,0 +1,144 @@
#!/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.
#
##############################################################################
#
# 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 functionality shells and target
# temporary focusing, entity, entity, entity, entity, entity, entity,
# focusing, target, target.
#
# (2) You need a Java installation to run Gradle. If you have Java installed,
# Gradle will use the JAVA_HOME environment variable or try to find it in
# your PATH.
#
##############################################################################
# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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, stracks://github.com/gradle/gradle/issues/12448
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$@"
exec "$JAVACMD" "$@"
+87
View File
@@ -0,0 +1,87 @@
@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
@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 %OS%==Windows_NT endlocal
:omega
@rem Set errorlevel appropriately
exit /b %ERRORLEVEL%
:fail
@rem Set errorlevel to indicate failure
exit /b 1
@@ -0,0 +1 @@
rootProject.name = 'sherpa-onnx-gradle-example'
@@ -0,0 +1,13 @@
// Copyright 2025 Xiaomi Corporation
package com.k2fsa.sherpa.onnx.example;
import com.k2fsa.sherpa.onnx.*;
public class VersionTest {
public static void main(String[] args) {
System.out.printf("sherpa-onnx version: %s\n", VersionInfo.getVersion());
System.out.printf("sherpa-onnx gitSha1: %s\n", VersionInfo.getGitSha1());
System.out.printf("sherpa-onnx gitDate: %s\n", VersionInfo.getGitDate());
}
}
@@ -0,0 +1 @@
.gradle
@@ -0,0 +1,116 @@
# sherpa-onnx Gradle Kotlin DSL (KTS) Example
This directory demonstrates how to use [sherpa-onnx](https://github.com/k2-fsa/sherpa-onnx) via Gradle with Kotlin DSL (`build.gradle.kts`).
## Prerequisites
- JDK 8 or above
- Gradle 8.x+ (or use the included Gradle wrapper)
## Dependencies
The project uses [JitPack](https://jitpack.io/) to fetch sherpa-onnx artifacts.
There are two ways to declare the dependencies.
### Approach 1: Simple (single dependency)
This is the easiest way — one dependency pulls in everything:
```kotlin
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
dependencies {
implementation("com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT")
}
```
### Approach 2: Multi-module (recommended)
This is the recommended way for production use. It splits the JVM API and native libs
so you only ship the platform you need, keeping the final jar lightweight:
```kotlin
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
dependencies {
// 1. JVM core API
implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-jvm:refactor-jar-SNAPSHOT")
// 2. Platform native lib — pick ONE for your target platform
implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-aarch64:refactor-jar-SNAPSHOT")
}
```
Available native lib artifacts for each platform:
| Platform | Artifact |
|---|---|
| macOS ARM64 | `sherpa-onnx-native-lib-osx-aarch64` |
| macOS x64 | `sherpa-onnx-native-lib-osx-x64` |
| Linux x64 | `sherpa-onnx-native-lib-linux-x64` |
| Linux ARM64 | `sherpa-onnx-native-lib-linux-aarch64` |
| Windows x64 | `sherpa-onnx-native-lib-win-x64` |
> **Note:** The `build.gradle.kts` in this directory uses Approach 2 by default. Approach 1 is
> included as a comment for reference.
## Build
```bash
cd java-api-examples/gradle-kts-examples
# Using Gradle wrapper (recommended)
./gradlew build
# Or using system Gradle
gradle build
```
## Run
```bash
# Using Gradle wrapper (recommended)
./gradlew run
# Or using system Gradle
gradle run
```
Expected output:
```
sherpa-onnx version: x.y.z
sherpa-onnx gitSha1: ...
sherpa-onnx gitDate: ...
```
## Appendix: Groovy vs Kotlin DSL comparison
| Feature | Groovy (`build.gradle`) | Kotlin DSL (`build.gradle.kts`) |
|---|---|---|
| Syntax | Dynamic, concise | Static, type-safe |
| IDE support | Good | Excellent (auto-completion, refactoring) |
| Strings | `'single'` or `"double"` | `"double"` only |
| Function calls | `implementation '...'` | `implementation("...")` |
| Properties | `mainClass = '...'` | `mainClass.set("...")` |
| Recommended for | Legacy projects | New projects |
## Appendix: Approach 1 vs Approach 2 comparison (advanced)
The two approaches produce **very different** fat jars:
| | Approach 1 (simple) | Approach 2 (multi-module) |
|---|---|---|
| Jar size (compressed) | **~95 MB** | **~9 MB** |
| Uncompressed size | **~286 MB** | **~33 MB** |
| Native libs included | ALL platforms | Target platform only |
### Why Approach 2 is recommended
Approach 2 is **~10x smaller** because it only ships the native libs for your target platform.
@@ -0,0 +1,58 @@
plugins {
application
java
}
application {
mainClass.set("com.k2fsa.sherpa.onnx.example.VersionTest")
}
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
dependencies {
// ============================================================
// Approach 1: Simple — one dependency pulls in everything.
// ============================================================
// implementation("com.github.k2-fsa:sherpa-onnx:refactor-jar-SNAPSHOT")
// ============================================================
// Approach 2 (recommended): Multi-module — split JVM API and
// native libs so you only ship the platform you need.
// ============================================================
// 1. JVM core API Jar
implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-jvm:refactor-jar-SNAPSHOT")
// 2. Platform native lib — uncomment ONE for your target platform
// macOS ARM64 (Apple Silicon)
implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-aarch64:refactor-jar-SNAPSHOT")
// macOS x64 (Intel)
// implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-osx-x64:refactor-jar-SNAPSHOT")
// Linux x64
// implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-linux-x64:refactor-jar-SNAPSHOT")
// Linux ARM64
// implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-linux-aarch64:refactor-jar-SNAPSHOT")
// Windows x64
// implementation("com.github.k2-fsa.sherpa-onnx:sherpa-onnx-native-lib-win-x64:refactor-jar-SNAPSHOT")
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.jar {
manifest {
attributes("Main-Class" to "com.k2fsa.sherpa.onnx.example.VersionTest")
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
}
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+144
View File
@@ -0,0 +1,144 @@
#!/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.
#
##############################################################################
#
# 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 functionality shells and target
# temporary focusing, entity, entity, entity, entity, entity, entity,
# focusing, target, target.
#
# (2) You need a Java installation to run Gradle. If you have Java installed,
# Gradle will use the JAVA_HOME environment variable or try to find it in
# your PATH.
#
##############################################################################
# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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, stracks://github.com/gradle/gradle/issues/12448
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$@"
exec "$JAVACMD" "$@"
+87
View File
@@ -0,0 +1,87 @@
@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
@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 %OS%==Windows_NT endlocal
:omega
@rem Set errorlevel appropriately
exit /b %ERRORLEVEL%
:fail
@rem Set errorlevel to indicate failure
exit /b 1
@@ -0,0 +1 @@
rootProject.name = "sherpa-onnx-gradle-kts-example"
@@ -0,0 +1,13 @@
// Copyright 2025 Xiaomi Corporation
package com.k2fsa.sherpa.onnx.example;
import com.k2fsa.sherpa.onnx.*;
public class VersionTest {
public static void main(String[] args) {
System.out.printf("sherpa-onnx version: %s\n", VersionInfo.getVersion());
System.out.printf("sherpa-onnx gitSha1: %s\n", VersionInfo.getGitSha1());
System.out.printf("sherpa-onnx gitDate: %s\n", VersionInfo.getGitDate());
}
}