|
| 1 | +use wasmedge_wasi_nn::{ |
| 2 | + self, ExecutionTarget, GraphBuilder, GraphEncoding, GraphExecutionContext, |
| 3 | + TensorType, |
| 4 | +}; |
| 5 | +use hound; |
| 6 | + |
| 7 | +fn get_data_from_context(context: &GraphExecutionContext, index: usize, limit: usize) -> Vec<u8> { |
| 8 | + // Preserve for 4096 tokens with average token length 8 |
| 9 | + const MAX_OUTPUT_BUFFER_SIZE: usize = 4096 * 4096; |
| 10 | + let mut output_buffer = vec![0u8; MAX_OUTPUT_BUFFER_SIZE]; |
| 11 | + let _ = context |
| 12 | + .get_output(index, &mut output_buffer) |
| 13 | + .expect("Failed to get output"); |
| 14 | + |
| 15 | + return output_buffer[..limit].to_vec(); |
| 16 | +} |
| 17 | + |
| 18 | +fn main() { |
| 19 | + let prompt = "It is a test sentence."; |
| 20 | + let tensor_data = prompt.as_bytes().to_vec(); |
| 21 | + let empty_vec: Vec<Vec<u8>> = Vec::new(); |
| 22 | + let graph = GraphBuilder::new(GraphEncoding::ChatTTS, ExecutionTarget::CPU) |
| 23 | + .build_from_bytes(empty_vec) |
| 24 | + .expect("Failed to build graph"); |
| 25 | + let mut context = graph |
| 26 | + .init_execution_context() |
| 27 | + .expect("Failed to init context"); |
| 28 | + context |
| 29 | + .set_input(0, TensorType::U8, &[1], &tensor_data) |
| 30 | + .expect("Failed to set input"); |
| 31 | + context.compute().expect("Failed to compute"); |
| 32 | + let bytes_written = get_data_from_context(&context, 1, 4); |
| 33 | + let bytes_written = usize::from_le_bytes(bytes_written.as_slice().try_into().unwrap()); |
| 34 | + println!("Byte: {}", bytes_written); |
| 35 | + let output_bytes = get_data_from_context(&context, 0, bytes_written); |
| 36 | + let spec = hound::WavSpec { |
| 37 | + channels: 1, |
| 38 | + sample_rate: 24000, |
| 39 | + bits_per_sample: 32, |
| 40 | + sample_format: hound::SampleFormat::Float, |
| 41 | + }; |
| 42 | + let mut writer = hound::WavWriter::create("output1.wav", spec).unwrap(); |
| 43 | + let samples: Vec<f32> = output_bytes |
| 44 | + .chunks_exact(4) |
| 45 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 46 | + .collect(); |
| 47 | + for sample in samples { |
| 48 | + writer.write_sample(sample).unwrap(); |
| 49 | + } |
| 50 | + writer.finalize().unwrap(); |
| 51 | + graph.unload().expect("Failed to free resource"); |
| 52 | +} |
0 commit comments