游雁
2023-02-10 d4b683433a9f922c857cbde46741fd2ec0402d9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import json
from typing import Union, Dict
from pathlib import Path
from typeguard import check_argument_types
 
import os
import logging
import torch
 
from funasr.bin.asr_inference_paraformer import Speech2Text
from funasr.export.models import get_model
 
 
 
class ASRModelExportParaformer:
    def __init__(self, cache_dir: Union[Path, str] = None, onnx: bool = True):
        assert check_argument_types()
        if cache_dir is None:
            cache_dir = Path.home() / "cache" / "export"
 
        self.cache_dir = Path(cache_dir)
        self.export_config = dict(
            feats_dim=560,
            onnx=False,
        )
        logging.info("output dir: {}".format(self.cache_dir))
        self.onnx = onnx
 
    def _export(
        self,
        model: Speech2Text,
        tag_name: str = None,
        verbose: bool = False,
    ):
 
        export_dir = self.cache_dir / tag_name.replace(' ', '-')
        os.makedirs(export_dir, exist_ok=True)
 
        # export encoder1
        self.export_config["model_name"] = "model"
        model = get_model(
            model,
            self.export_config,
        )
        self._export_onnx(model, verbose, export_dir)
        if self.onnx:
            self._export_onnx(model, verbose, export_dir)
        else:
            self._export_torchscripts(model, verbose, export_dir)
 
        logging.info("output dir: {}".format(export_dir))
 
 
    def _export_torchscripts(self, model, verbose, path, enc_size=None):
        if enc_size:
            dummy_input = model.get_dummy_inputs(enc_size)
        else:
            dummy_input = model.get_dummy_inputs_txt()
 
        # model_script = torch.jit.script(model)
        model_script = torch.jit.trace(model, dummy_input)
        model_script.save(os.path.join(path, f'{model.model_name}.torchscripts'))
 
    def export(self,
               tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
               mode: str = 'paraformer',
               ):
        
        model_dir = tag_name
        if model_dir.startswith('damo/'):
            from modelscope.hub.snapshot_download import snapshot_download
            model_dir = snapshot_download(model_dir, cache_dir=self.cache_dir)
        asr_train_config = os.path.join(model_dir, 'config.yaml')
        asr_model_file = os.path.join(model_dir, 'model.pb')
        cmvn_file = os.path.join(model_dir, 'am.mvn')
        json_file = os.path.join(model_dir, 'configuration.json')
        if mode is None:
            import json
            with open(json_file, 'r') as f:
                config_data = json.load(f)
                mode = config_data['model']['model_config']['mode']
        if mode == 'paraformer':
            from funasr.tasks.asr import ASRTaskParaformer as ASRTask
        elif mode == 'uniasr':
            from funasr.tasks.asr import ASRTaskUniASR as ASRTask
            
        model, asr_train_args = ASRTask.build_model_from_file(
            asr_train_config, asr_model_file, cmvn_file, 'cpu'
        )
        self._export(model, tag_name)
            
    # def export_from_modelscope(
    #     self,
    #     tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
    # ):
    #
    #     from funasr.tasks.asr import ASRTaskParaformer as ASRTask
    #     from modelscope.hub.snapshot_download import snapshot_download
    #
    #     model_dir = snapshot_download(tag_name, cache_dir=self.cache_dir)
    #     asr_train_config = os.path.join(model_dir, 'config.yaml')
    #     asr_model_file = os.path.join(model_dir, 'model.pb')
    #     cmvn_file = os.path.join(model_dir, 'am.mvn')
    #     model, asr_train_args = ASRTask.build_model_from_file(
    #         asr_train_config, asr_model_file, cmvn_file, 'cpu'
    #     )
    #     self.export(model, tag_name)
    #
    # def export_from_local(
    #     self,
    #     tag_name: str = '/root/cache/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
    # ):
    #
    #     from funasr.tasks.asr import ASRTaskParaformer as ASRTask
    #
    #     model_dir = tag_name
    #     asr_train_config = os.path.join(model_dir, 'config.yaml')
    #     asr_model_file = os.path.join(model_dir, 'model.pb')
    #     cmvn_file = os.path.join(model_dir, 'am.mvn')
    #     model, asr_train_args = ASRTask.build_model_from_file(
    #         asr_train_config, asr_model_file, cmvn_file, 'cpu'
    #     )
    #     self.export(model, tag_name)
 
    def _export_onnx(self, model, verbose, path, enc_size=None):
        if enc_size:
            dummy_input = model.get_dummy_inputs(enc_size)
        else:
            dummy_input = model.get_dummy_inputs()
 
        # model_script = torch.jit.script(model)
        model_script = model #torch.jit.trace(model)
 
        torch.onnx.export(
            model_script,
            dummy_input,
            os.path.join(path, f'{model.model_name}.onnx'),
            verbose=verbose,
            opset_version=12,
            input_names=model.get_input_names(),
            output_names=model.get_output_names(),
            dynamic_axes=model.get_dynamic_axes()
        )
 
if __name__ == '__main__':
    output_dir = "../export"
    export_model = ASRModelExportParaformer(cache_dir=output_dir, onnx=False)
    export_model.export('damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch')
    # export_model.export('/root/cache/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch')