punc_inference_launch.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # -*- encoding: utf-8 -*-
  2. #!/usr/bin/env python3
  3. # Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights Reserved.
  4. # MIT License (https://opensource.org/licenses/MIT)
  5. import argparse
  6. import logging
  7. import os
  8. import sys
  9. from typing import Union, Dict, Any
  10. from funasr.utils import config_argparse
  11. from funasr.utils.cli_utils import get_commandline_args
  12. from funasr.utils.types import str2bool
  13. from funasr.utils.types import str2triple_str
  14. from funasr.utils.types import str_or_none
  15. from funasr.utils.types import float_or_none
  16. import argparse
  17. import logging
  18. from pathlib import Path
  19. import sys
  20. from typing import Optional
  21. from typing import Sequence
  22. from typing import Tuple
  23. from typing import Union
  24. from typing import Any
  25. from typing import List
  26. import numpy as np
  27. import torch
  28. from typeguard import check_argument_types
  29. from funasr.datasets.preprocessor import CodeMixTokenizerCommonPreprocessor
  30. from funasr.utils.cli_utils import get_commandline_args
  31. from funasr.tasks.punctuation import PunctuationTask
  32. from funasr.torch_utils.device_funcs import to_device
  33. from funasr.torch_utils.forward_adaptor import ForwardAdaptor
  34. from funasr.torch_utils.set_all_random_seed import set_all_random_seed
  35. from funasr.utils import config_argparse
  36. from funasr.utils.types import str2triple_str
  37. from funasr.utils.types import str_or_none
  38. from funasr.datasets.preprocessor import split_to_mini_sentence
  39. from funasr.bin.punc_infer import Text2Punc, Text2PuncVADRealtime
  40. def inference_punc(
  41. batch_size: int,
  42. dtype: str,
  43. ngpu: int,
  44. seed: int,
  45. num_workers: int,
  46. log_level: Union[int, str],
  47. key_file: Optional[str],
  48. train_config: Optional[str],
  49. model_file: Optional[str],
  50. output_dir: Optional[str] = None,
  51. param_dict: dict = None,
  52. **kwargs,
  53. ):
  54. assert check_argument_types()
  55. logging.basicConfig(
  56. level=log_level,
  57. format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
  58. )
  59. if ngpu >= 1 and torch.cuda.is_available():
  60. device = "cuda"
  61. else:
  62. device = "cpu"
  63. # 1. Set random-seed
  64. set_all_random_seed(seed)
  65. text2punc = Text2Punc(train_config, model_file, device)
  66. def _forward(
  67. data_path_and_name_and_type,
  68. raw_inputs: Union[List[Any], bytes, str] = None,
  69. output_dir_v2: Optional[str] = None,
  70. cache: List[Any] = None,
  71. param_dict: dict = None,
  72. ):
  73. results = []
  74. split_size = 20
  75. if raw_inputs != None:
  76. line = raw_inputs.strip()
  77. key = "demo"
  78. if line == "":
  79. item = {'key': key, 'value': ""}
  80. results.append(item)
  81. return results
  82. result, _ = text2punc(line)
  83. item = {'key': key, 'value': result}
  84. results.append(item)
  85. return results
  86. for inference_text, _, _ in data_path_and_name_and_type:
  87. with open(inference_text, "r", encoding="utf-8") as fin:
  88. for line in fin:
  89. line = line.strip()
  90. segs = line.split("\t")
  91. if len(segs) != 2:
  92. continue
  93. key = segs[0]
  94. if len(segs[1]) == 0:
  95. continue
  96. result, _ = text2punc(segs[1])
  97. item = {'key': key, 'value': result}
  98. results.append(item)
  99. output_path = output_dir_v2 if output_dir_v2 is not None else output_dir
  100. if output_path != None:
  101. output_file_name = "infer.out"
  102. Path(output_path).mkdir(parents=True, exist_ok=True)
  103. output_file_path = (Path(output_path) / output_file_name).absolute()
  104. with open(output_file_path, "w", encoding="utf-8") as fout:
  105. for item_i in results:
  106. key_out = item_i["key"]
  107. value_out = item_i["value"]
  108. fout.write(f"{key_out}\t{value_out}\n")
  109. return results
  110. return _forward
  111. def inference_punc_vad_realtime(
  112. batch_size: int,
  113. dtype: str,
  114. ngpu: int,
  115. seed: int,
  116. num_workers: int,
  117. log_level: Union[int, str],
  118. #cache: list,
  119. key_file: Optional[str],
  120. train_config: Optional[str],
  121. model_file: Optional[str],
  122. output_dir: Optional[str] = None,
  123. param_dict: dict = None,
  124. **kwargs,
  125. ):
  126. assert check_argument_types()
  127. ncpu = kwargs.get("ncpu", 1)
  128. torch.set_num_threads(ncpu)
  129. if ngpu >= 1 and torch.cuda.is_available():
  130. device = "cuda"
  131. else:
  132. device = "cpu"
  133. # 1. Set random-seed
  134. set_all_random_seed(seed)
  135. text2punc = Text2PuncVADRealtime(train_config, model_file, device)
  136. def _forward(
  137. data_path_and_name_and_type,
  138. raw_inputs: Union[List[Any], bytes, str] = None,
  139. output_dir_v2: Optional[str] = None,
  140. cache: List[Any] = None,
  141. param_dict: dict = None,
  142. ):
  143. results = []
  144. split_size = 10
  145. cache_in = param_dict["cache"]
  146. if raw_inputs != None:
  147. line = raw_inputs.strip()
  148. key = "demo"
  149. if line == "":
  150. item = {'key': key, 'value': ""}
  151. results.append(item)
  152. return results
  153. result, _, cache = text2punc(line, cache_in)
  154. param_dict["cache"] = cache
  155. item = {'key': key, 'value': result}
  156. results.append(item)
  157. return results
  158. return results
  159. return _forward
  160. def inference_launch(mode, **kwargs):
  161. if mode == "punc":
  162. return inference_punc(**kwargs)
  163. if mode == "punc_VadRealtime":
  164. return inference_punc_vad_realtime(**kwargs)
  165. else:
  166. logging.info("Unknown decoding mode: {}".format(mode))
  167. return None
  168. def get_parser():
  169. parser = config_argparse.ArgumentParser(
  170. description="Punctuation inference",
  171. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  172. )
  173. parser.add_argument(
  174. "--log_level",
  175. type=lambda x: x.upper(),
  176. default="INFO",
  177. choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
  178. help="The verbose level of logging",
  179. )
  180. parser.add_argument("--output_dir", type=str, required=True)
  181. parser.add_argument("--gpuid_list", type=str, required=True)
  182. parser.add_argument(
  183. "--ngpu",
  184. type=int,
  185. default=0,
  186. help="The number of gpus. 0 indicates CPU mode",
  187. )
  188. parser.add_argument("--seed", type=int, default=0, help="Random seed")
  189. parser.add_argument("--njob", type=int, default=1, help="Random seed")
  190. parser.add_argument(
  191. "--dtype",
  192. default="float32",
  193. choices=["float16", "float32", "float64"],
  194. help="Data type",
  195. )
  196. parser.add_argument(
  197. "--num_workers",
  198. type=int,
  199. default=1,
  200. help="The number of workers used for DataLoader",
  201. )
  202. parser.add_argument(
  203. "--batch_size",
  204. type=int,
  205. default=1,
  206. help="The batch size for inference",
  207. )
  208. group = parser.add_argument_group("Input data related")
  209. group.add_argument("--data_path_and_name_and_type", type=str2triple_str, action="append", required=False)
  210. group.add_argument("--raw_inputs", type=str, required=False)
  211. group.add_argument("--key_file", type=str_or_none)
  212. group.add_argument("--cache", type=list, required=False)
  213. group.add_argument("--param_dict", type=dict, required=False)
  214. group = parser.add_argument_group("The model configuration related")
  215. group.add_argument("--train_config", type=str)
  216. group.add_argument("--model_file", type=str)
  217. group.add_argument("--mode", type=str, default="punc")
  218. return parser
  219. def main(cmd=None):
  220. print(get_commandline_args(), file=sys.stderr)
  221. parser = get_parser()
  222. args = parser.parse_args(cmd)
  223. kwargs = vars(args)
  224. kwargs.pop("config", None)
  225. # set logging messages
  226. logging.basicConfig(
  227. level=args.log_level,
  228. format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
  229. )
  230. logging.info("Decoding args: {}".format(kwargs))
  231. # gpu setting
  232. if args.ngpu > 0:
  233. jobid = int(args.output_dir.split(".")[-1])
  234. gpuid = args.gpuid_list.split(",")[(jobid - 1) // args.njob]
  235. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  236. os.environ["CUDA_VISIBLE_DEVICES"] = gpuid
  237. kwargs.pop("gpuid_list", None)
  238. kwargs.pop("njob", None)
  239. inference_pipeline = inference_launch(**kwargs)
  240. return inference_pipeline(kwargs["data_path_and_name_and_type"])
  241. if __name__ == "__main__":
  242. main()