- 新增 语音识别模块,集成 OpenAI 开源的 Whisper 和 Vosk

- 修复 质量评估模型的 Bug
- 修复 OCR 模块 recognizeAndDraw 方法的 Bug
- 修复 车牌识别在未检测到车牌时的报错问题
- 优化 OCR 表格识别功能,新增导出方式
This commit is contained in:
dengwenjie
2025-08-11 10:38:50 +08:00
parent 9b6f5ea9a1
commit 166f0f9d20
46 changed files with 1325 additions and 146 deletions

View File

@@ -12,7 +12,7 @@
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smartjavaai.version>1.0.22</smartjavaai.version>
<smartjavaai.version>1.0.23</smartjavaai.version>
<!--如果打包运行需要替换成你的main-->
<exec.mainClass>smartai.examples.face.facedet.FaceDetDemo</exec.mainClass>
@@ -95,16 +95,8 @@
<dependency>
<groupId>cn.smartjavaai</groupId>
<artifactId>smartjavaai-face</artifactId>
<version>1.0.22</version>
</dependency>
<dependency>
<groupId>cn.smartjavaai</groupId>
<artifactId>smartjavaai-all</artifactId>
<version>1.0.22</version>
</dependency>
<dependency>
<groupId>ai.djl.pytorch</groupId>

View File

