Android 将 Whisper 模型转换为 TFLite 并在 Android 应用中直接运行 ...

打印 上一主题 下一主题

主题 1840|帖子 1840|积分 5520

Whisper

将 Whisper 模型转换为 TFLite 并在 Android 应用中直接运行的完备步骤:

1. 模型转换流程

1.1 安装依赖

bash
复制
  1. # 安装 PyTorch、ONNX、TensorFlow 和转换工具
  2. pip install torch onnx tf2onnx transformers tensorflow
复制代码
1.2 导出 PyTorch 模型为 ONNX

python
复制
  1. import torch
  2. from transformers import WhisperForConditionalGeneration, WhisperProcessor
  3. # 加载模型和处理器
  4. model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
  5. processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
  6. # 示例输入(音频长度 30s,采样率 16kHz)
  7. dummy_input = torch.randn(1, 30000)  # 1x30000 的音频信号
  8. # 导出为 ONNX
  9. torch.onnx.export(
  10.     model,
  11.     dummy_input,
  12.     "whisper_tiny.onnx",
  13.     input_names=["input_features"],
  14.     output_names=["logits"],
  15.     dynamic_axes={"input_features": {0: "batch_size", 1: "sequence_length"}},
  16. )
复制代码
1.3 转换 ONNX 为 TensorFlow 模型

python
复制
  1. import tf2onnx
  2. from onnx_tf.backend import prepare
  3. # 加载 ONNX 模型并转换为 TensorFlow
  4. onnx_model = onnx.load("whisper_tiny.onnx")
  5. tf_rep = prepare(onnx_model)
  6. tf_rep.export_graph("whisper_tiny_tf")
复制代码
1.4 转换为 TFLite 模型(含量化)

python
复制
  1. import tensorflow as tf
  2. # 加载 TensorFlow SavedModel
  3. converter = tf.lite.TFLiteConverter.from_saved_model("whisper_tiny_tf")
  4. # 启用动态范围量化(减小模型体积)
  5. converter.optimizations = [tf.lite.Optimize.DEFAULT]
  6. # 转换为 TFLite 模型
  7. tflite_model = converter.convert()
  8. # 保存模型
  9. with open("whisper_tiny.tflite", "wb") as f:
  10.     f.write(tflite_model)
复制代码

2. Android 端集成

2.1 添加 TFLite 依赖

在 app/build.gradle 中添加:
gradle
复制
  1. dependencies {
  2.     implementation 'org.tensorflow:tensorflow-lite:2.10.0'
  3.     implementation 'org.tensorflow:tensorflow-lite-support:0.4.4'
  4. }
复制代码
2.2 将模型文件放入 Assets

复制
  1. app/src/main/assets/
  2. └── whisper_tiny.tflite
复制代码

3. Java 代码实现

3.1 音频预处置惩罚工具类

java
复制
  1. import android.content.Context;
  2. import org.tensorflow.lite.support.audio.TensorAudio;
  3. import org.tensorflow.lite.support.common.FileUtil;
  4. public class AudioPreprocessor {
  5.     // 将音频文件转换为模型输入张量
  6.     public static TensorAudio preprocessAudio(Context context, String audioPath) {
  7.         // 加载音频并重采样到 16kHz
  8.         TensorAudio tensor = TensorAudio.create(
  9.             TensorAudio.TensorAudioFormat.create(1, 16000),
  10.             FileUtil.loadAudioFile(context, audioPath)
  11.         );
  12.         return tensor;
  13.     }
  14. }
复制代码
3.2 TFLite 模型推理

java
复制
  1. import android.content.Context;
  2. import org.tensorflow.lite.Interpreter;
  3. import org.tensorflow.lite.support.common.FileUtil;
  4. import java.nio.ByteBuffer;
  5. public class WhisperInference {
  6.     private final Interpreter interpreter;
  7.     public WhisperInference(Context context) {
  8.         // 加载 TFLite 模型
  9.         ByteBuffer modelBuffer = FileUtil.loadMappedFile(context, "whisper_tiny.tflite");
  10.         interpreter = new Interpreter(modelBuffer);
  11.     }
  12.     public String transcribe(TensorAudio audioTensor) {
  13.         // 输入输出容器
  14.         float[][][] input = new float[1][80][3000]; // 梅尔频谱图维度
  15.         String[] output = new String[1];
  16.         // 执行推理
  17.         interpreter.run(input, output);
  18.         return output[0];
  19.     }
  20.     public void close() {
  21.         interpreter.close();
  22.     }
  23. }
