ASLP-lab commited on
Commit
27d1541
·
verified ·
1 Parent(s): 1fcd812

Upload infer_qwen2.5omni.py

Browse files
Files changed (1) hide show
  1. infer_qwen2.5omni.py +68 -0
infer_qwen2.5omni.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from qwen_omni_utils import process_mm_info
2
+ import torch
3
+ from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
4
+ import librosa
5
+ import os
6
+ from io import BytesIO
7
+ from urllib.request import urlopen
8
+ import argparse
9
+ # @title inference function
10
+ def inference(audio_path,model,processor,prompt, sys_prompt):
11
+ messages = [
12
+ {"role": "system", "content": [{"type": "text", "text": sys_prompt}]},
13
+ {"role": "user", "content": [
14
+ {"type": "audio", "audio": audio_path},
15
+ {"type": "text", "text": prompt},
16
+ ]
17
+ },
18
+ ]
19
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
20
+ audios, images, videos = process_mm_info(messages, use_audio_in_video=True)
21
+ inputs = processor(text=text, audio=audios, images=images, videos=videos, return_tensors="pt", padding=True, use_audio_in_video=True)
22
+ inputs = inputs.to(model.device).to(model.dtype)
23
+
24
+ output = model.generate(**inputs, use_audio_in_video=True, return_audio=False, thinker_max_new_tokens=256, thinker_do_sample=False)
25
+
26
+ text = processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)
27
+ return text
28
+
29
+ def transcribe(wavs_path, out_path, gpu_id, model):
30
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
31
+ model_path = model
32
+ model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
33
+ model_path,
34
+ torch_dtype=torch.bfloat16,
35
+ device_map="auto",
36
+ )
37
+ prompt = "请将这段中文语音转换为纯文本,去掉标点符号。"
38
+ processor = Qwen2_5OmniProcessor.from_pretrained(model_path)
39
+ with open(wavs_path, "r") as f_in, open(out_path, "w") as f_out:
40
+ for line in f_in:
41
+ utt, path = line.strip().split(" ", maxsplit=1)
42
+ try:
43
+ response=inference(path,model,processor, prompt=prompt, sys_prompt="You are a speech recognition model.")
44
+ except Exception as e:
45
+ print(f"Inference failed: {str(e)}")
46
+ response="None"
47
+ text = response[0].strip()
48
+ lines = text.strip().splitlines()
49
+ text = lines[-1]
50
+ print(f"[{utt}] >>> {text}")
51
+ f_out.write(f"{utt} {text}\n")
52
+
53
+
54
+
55
+
56
+ if __name__ == "__main__":
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument("--wavs_path", type=str)
59
+ parser.add_argument("--out_path", type=str)
60
+ parser.add_argument("--gpu", type=int, default=0)
61
+ parser.add_argument("--model", type=str)
62
+ args = parser.parse_args()
63
+ transcribe(
64
+ wavs_path=args.wavs_path,
65
+ out_path=args.out_path,
66
+ gpu_id=args.gpu,
67
+ model=args.model
68
+ )