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
|
| 5 |
+
import soundfile as sf
|
| 6 |
+
|
| 7 |
+
# Model configuration for 4-bit inference
|
| 8 |
+
quantization_config = BitsAndBytesConfig(
|
| 9 |
+
load_in_4bit=True,
|
| 10 |
+
bnb_4bit_quant_type="nf4",
|
| 11 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 12 |
+
bnb_4bit_use_double_quant=True,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# Load model and tokenizer
|
| 16 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 17 |
+
"akh99/veena-hinglish",
|
| 18 |
+
quantization_config=quantization_config,
|
| 19 |
+
device_map="auto",
|
| 20 |
+
trust_remote_code=True,
|
| 21 |
+
)
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained("akh99/veena-hinglish", trust_remote_code=True)
|
| 23 |
+
|
| 24 |
+
# Initialize SNAC decoder
|
| 25 |
+
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").eval().cuda()
|
| 26 |
+
|
| 27 |
+
# Control token IDs (fixed for Veena)
|
| 28 |
+
START_OF_SPEECH_TOKEN = 128257
|
| 29 |
+
END_OF_SPEECH_TOKEN = 128258
|
| 30 |
+
START_OF_HUMAN_TOKEN = 128259
|
| 31 |
+
END_OF_HUMAN_TOKEN = 128260
|
| 32 |
+
START_OF_AI_TOKEN = 128261
|
| 33 |
+
END_OF_AI_TOKEN = 128262
|
| 34 |
+
AUDIO_CODE_BASE_OFFSET = 128266
|
| 35 |
+
|
| 36 |
+
# Available speakers
|
| 37 |
+
speakers = ["kavya", "agastya", "maitri", "vinaya"]
|
| 38 |
+
|
| 39 |
+
def generate_speech(text, speaker="kavya", temperature=0.01, top_p=0.3):
|
| 40 |
+
"""Generate speech from text using specified speaker voice"""
|
| 41 |
+
|
| 42 |
+
# Prepare input with speaker token
|
| 43 |
+
prompt = f"<spk_{speaker}> {text}"
|
| 44 |
+
prompt_tokens = tokenizer.encode(prompt, add_special_tokens=False)
|
| 45 |
+
|
| 46 |
+
# Construct full sequence: [HUMAN] <spk_speaker> text [/HUMAN] [AI] [SPEECH]
|
| 47 |
+
input_tokens = [
|
| 48 |
+
START_OF_HUMAN_TOKEN,
|
| 49 |
+
*prompt_tokens,
|
| 50 |
+
END_OF_HUMAN_TOKEN,
|
| 51 |
+
START_OF_AI_TOKEN,
|
| 52 |
+
START_OF_SPEECH_TOKEN
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
input_ids = torch.tensor([input_tokens], device=model.device)
|
| 56 |
+
|
| 57 |
+
# Calculate max tokens based on text length
|
| 58 |
+
max_tokens = min(int(len(text) * 1.3) * 7 + 21, 700)
|
| 59 |
+
|
| 60 |
+
# Generate audio tokens
|
| 61 |
+
with torch.no_grad():
|
| 62 |
+
output = model.generate(
|
| 63 |
+
input_ids,
|
| 64 |
+
max_new_tokens=max_tokens,
|
| 65 |
+
do_sample=True,
|
| 66 |
+
temperature=temperature,
|
| 67 |
+
top_p=top_p,
|
| 68 |
+
repetition_penalty=1.05,
|
| 69 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 70 |
+
eos_token_id=[END_OF_SPEECH_TOKEN, END_OF_AI_TOKEN]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Extract SNAC tokens
|
| 74 |
+
generated_ids = output[0][len(input_tokens):].tolist()
|
| 75 |
+
snac_tokens = [
|
| 76 |
+
token_id for token_id in generated_ids
|
| 77 |
+
if AUDIO_CODE_BASE_OFFSET <= token_id < (AUDIO_CODE_BASE_OFFSET + 7 * 4096)
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
if not snac_tokens:
|
| 81 |
+
raise ValueError("No audio tokens generated")
|
| 82 |
+
|
| 83 |
+
# Decode audio
|
| 84 |
+
audio = decode_snac_tokens(snac_tokens, snac_model)
|
| 85 |
+
return audio
|
| 86 |
+
|
| 87 |
+
def decode_snac_tokens(snac_tokens, snac_model):
|
| 88 |
+
"""De-interleave and decode SNAC tokens to audio"""
|
| 89 |
+
if not snac_tokens or len(snac_tokens) % 7 != 0:
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
# Get the device of the SNAC model. Fixed by Shresth to run on colab notebook :)
|
| 93 |
+
snac_device = next(snac_model.parameters()).device
|
| 94 |
+
|
| 95 |
+
# De-interleave tokens into 3 hierarchical levels
|
| 96 |
+
codes_lvl = [[] for _ in range(3)]
|
| 97 |
+
llm_codebook_offsets = [AUDIO_CODE_BASE_OFFSET + i * 4096 for i in range(7)]
|
| 98 |
+
|
| 99 |
+
for i in range(0, len(snac_tokens), 7):
|
| 100 |
+
# Level 0: Coarse (1 token)
|
| 101 |
+
codes_lvl[0].append(snac_tokens[i] - llm_codebook_offsets[0])
|
| 102 |
+
# Level 1: Medium (2 tokens)
|
| 103 |
+
codes_lvl[1].append(snac_tokens[i+1] - llm_codebook_offsets[1])
|
| 104 |
+
codes_lvl[1].append(snac_tokens[i+4] - llm_codebook_offsets[4])
|
| 105 |
+
# Level 2: Fine (4 tokens)
|
| 106 |
+
codes_lvl[2].append(snac_tokens[i+2] - llm_codebook_offsets[2])
|
| 107 |
+
codes_lvl[2].append(snac_tokens[i+3] - llm_codebook_offsets[3])
|
| 108 |
+
codes_lvl[2].append(snac_tokens[i+5] - llm_codebook_offsets[5])
|
| 109 |
+
codes_lvl[2].append(snac_tokens[i+6] - llm_codebook_offsets[6])
|
| 110 |
+
|
| 111 |
+
# Convert to tensors for SNAC decoder
|
| 112 |
+
hierarchical_codes = []
|
| 113 |
+
for lvl_codes in codes_lvl:
|
| 114 |
+
tensor = torch.tensor(lvl_codes, dtype=torch.int32, device=snac_device).unsqueeze(0)
|
| 115 |
+
if torch.any((tensor < 0) | (tensor > 4095)):
|
| 116 |
+
raise ValueError("Invalid SNAC token values")
|
| 117 |
+
hierarchical_codes.append(tensor)
|
| 118 |
+
|
| 119 |
+
# Decode with SNAC
|
| 120 |
+
with torch.no_grad():
|
| 121 |
+
audio_hat = snac_model.decode(hierarchical_codes)
|
| 122 |
+
|
| 123 |
+
return audio_hat.squeeze().clamp(-1, 1).cpu().numpy()
|
| 124 |
+
|
| 125 |
+
# --- Example Usage ---
|
| 126 |
+
# Hinglish
|
| 127 |
+
'''
|
| 128 |
+
text_mixed = "Laptop switch on nahi ho raha shayad charging problem hai."
|
| 129 |
+
audio = generate_speech(text_mixed, speaker="kavya")
|
| 130 |
+
sf.write("output_hinglish.wav", audio, 24000)
|
| 131 |
+
'''
|
| 132 |
+
|
| 133 |
+
def interface_fn(text, speaker):
|
| 134 |
+
audio = generate_speech(text, speaker=speaker)
|
| 135 |
+
# Save to a temporary file for Gradio to play
|
| 136 |
+
output_path = "output.wav"
|
| 137 |
+
sf.write(output_path, audio, 24000)
|
| 138 |
+
return output_path
|
| 139 |
+
|
| 140 |
+
# Create the Gradio interface
|
| 141 |
+
demo = gr.Interface(
|
| 142 |
+
fn=interface_fn,
|
| 143 |
+
inputs=[gr.Textbox(label="Text"), gr.Dropdown(choices=speakers, label="Speaker")],
|
| 144 |
+
outputs=gr.Audio(label="Generated Audio")
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
demo.launch()
|