复制代码
3.3 主界面逻辑

java
复制
  1. import android.os.Bundle;
  2. import android.widget.Button;
  3. import androidx.appcompat.app.AppCompatActivity;
  4. public class MainActivity extends AppCompatActivity {
  5.     private WhisperInference whisperInference;
  6.     @Override
  7.     protected void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.activity_main);
  10.         // 初始化模型
  11.         whisperInference = new WhisperInference(this);
  12.         // 录音和推理按钮
  13.         Button btnProcess = findViewById(R.id.btn_process);
  14.         btnProcess.setOnClickListener(v -> {
  15.             // 1. 录音并保存为文件(需实现录音逻辑)
  16.             String audioPath = "/path/to/audio.wav";
  17.             
  18.             // 2. 预处理音频
  19.             TensorAudio audio = AudioPreprocessor.preprocessAudio(this, audioPath);
  20.             
  21.             // 3. 执行推理
  22.             String text = whisperInference.transcribe(audio);
  23.             
  24.             // 4. 使用 TTS 播放结果
  25.             // (参考之前的 TTS 代码)
  26.         });
  27.     }
  28.     @Override
  29.     protected void onDestroy() {
  30.         whisperInference.close();
  31.         super.onDestroy();
  32.     }
  33. }
复制代码

4. 关键优化技能

4.1 模型量化



  • 动态范围量化:减少 4x 模型体积(从 150MB 到 ~40MB)
  • 全整数量化(需校准数据集):
    python
    复制
    1. converter.representative_dataset = calibration_dataset
    2. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
    复制代码
4.2 输入输出优化



  • 梅尔频谱图预处置惩罚:在 Android 端实现音频到频谱图的转换(替代 Python 代码)
  • 缓存机制:复用 Interpreter 实例避免重复加载模型
4.3 多线程推理

java
复制
  1. // 在后台线程执行推理
  2. new Thread(() -> {
  3.     String text = whisperInference.transcribe(audio);
  4.     runOnUiThread(() -> updateUI(text));
  5. }).start();
复制代码

5. 完备流程对比

步骤Python + Chaquopy 方案TFLite 方案模型体积200MB+ (含 Python 运行时)40MB (量化后)推理速度较慢(依赖 Python 解释器)快(原生 C++ 执行)内存占用高(加载完备 PyTorch 模型)低(TFLite 优化)开辟复杂度低(直接调用 Python)中(需处置惩罚模型转换和 C++ 接口)
6. 留意事项


  • 算子兼容性:转换过程中大概遇到不支持的算子(如自界说 Layer),需手动实现或简化模型。
  • 精度损失:量化大概导致辨认准确率降落,需通过测试调整量化策略。
  • 及时性要求:长音频需分段处置惩罚,避免内存溢出。
  • 设备兼容性:确保 NDK 编译时包罗全部目标 ABI(armeabi-v7a, arm64-v8a)。

通过上述步骤,可将 Whisper 模型高效摆设到 Android 设备,显著提升性能并降低依赖复杂度。
TTS

TensorFlowTTS 
https://github.com/TensorSpeech/TensorFlowTTS
      Android for TTSTensorFlowTTS/examples/android at master · TensorSpeech/TensorFlowTTS · GitHub:stuck_out_tongue_closed_eyes: TensorFlowTTS: Real-Time State-of-the-art Speech Synthesis for Tensorflow 2 (supported including English, French, Korean, Chinese, German and Easy to adapt for other languages) - TensorFlowTTS/examples/android at master · TensorSpeech/TensorFlowTTS
https://github.com/TensorSpeech/TensorFlowTTS/tree/master/examples/android

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

天津储鑫盛钢材现货供应商

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表