@@ -1,5 +1,6 @@
package smartai.examples.face.attribute;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionResponse;
import cn.smartjavaai.common.entity.R;
@@ -16,6 +17,7 @@ import cn.smartjavaai.face.model.facedect.FaceDetModel;
import cn.smartjavaai.face.utils.FaceUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.imageio.ImageIO;
@@ -33,6 +35,12 @@ import java.util.List;
@Slf4j
public class FaceAttributeDetDemo {
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
public FaceAttributeModel getFaceAttributeModel() {
FaceAttributeConfig config = new FaceAttributeConfig();

View File

@@ -2,6 +2,7 @@ package smartai.examples.face.expression;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionRectangle;
import cn.smartjavaai.common.entity.DetectionResponse;
@@ -26,6 +27,7 @@ import cn.smartjavaai.face.model.liveness.LivenessDetModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import nu.pattern.OpenCV;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opencv.core.Mat;
import org.opencv.core.Size;
@@ -54,6 +56,12 @@ public class ExpressionRecDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取人脸检测模型
* @return

View File

@@ -2,6 +2,7 @@ package smartai.examples.face.facedet;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionRectangle;
import cn.smartjavaai.common.entity.DetectionResponse;
@@ -19,6 +20,7 @@ import cn.smartjavaai.face.model.liveness.LivenessDetModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import nu.pattern.OpenCV;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opencv.core.Mat;
import org.opencv.core.Size;
@@ -32,6 +34,7 @@ import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
/**
@@ -47,6 +50,12 @@ public class FaceDetDemo {
public static String imgPath = "src/main/resources/iu_1.jpg";
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取人脸检测模型
@@ -55,7 +64,10 @@ public class FaceDetDemo {
*/
public FaceDetModel getFaceDetModel(){
FaceDetConfig config = new FaceDetConfig();
//高精度模型,速度慢
config.setModelEnum(FaceDetModelEnum.RETINA_FACE);//人脸检测模型
//下载模型并替换本地路径下载地址https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/retinaface.pt");
config.setConfidenceThreshold(FaceDetectConstant.DEFAULT_CONFIDENCE_THRESHOLD);//只返回相似度大于该值的人脸
config.setNmsThresh(FaceDetectConstant.NMS_THRESHOLD);//用于去除重复的人脸框,当两个框的重叠度超过该值时,只保留一个
return FaceDetModelFactory.getInstance().getModel(config);
@@ -70,7 +82,7 @@ public class FaceDetDemo {
FaceDetConfig config = new FaceDetConfig();
//指定模型
config.setModelEnum(FaceDetModelEnum.SEETA_FACE6_MODEL);
//指定模型路径:请根据实际情况替换为本地模型文件的绝对路径(模型下载地址请查看文档
//指定模型路径:请根据实际情况替换为本地模型文件的绝对路径(下载地址https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("C:/Users/Administrator/Downloads/sf3.0_models/sf3.0_models");
return FaceDetModelFactory.getInstance().getModel(config);
}
@@ -153,28 +165,6 @@ public class FaceDetDemo {
}
/**
* 人脸检测(离线模型)
*/
@Test
public void testDetectFaceOffine(){
try {
FaceDetConfig config = new FaceDetConfig();
config.setModelEnum(FaceDetModelEnum.RETINA_FACE);//人脸模型
//模型路径,不同模型下载路径请参看文档
config.setModelPath("/Users/xxx/Documents/develop/face_model/retinaface.pt");
FaceDetModel faceModel = FaceDetModelFactory.getInstance().getModel(config);
R<DetectionResponse> detectedResult = faceModel.detect(imgPath);
if(detectedResult.isSuccess()){
log.info("人脸检测结果:{}", JSONObject.toJSONString(detectedResult.getData()));
}else{
log.info("人脸检测失败:{}", detectedResult.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 人脸检测GPU模式
*/
@@ -182,7 +172,10 @@ public class FaceDetDemo {
public void testDetectFaceGPU(){
try {
FaceDetConfig config = new FaceDetConfig();
config.setModelEnum(FaceDetModelEnum.RETINA_FACE);//人脸模型
//高精度模型,速度慢
config.setModelEnum(FaceDetModelEnum.RETINA_FACE);//人脸检测模型
//下载模型并替换本地路径下载地址https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/retinaface.pt");
config.setDevice(DeviceEnum.GPU);
FaceDetModel faceModel = FaceDetModelFactory.getInstance().getModel(config);
R<DetectionResponse> detectedResult = faceModel.detect(imgPath);
@@ -223,7 +216,7 @@ public class FaceDetDemo {
@Test
public void testDetectCamera(){
try {
FaceDetModel faceModel = getFaceDetModel();
FaceDetModel faceModel = getSeetaface6DetModel();
OpenCV.loadShared();
VideoCapture capture = new VideoCapture(0);
if (!capture.isOpened()) {

View File

@@ -1,5 +1,6 @@
package smartai.examples.face.facerec;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionResponse;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.common.entity.face.FaceSearchResult;
@@ -24,8 +25,10 @@ import cn.smartjavaai.face.vector.entity.FaceVector;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
@@ -42,14 +45,25 @@ public class FaceRecDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取人脸检测模型
* 获取人脸检测模型(高精度,速度慢)
* 追求准确度可以使用
* 也可以使用其他模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
* @return
*/
public FaceDetModel getFaceDetModel(){
public FaceDetModel getHighAccuracyDetModel(){
FaceDetConfig config = new FaceDetConfig();
//高精度模型,速度慢
config.setModelEnum(FaceDetModelEnum.RETINA_FACE);//人脸检测模型
//下载模型并替换本地路径下载地址https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/retinaface.pt");
config.setConfidenceThreshold(FaceDetectConstant.DEFAULT_CONFIDENCE_THRESHOLD);//只返回相似度大于该值的人脸
config.setNmsThresh(FaceDetectConstant.NMS_THRESHOLD);//用于去除重复的人脸框,当两个框的重叠度超过该值时,只保留一个
config.setDevice(device);
@@ -57,21 +71,62 @@ public class FaceRecDemo {
}
/**
* 获取人脸识别模型
* 获取人脸检测模型(高速模型,精度一般)
* 追求速度可以使用
* 也可以使用其他模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
* @return
*/
public FaceRecModel getFaceRecModel(){
public FaceDetModel getHighSpeedDetModel(){
FaceDetConfig config = new FaceDetConfig();
//高速模型,速度快,精度一般
config.setModelEnum(FaceDetModelEnum.SEETA_FACE6_MODEL);
//下载模型并替换本地路径下载地址https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/sf3.0_models");
config.setDevice(device);
return FaceDetModelFactory.getInstance().getModel(config);
}
/**
* 获取人脸识别模型(高精度,速度慢)
* 追求准确度可以使用
* 也可以使用其他模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
* @return
*/
public FaceRecModel getHighAccuracyFaceRecModel(){
FaceRecConfig config = new FaceRecConfig();
config.setModelEnum(FaceRecModelEnum.FACENET_MODEL);
// config.setModelPath("/Users/xxx/Documents/develop/model/elasticface.pt");
// config.setModelPath("/Users/xxx/Documents/develop/model/InsightFace/model_mobilefacenet.pt");
//高精度模型,速度慢
config.setModelEnum(FaceRecModelEnum.ELASTIC_FACE_MODEL);
//模型路径请下载模型并替换为本地路径https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/elasticface.pt");
//裁剪人脸如果图片已经是裁剪过的则请将此参数设置为false
config.setCropFace(true);
//开启人脸对齐:适用于人脸不正的场景,开启将提升人脸特征准确度,关闭可以提升性能
config.setAlign(true);
config.setDevice(device);
//指定人脸检测模型
config.setDetectModel(getFaceDetModel());
config.setDetectModel(getHighAccuracyDetModel());
return FaceRecModelFactory.getInstance().getModel(config);
}
/**
* 获取人脸识别模型(高速模型,精度一般)
* 追求速度可以使用
* 也可以使用其他模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
* @return
*/
public FaceRecModel getHighSpeedFaceRecModel(){
FaceRecConfig config = new FaceRecConfig();
//高精度模型,速度慢
config.setModelEnum(FaceRecModelEnum.SEETA_FACE6_MODEL);
//模型路径请下载模型并替换为本地路径https://pan.baidu.com/s/10l22x5fRz_gwLr8EAHa1Jg?pwd=1234 提取码: 1234
config.setModelPath("/Users/xxx/Documents/develop/model/sf3.0_models");
//裁剪人脸如果图片已经是裁剪过的则请将此参数设置为false
config.setCropFace(true);
//开启人脸对齐:适用于人脸不正的场景,开启将提升人脸特征准确度,关闭可以提升性能
config.setAlign(false);
config.setDevice(device);
//指定人脸检测模型
config.setDetectModel(getHighSpeedDetModel());
return FaceRecModelFactory.getInstance().getModel(config);
}
@@ -81,14 +136,15 @@ public class FaceRecDemo {
*/
public FaceRecModel getFaceRecModelWithDbConfig(){
FaceRecConfig config = new FaceRecConfig();
//高精度模型,速度慢,追求速度请更换高速模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
config.setModelEnum(FaceRecModelEnum.ELASTIC_FACE_MODEL);//人脸检测模型
config.setModelPath("/Users/xxx/Documents/develop/model/elasticface.pt");
//裁剪人脸如果图片已经是裁剪过的则请将此参数设置为false
config.setCropFace(true);
//开启人脸对齐:适用于人脸不正的场景,开启将提升人脸特征准确度,关闭可以提升性能
config.setAlign(true);
//指定人脸检测模型
config.setDetectModel(getFaceDetModel());
//指定人脸检测模型,高精度模型,速度慢,追求速度请更换高速模型getHighSpeedDetModel
config.setDetectModel(getHighAccuracyDetModel());
config.setDevice(device);
//初始化向量数据库Milvus数据库配置
@@ -112,13 +168,15 @@ public class FaceRecDemo {
*/
public FaceRecModel getFaceRecModelWithSQLiteConfig(){
FaceRecConfig config = new FaceRecConfig();
config.setModelEnum(FaceRecModelEnum.FACENET_MODEL);//人脸检测模型
//高精度模型,速度慢, 追求速度请更换高速模型具体其他模型参数可以查看文档http://doc.smartjavaai.cn/face.html
config.setModelEnum(FaceRecModelEnum.ELASTIC_FACE_MODEL);//人脸检测模型
config.setModelPath("/Users/xxx/Documents/develop/model/elasticface.pt");
//裁剪人脸如果图片已经是裁剪过的则请将此参数设置为false
config.setCropFace(true);
//开启人脸对齐:适用于人脸不正的场景,开启将提升人脸特征准确度,关闭可以提升性能
config.setAlign(true);
//指定人脸检测模型
config.setDetectModel(getFaceDetModel());
//指定人脸检测模型,高精度模型,速度慢,追求速度请更换高速模型getHighSpeedDetModel
config.setDetectModel(getHighAccuracyDetModel());
config.setDevice(device);
//初始化SQLite数据库
@@ -138,7 +196,8 @@ public class FaceRecDemo {
@Test
public void testExtractFeatures(){
try {
FaceRecModel faceRecModel = getFaceRecModel();
//高精度模型,速度慢, 追求速度请更换高速模型: getHighSpeedFaceRecModel
FaceRecModel faceRecModel = getHighAccuracyFaceRecModel();
//提取图片中所有人脸特征
R<DetectionResponse> faceResult = faceRecModel.extractFeatures("src/main/resources/iu_1.jpg");
if(faceResult.isSuccess()){
@@ -162,7 +221,8 @@ public class FaceRecDemo {
@Test
public void featureComparison(){
try {
FaceRecModel faceRecModel = getFaceRecModel();
//高精度模型,速度慢, 追求速度请更换高速模型: getHighSpeedFaceRecModel
FaceRecModel faceRecModel = getHighAccuracyFaceRecModel();
//基于图像直接比对人脸特征
R<Float> similarResult = faceRecModel.featureComparison("src/main/resources/iu_1.jpg","src/main/resources/iu_2.jpg");
if(similarResult.isSuccess()){
@@ -188,7 +248,8 @@ public class FaceRecDemo {
@Test
public void featureComparison2(){
try {
FaceRecModel faceRecModel = getFaceRecModel();
//高精度模型,速度慢, 追求速度请更换高速模型: getHighSpeedFaceRecModel
FaceRecModel faceRecModel = getHighAccuracyFaceRecModel();
//特征提取(提取分数最高人脸特征),适用于单人脸场景
R<float[]> featureResult1 = faceRecModel.extractTopFaceFeature("src/main/resources/iu_1.jpg");
if(featureResult1.isSuccess()){
@@ -226,6 +287,7 @@ public class FaceRecDemo {
@Test
public void searchFace(){
try {
//高精度模型,速度慢, 追求速度请更换高速模型
FaceRecModel faceRecModel = getFaceRecModelWithDbConfig();
//等待加载人脸库结束
while (!faceRecModel.isLoadFaceCompleted()){
@@ -303,6 +365,7 @@ public class FaceRecDemo {
@Test
public void searchFace2(){
try {
//高精度模型,速度慢, 追求速度请更换高速模型
FaceRecModel faceRecModel = getFaceRecModelWithSQLiteConfig();
//等待加载人脸库结束
while (!faceRecModel.isLoadFaceCompleted()){
@@ -419,4 +482,7 @@ public class FaceRecDemo {
}

View File

@@ -3,6 +3,7 @@ package smartai.examples.face.liveness;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import cn.hutool.core.lang.UUID;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionRectangle;
import cn.smartjavaai.common.entity.DetectionResponse;
@@ -32,6 +33,7 @@ import nu.pattern.OpenCV;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opencv.core.Mat;
import org.opencv.core.Size;
@@ -61,6 +63,12 @@ public class LivenessDetDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**

View File

@@ -1,5 +1,6 @@
package smartai.examples.face.quality;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionResponse;
import cn.smartjavaai.common.entity.R;
@@ -23,11 +24,13 @@ import cn.smartjavaai.face.model.quality.FaceQualityModel;
import cn.smartjavaai.face.utils.FaceUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
/**
@@ -41,6 +44,12 @@ public class FaceQualityDetDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}

View File

@@ -12,7 +12,7 @@
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smartjavaai.version>1.0.22</smartjavaai.version>
<smartjavaai.version>1.0.23</smartjavaai.version>
<!--如果打包运行需要替换成你的main-->
<exec.mainClass>smartai.examples.objectdetection.ObjectDetection</exec.mainClass>

View File

@@ -11,6 +11,7 @@ import ai.djl.repository.zoo.ModelNotFoundException;
import ai.djl.repository.zoo.ModelZoo;
import ai.djl.repository.zoo.ZooModel;
import ai.djl.training.util.ProgressBar;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionRectangle;
import cn.smartjavaai.common.entity.DetectionResponse;
@@ -27,6 +28,7 @@ import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import nu.pattern.OpenCV;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opencv.core.Mat;
import org.opencv.core.Size;
@@ -47,6 +49,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
/**
* 目标检测模型demo
@@ -61,6 +64,12 @@ public class ObjectDetection {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
@@ -139,15 +148,30 @@ public class ObjectDetection {
public void objectDetectionWithOfficialModel(){
try {
DetectorModelConfig config = new DetectorModelConfig();
config.setThreshold(0.3f);
// config.setThreshold(0.3f);
//也支持YoloV8YOLOV8_OFFICIAL 模型可以从文档中提供的地址下载
config.setModelEnum(DetectorModelEnum.YOLOV12_OFFICIAL);//检测模型目前支持19种模型
// 指定模型路径,需要更改为自己的模型路径
config.setModelPath("/Users/xxx/Documents/yolov12n.onnx");
config.setModelPath("/Users/wenjie/Documents/develop/face_model/yolo11n.torchscript");
config.setDevice(device);
config.putCustomParam("width", 640);//resize 宽
config.putCustomParam("height", 640);// resize 高
config.putCustomParam("resize", true);
config.putCustomParam("toTensor", true);
config.putCustomParam("applyRatio", true);
config.putCustomParam("threshold", 0.6f);
// for performance optimization maxBox parameter can reduce number of
// considered boxes from 8400
config.putCustomParam("maxBox", 8400);
// config.putCustomParam("pad", 114d);
// List<Float> mean = Arrays.asList(0.5f,0.5f,0.5f,0.5f,0.5f,0.5f);
// String normalize = mean.stream().map(Object::toString).collect(Collectors.joining(","));
// config.putCustomParam("normalize", normalize);
// config.putCustomParam("flag", Image.Flag.COLOR);
// config.putCustomParam("pad", 114);
//一定要将yolo官方的类别文件synset.txt文档中下载放在模型同目录下否则报错
DetectorModel detectorModel = ObjectDetectionModelFactory.getInstance().getModel(config);
DetectionResponse detect = detectorModel.detect("src/main/resources/dog_bike_car.jpg");
DetectionResponse detect = detectorModel.detect("src/main/resources/object_detection.jpg");
log.info("目标检测结果:{}", JSONObject.toJSONString(detect));
} catch (Exception e) {
e.printStackTrace();

View File

@@ -12,7 +12,7 @@
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smartjavaai.version>1.0.22</smartjavaai.version>
<smartjavaai.version>1.0.23</smartjavaai.version>
<!--如果打包运行需要替换成你的main-->
<exec.mainClass>smartai.examples.ocr.common.OcrRecognizeDemo</exec.mainClass>

View File

@@ -1,6 +1,7 @@
package smartai.examples.ocr.common;
import ai.djl.modality.cv.Image;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.DetectionResponse;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.common.utils.ImageUtils;
@@ -14,12 +15,14 @@ import cn.smartjavaai.ocr.model.common.detect.OcrCommonDetModel;
import cn.smartjavaai.ocr.utils.OcrUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opencv.core.Mat;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
@@ -32,9 +35,17 @@ import java.util.List;
public class OcrDetectionDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取文本检测模型
* @return

View File

@@ -1,5 +1,6 @@
package smartai.examples.ocr.common;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.ocr.config.DirectionModelConfig;
import cn.smartjavaai.ocr.config.OcrDetModelConfig;
@@ -12,8 +13,10 @@ import cn.smartjavaai.ocr.model.common.detect.OcrCommonDetModel;
import cn.smartjavaai.ocr.model.common.direction.OcrDirectionModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
@@ -28,6 +31,12 @@ public class OcrDirectionDetDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取方向检测模型
* @return

View File

@@ -1,6 +1,10 @@
package smartai.examples.ocr.common;
import ai.djl.modality.cv.Image;
import ai.djl.util.JsonUtils;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.common.utils.ImageUtils;
import cn.smartjavaai.ocr.config.DirectionModelConfig;
@@ -18,9 +22,15 @@ import cn.smartjavaai.ocr.model.common.direction.OcrDirectionModel;
import cn.smartjavaai.ocr.model.common.recognize.OcrCommonRecModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
@@ -35,6 +45,13 @@ public class OcrRecognizeDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
//Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取通用识别模型(不带方向矫正)
* @return
@@ -44,7 +61,7 @@ public class OcrRecognizeDemo {
//指定文本识别模型
recModelConfig.setRecModelEnum(CommonRecModelEnum.PP_OCR_V5_MOBILE_REC_MODEL);
//指定识别模型位置,需要更改为自己的模型路径(下载地址请查看文档)
recModelConfig.setRecModelPath("/Users/xxx/Documents/develop/model/ocr/PP-OCRv5_mobile_rec_infer/PP-OCRv5_mobile_rec_infer.onnx");
recModelConfig.setRecModelPath("/Users/wenjie/Documents/develop/model/ocr/PP-OCRv5_mobile_rec_infer/PP-OCRv5_mobile_rec_infer.onnx");
recModelConfig.setDevice(device);
recModelConfig.setTextDetModel(getDetectionModel());
return OcrModelFactory.getInstance().getRecModel(recModelConfig);
@@ -59,7 +76,7 @@ public class OcrRecognizeDemo {
//指定检测模型
config.setModelEnum(CommonDetModelEnum.PP_OCR_V5_MOBILE_DET_MODEL);
//指定模型位置,需要更改为自己的模型路径(下载地址请查看文档)
config.setDetModelPath("/Users/xxx/Documents/develop/model/ocr/PP-OCRv5_mobile_det_infer/PP-OCRv5_mobile_det_infer.onnx");
config.setDetModelPath("/Users/wenjie/Documents/develop/model/ocr/PP-OCRv5_mobile_det_infer/PP-OCRv5_mobile_det_infer.onnx");
config.setDevice(device);
return OcrModelFactory.getInstance().getDetModel(config);
}
@@ -180,6 +197,59 @@ public class OcrRecognizeDemo {
}
}
@Test
public void recognizeAndDraw2(){
try {
OcrCommonRecModel recModel = getRecModel();
int fontSize = 18;
//创建保存路径
Path inputImagePath = Paths.get("src/main/resources/general_ocr_002.png");
Path imageOutputPath = Paths.get("output/ocr_4_recognized.jpg");
BufferedImage image = null;
image = ImageIO.read(new File(inputImagePath.toAbsolutePath().toString()));
BufferedImage resultImage = recModel.recognizeAndDraw(image, fontSize, new OcrRecOptions());
ImageUtils.saveImage(resultImage, imageOutputPath.toAbsolutePath().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文本识别并绘制结果返回base64
*/
@Test
public void recognizeAndDrawToBase64(){
try {
OcrCommonRecModel recModel = getRecModel();
int fontSize = 18;
//创建保存路径
Path inputImagePath = Paths.get("src/main/resources/general_ocr_002.png");
byte[] imageBytes = FileUtil.readBytes(inputImagePath);
String base64 = recModel.recognizeAndDrawToBase64(imageBytes, fontSize, new OcrRecOptions());
log.info("base64:{}", base64);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文本识别并绘制结果返回OcrInfo,OcrInfo中包含base64
*/
@Test
public void recognizeAndDraw3(){
try {
OcrCommonRecModel recModel = getRecModel();
int fontSize = 18;
//创建保存路径
Path inputImagePath = Paths.get("src/main/resources/general_ocr_002.png");
byte[] imageBytes = FileUtil.readBytes(inputImagePath);
OcrInfo ocrInfo = recModel.recognizeAndDraw(imageBytes, fontSize, new OcrRecOptions());
log.info("ocrInfo:{}", JsonUtils.toJson(ocrInfo));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 批量识别
* 注意事项:

View File

@@ -1,6 +1,7 @@
package smartai.examples.ocr.plate;
import ai.djl.util.JsonUtils;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.common.utils.ImageUtils;
@@ -13,9 +14,11 @@ import cn.smartjavaai.ocr.factory.PlateModelFactory;
import cn.smartjavaai.ocr.model.plate.PlateDetModel;
import cn.smartjavaai.ocr.model.plate.PlateRecModel;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
@@ -27,6 +30,12 @@ public class PlateRecDemo {
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 获取车牌检测模型
* @return

View File

@@ -2,6 +2,7 @@ package smartai.examples.ocr.table;
import ai.djl.modality.cv.Image;
import cn.hutool.core.io.FileUtil;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.common.utils.ImageUtils;
@@ -21,17 +22,21 @@ import cn.smartjavaai.ocr.model.table.TableRecognizer;
import cn.smartjavaai.ocr.model.table.TableStructureModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* OCR 文本识别 示例
* OCR 表格识别 示例
* 模型下载地址https://pan.baidu.com/s/1MLfd73Vjdpnuls9-oqc9uw?pwd=1234 提取码: 1234
* @author dwj
* @date 2025/5/25
@@ -39,6 +44,13 @@ import java.util.List;
@Slf4j
public class TableRecDemo {
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
//设备类型
public static DeviceEnum device = DeviceEnum.CPU;
@@ -51,7 +63,7 @@ public class TableRecDemo {
//指定文本识别模型
recModelConfig.setRecModelEnum(CommonRecModelEnum.PP_OCR_V5_MOBILE_REC_MODEL);
//指定识别模型位置,需要更改为自己的模型路径(下载地址请查看文档)
recModelConfig.setRecModelPath("/Users/xxx/Documents/develop/model/ocr/PP-OCRv5_mobile_rec_infer/PP-OCRv5_mobile_rec_infer.onnx");
recModelConfig.setRecModelPath("/Users/wenjie/Documents/develop/model/ocr/PP-OCRv5_mobile_rec_infer/PP-OCRv5_mobile_rec_infer.onnx");
recModelConfig.setDevice(device);
recModelConfig.setTextDetModel(getDetectionModel());
return OcrModelFactory.getInstance().getRecModel(recModelConfig);
@@ -66,7 +78,7 @@ public class TableRecDemo {
//指定检测模型
config.setModelEnum(CommonDetModelEnum.PP_OCR_V5_MOBILE_DET_MODEL);
//指定模型位置,需要更改为自己的模型路径(下载地址请查看文档)
config.setDetModelPath("/Users/xxx/Documents/develop/model/ocr/PP-OCRv5_mobile_det_infer/PP-OCRv5_mobile_det_infer.onnx");
config.setDetModelPath("/Users/wenjie/Documents/develop/model/ocr/PP-OCRv5_mobile_det_infer/PP-OCRv5_mobile_det_infer.onnx");
// config.setDetModelPath("/Users/xxx/Documents/develop/model/ocr/PP-OCRv5_server_det_infer/PP-OCRv5_server_det.onnx");
config.setDevice(device);
return OcrModelFactory.getInstance().getDetModel(config);
@@ -81,7 +93,7 @@ public class TableRecDemo {
//指定行文本方向检测模型
directionModelConfig.setModelEnum(DirectionModelEnum.PP_LCNET_X0_25);
//指定行文本方向检测模型路径,需要更改为自己的模型路径(下载地址请查看文档)
directionModelConfig.setModelPath("/Users/xxx/Documents/develop/model/ocr/PP-LCNet_x0_25_textline_ori_infer/PP-LCNet_x0_25_textline_ori_infer.onnx");
directionModelConfig.setModelPath("/Users/wenjie/Documents/develop/model/ocr/PP-LCNet_x0_25_textline_ori_infer/PP-LCNet_x0_25_textline_ori_infer.onnx");
directionModelConfig.setDevice(device);
return OcrModelFactory.getInstance().getDirectionModel(directionModelConfig);
}
@@ -95,7 +107,7 @@ public class TableRecDemo {
//指定行文本方向检测模型
config.setModelEnum(TableStructureModelEnum.SLANET_PLUS);
//指定行文本方向检测模型路径,需要更改为自己的模型路径(下载地址请查看文档)
config.setModelPath("/Users/xxx/Documents/develop/model/ocr/slanet-plus/slanet-plus.onnx");
config.setModelPath("/Users/wenjie/Documents/develop/model/ocr/slanet-plus/slanet-plus.onnx");
// config.setModelPath("/Users/xxx/Documents/develop/model/ocr/SLANet_infer/SLANet.onnx");
config.setDevice(device);
return TableRecModelFactory.getInstance().getTableStructureModel(config);
@@ -142,4 +154,47 @@ public class TableRecDemo {
}
}
/**
* 表格识别
* 仅支持简单表格
* 流程:表格结构识别 -> 文本检测 -> 文本识别 -> 合成html table
* 注意事项:
* 1、批量检测时模型应统一放在外层 try 中使用,避免重复加载,自动释放资源更安全。
* 2、模型文件需要放在单独文件夹
*/
@Test
public void recognize2(){
try {
TableStructureModel tableStructureModel = getTableStructureModel();
OcrCommonDetModel detModel = getDetectionModel();
OcrCommonRecModel recModel = getRecModel();
OcrDirectionModel directionModel = getDirectionModel();
//创建表格识别器
TableRecognizer tableRecognizer = TableRecognizer.builder()
.withStructureModel(tableStructureModel)
.withTextDetModel(detModel)
// .withDirectionModel(getDirectionModel()) //如果表格中存在旋转的文字,可以使用方向分类模型
.withTextRecModel(recModel).build();
String imagePath = "src/main/resources/table/table_ch1.png";
BufferedImage image = ImageIO.read(new File(Paths.get(imagePath).toAbsolutePath().toString()));
R<TableStructureResult> result = tableRecognizer.recognize(image);
if(result.isSuccess()){
log.info("result: {}", result.getData().getHtml());
//导出html内容到文件
Path outputPath = Paths.get("output/table_ch2_result.html");
FileUtil.writeUtf8String(result.getData().getHtml(), outputPath.toAbsolutePath().toString());
//绘制表格结构
BufferedImage resultImage = tableRecognizer.drawTable(result.getData(), image);
ImageUtils.saveImage(resultImage, "output/table_ch2_result.jpg");
//导出excel如果导出失败可能是因为表格结果识别的结果是错乱的
try (OutputStream out = Files.newOutputStream(Paths.get("output/table_ch2_result2.xls"))) {
tableRecognizer.exportExcel(result.getData().getHtml(), out);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

7
examples/speech-examples/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
.idea
.idea/
target
log
*.iml
/.settings/
/logging.file_IS_UNDEFINED/

View File

@@ -0,0 +1,43 @@
# OCR文字识别示例
我来为你写一个 `speech-examples` 项目的 README.md 文件。
## 🎤 语音识别示例
本项目展示了如何使用 SmartJavaAI SDK 进行语音识别,支持 Whisper 和 Vosk 两种语音识别引擎。
## 📁 项目结构
```
src
├── main
│ ├── java
│ │ └── smartai/examples/speech/asr
│ │ └── SpeechRecognizeDemo.java # 语音识别示例
│ └── resources
│ ├── logback.xml # 日志配置文件
│ ├── speech_zh.mp3 # 中文测试音频
│ ├── lff_zh.mp3 # 中文测试音频
│ └── jfk_en.wav # 英文测试音频
└── test
```
## 🚀 快速开始
1. 克隆项目到本地:
2. 导入项目至 IntelliJ IDEA。
3. 根据需要修改模型路径(见各 demo 中注释)。
4. 运行对应的 JUnit 测试类方法即可体验各项功能。
---
## 📄 文档
有关完整使用说明,请查阅 SmartJavaAI 官方文档:
[http://doc.smartjavaai.cn](http://doc.smartjavaai.cn)
---

View File

@@ -0,0 +1,214 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.smartjavaai</groupId>
<artifactId>examples-speech</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smartjavaai.version>1.0.23</smartjavaai.version>
<!--如果打包运行需要替换成你的main-->
<exec.mainClass>smartai.examples.speech.asr.common.OcrRecognizeDemo</exec.mainClass>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.smartjavaai</groupId>
<artifactId>smartjavaai-bom</artifactId>
<version>${smartjavaai.version}</version>
<type>pom</type>
<!-- 注意这里是import -->
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.24.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--语音识别模块-->
<dependency>
<groupId>cn.smartjavaai</groupId>
<artifactId>smartjavaai-speech</artifactId>
<exclusions>
<exclusion>
<groupId>com.microsoft.onnxruntime</groupId>
<artifactId>onnxruntime</artifactId>
</exclusion>
<exclusion>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
</exclusion>
<exclusion>
<groupId>ai.djl.huggingface</groupId>
<artifactId>tokenizers</artifactId>
</exclusion>
<exclusion>
<groupId>ai.djl.ml.xgboost</groupId>
<artifactId>xgboost</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--ffmpeg库 引用所有平台库-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>3.5.0</version>
</dependency>
<!-- windows平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-win64</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
<!-- linux x86 平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-linux64</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
<!-- linux arm64 平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-linux-arm64</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
<!-- linux arm32 平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-linux-arm32</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
<!-- macOS osx64 平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-osx64</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
<!-- macOS M系列 平台 (保留对应平台的配置,可以减小包大小)-->
<!-- <dependency>-->
<!-- <groupId>ws.schild</groupId>-->
<!-- <artifactId>jave-nativebin-osxm1</artifactId>-->
<!-- <version>3.5.0</version>-->
<!-- </dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${exec.mainClass}</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliyunmaven</id>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@@ -0,0 +1,311 @@
package smartai.examples.speech.asr;
import ai.djl.util.JsonUtils;
import cn.hutool.core.io.FileUtil;
import cn.smartjavaai.common.entity.Language;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.speech.asr.config.AsrModelConfig;
import cn.smartjavaai.speech.asr.entity.AsrResult;
import cn.smartjavaai.speech.asr.entity.VoskParams;
import cn.smartjavaai.speech.asr.entity.WhisperParams;
import cn.smartjavaai.speech.asr.enums.AsrModelEnum;
import cn.smartjavaai.speech.asr.factory.SpeechRecognizerFactory;
import cn.smartjavaai.speech.asr.model.SpeechRecognizer;
import cn.smartjavaai.speech.asr.model.VoskRecognizer;
import cn.smartjavaai.speech.asr.model.WhisperRecognizer;
import io.github.givimad.whisperjni.WhisperFullParams;
import io.github.givimad.whisperjni.WhisperGrammar;
import io.github.givimad.whisperjni.WhisperSamplingStrategy;
import io.github.givimad.whisperjni.WhisperState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.vosk.Recognizer;
import javax.sound.sampled.AudioSystem;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Paths;
/**
*
* 语音识别demo
* @author dwj
* @date 2025/8/6
*/
@Slf4j
public class SpeechRecognizeDemo {
/**
* 获取Whisper模型
* 模型下载网盘通过网盘分享的文件https://pan.baidu.com/s/1kiMF5MF641R7LTn1GpB2lQ?pwd=1234 提取码: 1234
* 更多模型下载地址https://huggingface.co/ggerganov/whisper.cpp/tree/main
* @return
*/
public SpeechRecognizer getWhisperRecognizer() {
AsrModelConfig config = new AsrModelConfig();
config.setModelEnum(AsrModelEnum.WHISPER);
//模型下载地址https://huggingface.co/ggerganov/whisper.cpp/tree/main
config.setModelPath("/Users/xxx/Documents/develop/model/speech/ggml-medium.bin");
return SpeechRecognizerFactory.getInstance().getModel(config);
}
/**
* Whisper 语音识别
* 多语言模型支持100种语言
* 注意事项:
* 1、不支持centos7
* 2、模型越大越准确
* 3、暂不支持GPU使用如需GPU使用需要自行编译https://github.com/ggml-org/whisper.cpp/tree/master?tab=readme-ov-file#nvidia-gpu-support
*/
@Test
public void testWhisper() {
try {
SpeechRecognizer recognizer = getWhisperRecognizer();
WhisperParams params = new WhisperParams();
//语言:中文
params.setLanguage(Language.ZH);
R<AsrResult> result = recognizer.recognize("src/main/resources/speech_zh.mp3", params);
if (result.isSuccess()){
log.info("识别成功:{}", JsonUtils.toJson(result.getData()));
}else{
log.info("识别失败:{}", result.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Whisper 语音识别(使用个性化配置)
* 多语言模型支持100种语言
* 注意事项:
* 1、不支持centos7
* 2、模型越大越准确
* 3、暂不支持GPU使用如需GPU使用需要自行编译https://github.com/ggml-org/whisper.cpp/tree/master?tab=readme-ov-file#nvidia-gpu-support
*/
@Test
public void testWhisperWithCustomConfig() {
try {
SpeechRecognizer recognizer = getWhisperRecognizer();
WhisperParams params = new WhisperParams();
//语言:中文
params.setLanguage(Language.ZH);
/**
* 解码搜索策略类型:
* GREEDY - 贪婪解码,逐步选择概率最高的结果;
* BEAN_SEARCH - Beam 搜索,保留多个候选路径以提高准确性。
*/
WhisperFullParams fullParams = new WhisperFullParams(WhisperSamplingStrategy.BEAN_SEARCH);
//语言
fullParams.language = Language.ZH.getCode();
//线程数,设为 0 表示使用最大核心数。
fullParams.nThreads = 0;
//解码器使用的历史文本作为提示的最大 token 数。
fullParams.nMaxTextCtx = 16384;
//解码起始偏移(毫秒)
fullParams.offsetMs = 0;
//解码持续时长(毫秒),超过此长度的音频将被截断
fullParams.durationMs = 0;
//是否翻译为英文
fullParams.translate = false;
// 初始提示,用于提供上下文或样例,帮助模型更准确地理解语音内容
fullParams.initialPrompt = "简体中文";
//禁用上下文链接,不使用前一段解码结果作为上下文
fullParams.noContext = true;
//是否强制仅输出一个段落(适用于短语音)
fullParams.singleSegment = false;
//是否打印特殊标记
fullParams.printSpecial = false;
//是否直接从 whisper.cpp 中打印结果(不推荐,建议使用回调方式替代)
fullParams.printRealtime = false;
//抑制非语音 token输出
fullParams.suppressNonSpeechTokens = false;
//更多参数请查看官网https://github.com/GiviMAD/whisper-jni/blob/33854520b1f0b3697106a7932a2fd64e8191bca9/src/main/java/io/github/givimad/whisperjni/WhisperFullParams.java
params.setParams(fullParams);
//建议上传 WAV 格式音频。其他格式将自动转换为 WAV可能影响处理速度
R<AsrResult> result = recognizer.recognize("src/main/resources/speech_zh.mp3", params);
if (result.isSuccess()){
log.info("识别成功:{}", JsonUtils.toJson(result.getData()));
}else{
log.info("识别失败:{}", result.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Whisper 语音识别(使用Grammar语法规则)
* 多语言模型支持100种语言
* 注意事项:
* 1、不支持centos7
* 2、模型越大越准确
* 3、暂不支持GPU使用如需GPU使用需要自行编译https://github.com/ggml-org/whisper.cpp/tree/master?tab=readme-ov-file#nvidia-gpu-support
*/
@Test
public void testWhisperWithGrammar() {
try {
WhisperRecognizer whisperRecognizer = (WhisperRecognizer)getWhisperRecognizer();
//语法规则
String grammarText = "root ::= \" And so, my fellow American, ask not what your country can do for you, ask what you can do for your country.\"";
try (WhisperGrammar grammar = whisperRecognizer.parseGrammar(grammarText)){
WhisperParams params = new WhisperParams();
WhisperFullParams fullParams = new WhisperFullParams(WhisperSamplingStrategy.BEAN_SEARCH);
//语言:英文
fullParams.language = Language.EN.getCode();
fullParams.grammar = grammar;
params.setParams(fullParams);
//建议上传 WAV 格式音频。其他格式将自动转换为 WAV可能影响处理速度
R<AsrResult> result = whisperRecognizer.recognize("src/main/resources/jfk_en.wav", params);
if (result.isSuccess()){
log.info("识别成功:{}", JsonUtils.toJson(result.getData()));
}else{
log.info("识别失败:{}", result.getMessage());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Vosk模型中文
* 模型下载网盘通过网盘分享的文件https://pan.baidu.com/s/1kiMF5MF641R7LTn1GpB2lQ?pwd=1234 提取码: 1234
* 更多模型下载地址https://alphacephei.com/vosk/models
* @return
*/
public SpeechRecognizer geVoskRecognizer() {
AsrModelConfig config = new AsrModelConfig();
config.setModelEnum(AsrModelEnum.VOSK);
/**
* 每个模型只支持一种语言请下载对应语音的模型模型下载地址https://alphacephei.com/vosk/models
* 将模型解压后,将模型目录位置填写到此处
*/
config.setModelPath("/Users/xxx/Documents/develop/model/speech/vosk-model-cn-0.22");
/**
* macos m系列芯片需要手动下载依赖库并指定位置其他平台不需要
* 下载地址https://pan.baidu.com/s/1LZ_EX1XdTTp_f5ruud82MA?pwd=1234 提取码: 1234
*/
// config.setLibPath(Paths.get("/Users/xxx/Downloads/vosk-arrch64-dylib-main/libvosk.dylib"));
return SpeechRecognizerFactory.getInstance().getModel(config);
}
/**
* 获取Vosk模型英文
* 模型下载网盘通过网盘分享的文件https://pan.baidu.com/s/1kiMF5MF641R7LTn1GpB2lQ?pwd=1234 提取码: 1234
* 更多模型下载地址https://alphacephei.com/vosk/models
* @return
*/
public SpeechRecognizer geEnVoskRecognizer() {
AsrModelConfig config = new AsrModelConfig();
config.setModelEnum(AsrModelEnum.VOSK);
/**
* 每个模型只支持一种语言请下载对应语音的模型模型下载地址https://alphacephei.com/vosk/models
* 将模型解压后,将模型目录位置填写到此处
*/
config.setModelPath("/Users/xxx/Documents/develop/model/speech/vosk-model-small-en-us-0.15");
// config.setLibPath(Paths.get("/Users/xxx/Downloads/vosk-arrch64-dylib-main/libvosk.dylib"));
return SpeechRecognizerFactory.getInstance().getModel(config);
}
/**
* Vosk 语音识别
* 支持 20 多种语言和方言——英语、印度英语、德语、法语、西班牙语、葡萄牙语、中文、俄语、土耳其语、越南语、意大利语、荷兰语、加泰罗尼亚语、阿拉伯语、希腊语、波斯语、菲律宾语、乌克兰语、哈萨克语、瑞典语、日语、世界语、印地语、捷克语、波兰语等
* 注意事项:
* 1、每个模型只支持一种语言请下载对应语言的模型
* 2、如果音频中存在多种语言不推荐使用vosk可以使用Whisper
* 3、模型越大越准确
* 4、暂不支持GPU使用如需GPU使用需要自行编译https://alphacephei.com/vosk/install
*/
@Test
public void testVosk() {
try {
SpeechRecognizer recognizer = geVoskRecognizer();
//建议上传 WAV 格式音频。其他格式将自动转换为 WAV可能影响处理速度
R<AsrResult> result = recognizer.recognize("src/main/resources/lff_zh.mp3");
if (result.isSuccess()){
log.info("识别成功:{}", JsonUtils.toJson(result.getData()));
}else{
log.info("识别失败:{}", result.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Vosk 语音识别(使用Grammar语法规则)
* 支持 20 多种语言和方言——英语、印度英语、德语、法语、西班牙语、葡萄牙语、中文、俄语、土耳其语、越南语、意大利语、荷兰语、加泰罗尼亚语、阿拉伯语、希腊语、波斯语、菲律宾语、乌克兰语、哈萨克语、瑞典语、日语、世界语、印地语、捷克语、波兰语等
* 注意事项:
* 1、每个模型只支持一种语言请下载对应语言的模型
* 2、如果音频中存在多种语言不推荐使用vosk可以使用Whisper
* 3、模型越大越准确
* 4、暂不支持GPU使用如需GPU使用需要自行编译https://alphacephei.com/vosk/install
*/
@Test
public void testVoskWithGrammar() {
try {
//获取英文模型
SpeechRecognizer recognizer = geEnVoskRecognizer();
VoskParams voskParams = new VoskParams();
//英文
voskParams.setLanguage(Language.EN);
voskParams.setGrammar("[\"one two three four five six seven eight nine zero oh\"]");
//建议上传 WAV 格式音频。其他格式将自动转换为 WAV可能影响处理速度
R<AsrResult> result = recognizer.recognize("src/main/resources/test_en.wav",voskParams);
if (result.isSuccess()){
log.info("识别成功:{}", JsonUtils.toJson(result.getData()));
}else{
log.info("识别失败:{}", result.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Vosk 语音识别(使用Vosk内部识别器)
* 支持 20 多种语言和方言——英语、印度英语、德语、法语、西班牙语、葡萄牙语、中文、俄语、土耳其语、越南语、意大利语、荷兰语、加泰罗尼亚语、阿拉伯语、希腊语、波斯语、菲律宾语、乌克兰语、哈萨克语、瑞典语、日语、世界语、印地语、捷克语、波兰语等
* 注意事项:
* 1、每个模型只支持一种语言请下载对应语言的模型
* 2、如果音频中存在多种语言不推荐使用vosk可以使用Whisper
* 3、模型越大越准确
* 4、暂不支持GPU使用如需GPU使用需要自行编译https://alphacephei.com/vosk/install
*/
@Test
public void testVoskAdvanced() {
try {
VoskRecognizer recognizer = (VoskRecognizer)geVoskRecognizer();
//使用vosk内部接口需要指定识别音频的采样率
Recognizer voskRecognizer = recognizer.createAdvancedRecognizer(16000);
voskRecognizer.setWords(true);
voskRecognizer.setPartialWords(true);
// 使用vosk内部接口只支持wav格式
String audioPath = "src/main/resources/lff_zh.wav";
InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(audioPath)));
int nbytes;
byte[] b = new byte[4096];
while ((nbytes = ais.read(b)) >= 0) {
if (voskRecognizer.acceptWaveForm(b, nbytes)) {
log.info(voskRecognizer.getResult());
} else {
log.info(voskRecognizer.getPartialResult());
}
}
log.info(voskRecognizer.getFinalResult());
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: smartai.examples.face.SeetaFace6LinuxDemo

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 步骤2: 配置文件 (src/main/resources/logback.xml) -->
<configuration scan="true" scanPeriod="30 seconds">
<!-- 控制台日志输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@@ -12,7 +12,7 @@
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smartjavaai.version>1.0.22</smartjavaai.version>
<smartjavaai.version>1.0.23</smartjavaai.version>
<!--如果打包运行需要替换成你的main-->
<exec.mainClass>smartai.examples.nlp.translation.TranslationDemo</exec.mainClass>

View File

@@ -1,6 +1,7 @@
package smartai.examples.nlp.translation;
import ai.djl.util.JsonUtils;
import cn.smartjavaai.common.config.Config;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.common.enums.DeviceEnum;
import cn.smartjavaai.translation.config.TranslationModelConfig;
@@ -11,8 +12,11 @@ import cn.smartjavaai.translation.factory.TranslationModelFactory;
import cn.smartjavaai.translation.model.TranslationModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
/**
* 翻译Demo
* 支持 Meta AI 开源的 NLLB-200 模型,实现 200 多种语言之间的高质量互译。
@@ -23,6 +27,12 @@ import org.junit.Test;
@Slf4j
public class TranslationDemo {
@BeforeClass
public static void beforeAll() throws IOException {
//修改缓存路径
// Config.setCachePath("/Users/xxx/smartjavaai_cache");
}
/**
* 翻译