basyx commited on
Commit
1c689d4
·
verified ·
1 Parent(s): ed66b6f

Create generate.py

Browse files
Files changed (1) hide show
  1. generate.py +38 -0
generate.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
3
+ import numpy as np
4
+
5
+ MODEL_ID = "facebook/musicgen-small"
6
+ device = "cpu"
7
+
8
+ print(f"[*] Initializing Engine: Loading {MODEL_ID}...")
9
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
10
+ model = MusicgenForConditionalGeneration.from_pretrained(MODEL_ID, torch_dtype=torch.float32)
11
+ model.to(device)
12
+ print("[+] Engine Ready.")
13
+
14
+ def generate_music(prompt, duration):
15
+ if not prompt:
16
+ return None
17
+
18
+ print(f"[#] Generating: {prompt} ({duration}s)")
19
+ try:
20
+ duration = min(int(duration), 30)
21
+ inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
22
+ max_tokens = int(duration * 50)
23
+
24
+ with torch.no_grad():
25
+ audio_values = model.generate(
26
+ **inputs,
27
+ max_new_tokens=max_tokens,
28
+ do_sample=True,
29
+ guidance_scale=3.0
30
+ )
31
+
32
+ sampling_rate = model.config.audio_encoder.sampling_rate
33
+ audio_data = audio_values[0, 0].cpu().numpy()
34
+ return sampling_rate, audio_data
35
+ except Exception as e:
36
+ print(f"[!] Error: {str(e)}")
37
+ return None, None
38
+