MCPcopy Create free account
hub / github.com/FunAudioLLM/Fun-Audio-Chat / infer_example

Function infer_example

examples/infer_s2s.py:37–90  ·  view source on GitHub ↗

推理示例函数 Args: model_path: 模型路径 audio_path: 输入音频路径

(model_path, audio_path)

Source from the content-addressed store, hash-verified

35device = "cuda:0" if torch.cuda.is_available() else "cpu"
36
37def infer_example(model_path, audio_path):
38 """
39 推理示例函数
40
41 Args:
42 model_path: 模型路径
43 audio_path: 输入音频路径
44 """
45 # 加载模型和处理器
46 config = AutoConfig.from_pretrained(model_path)
47 processor = AutoProcessor.from_pretrained(model_path)
48 model = AutoModelForSeq2SeqLM.from_pretrained(model_path, config=config, torch_dtype=torch.bfloat16, device_map=device)
49
50 # 生成参数
51 sp_gen_kwargs = DEFAULT_SP_GEN_KWARGS.copy()
52 sp_gen_kwargs['text_greedy'] = True
53 gen_kwargs = DEFAULT_S2M_GEN_KWARGS.copy()
54 gen_kwargs['max_new_tokens'] = 2048
55 model.sp_gen_kwargs.update(sp_gen_kwargs)
56
57 # 构建audio样例
58 audio = [librosa.load(audio_path, sr=16000)[0]]
59
60 conversation = [
61 {"role": "system", "content": SPOKEN_S2M_PROMPT},
62 {"role": "user", "content": AUDIO_TEMPLATE},
63 ]
64
65 text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
66 inputs = processor(text=text, audio=audio, return_tensors="pt", return_token_type_ids=False).to(model.device)
67 generate_ids, audio_ids = model.generate(**inputs, **gen_kwargs)
68 generate_ids = generate_ids[:, inputs.input_ids.size(1):]
69 generate_text = processor.decode(generate_ids[0], skip_special_tokens=True)
70 generate_audio = processor.speech_tokenizer.decode(audio_ids[0])
71
72 print("generate_text: ", generate_text)
73 print("generate_audio_token: ", generate_audio)
74
75 token_for_cosyvoice = list(filter(lambda x: 0 <= x < 6561, audio_ids[0].tolist()))
76
77 # 加载CosyVoice detokenizer用于将token转换为wav
78 print("Loading CosyVoice detokenizer...")
79 cosyvoice_model = get_audio_detokenizer()
80
81 # (使用默认的中文女声,你可以根据需要修改)
82 print("Converting audio tokens to wav...")
83 speech = token2wav(cosyvoice_model, token_for_cosyvoice, embedding=None, token_hop_len=25 * 30, pre_lookahead_len=3)
84
85 # 保存wav文件
86 output_uuid = str(uuid.uuid4())
87 os.makedirs('saves', exist_ok=True)
88 output_path = f'saves/output_audio_{output_uuid}.wav'
89 torchaudio.save(output_path, speech.cpu(), cosyvoice_model.sample_rate)
90 print(f"Audio saved to: {output_path}")
91
92def infer_multiturn_example(model_path, audio_paths):
93 """

Callers 1

infer_s2s.pyFile · 0.70

Calls 3

get_audio_detokenizerFunction · 0.90
token2wavFunction · 0.90
decodeMethod · 0.80

Tested by

no test coverage detected