sadafwalliyani commited on
Commit
d0d0a63
1 Parent(s): 13dfdf4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -61
app.py CHANGED
@@ -6,20 +6,18 @@ import os
6
  import numpy as np
7
  import base64
8
 
9
- genres = ["Pop", "Rock", "Jazz", "Electronic", "Hip-Hop", "Classical",
10
- "Lofi", "Chillpop","Country","R&G", "Folk","Heavy Metal",
11
  "EDM", "Soil", "Funk","Reggae", "Disco", "Punk Rock", "House",
12
- "Techno","Indie Rock", "Grunge", "Ambient","Gospel", ]
13
 
14
  @st.cache_resource()
15
  def load_model():
16
  model = MusicGen.get_pretrained('facebook/musicgen-medium')
17
  return model
18
 
19
- def generate_music_tensors(descriptions, duration: int):
20
  model = load_model()
21
- # model = load_model().to('cpu')
22
-
23
 
24
  model.set_generation_params(
25
  use_sampling=True,
@@ -27,9 +25,9 @@ def generate_music_tensors(descriptions, duration: int):
27
  duration=duration
28
  )
29
 
30
- with st.spinner("Generating Music with Medium-Model..."):
31
  output = model.generate(
32
- descriptions=descriptions,
33
  progress=True,
34
  return_tokens=True
35
  )
@@ -37,10 +35,9 @@ def generate_music_tensors(descriptions, duration: int):
37
  st.success("Music Generation Complete!")
38
  return output
39
 
40
-
41
- def save_audio(samples: torch.Tensor):
42
  sample_rate = 30000
43
- save_path = "audio_output"
44
  assert samples.dim() == 2 or samples.dim() == 3
45
 
46
  samples = samples.detach().cpu()
@@ -48,8 +45,9 @@ def save_audio(samples: torch.Tensor):
48
  samples = samples[None, ...]
49
 
50
  for idx, audio in enumerate(samples):
51
- audio_path = os.path.join(save_path, f"audio_{idx}.wav")
52
  torchaudio.save(audio_path, audio, sample_rate)
 
53
 
54
  def get_binary_file_downloader_html(bin_file, file_label='File'):
55
  with open(bin_file, 'rb') as f:
@@ -64,56 +62,37 @@ st.set_page_config(
64
  )
65
 
66
  def main():
67
- with st.sidebar:
68
- st.header("""⚙🎶 Craft Musical Creations 🎶""",divider="rainbow")
69
- st.text("")
70
- st.subheader("1. Enter your music description.......")
71
- bpm = st.number_input("Enter Speed in BPM", min_value=60)
72
-
73
- text_area = st.text_area('Ex : 80s rock song with guitar and drums')
74
- st.text('')
75
- # Dropdown for genres
76
- selected_genre = st.selectbox("Select Genre", genres)
77
-
78
- st.subheader("2. Select time duration (In Seconds)")
79
- time_slider = st.slider("Select time duration (In Seconds)", 0, 60, 10)
80
- # time_slider = st.slider("Select time duration (In Minutes)", 0,300,10, step=1)
81
-
82
-
83
- st.title("""🎵 AI Composer Medium-Model 🎵""")
84
- st.text('')
85
- left_co,right_co = st.columns(2)
86
- left_co.write("""Music Generation with Prompts""")
87
- left_co.write(("""First generation may take some time ......."""))
88
-
89
- if st.sidebar.button('Lets Generate !'):
90
- with left_co:
91
- st.text('')
92
- st.text('')
93
- st.text('')
94
- st.text('')
95
- st.text('')
96
- st.text('')
97
- st.text('\n\n')
98
- st.subheader("Generated Music")
99
-
100
- # Generate audio
101
- # descriptions = [f"{text_area} {selected_genre} {bpm} BPM" for _ in range(5)]
102
- descriptions = [f"{text_area} {selected_genre} {bpm} BPM" for _ in range(1)] # Change the batch size to 1
103
- music_tensors = generate_music_tensors(descriptions, time_slider)
104
-
105
- # Only play the full audio for index 0
106
- idx = 0
107
- music_tensor = music_tensors[idx]
108
- save_music_file = save_audio(music_tensor)
109
- audio_filepath = f'audio_output/audio_{idx}.wav'
110
- audio_file = open(audio_filepath, 'rb')
111
- audio_bytes = audio_file.read()
112
-
113
- # Play the full audio
114
- st.audio(audio_bytes, format='audio/wav')
115
- st.markdown(get_binary_file_downloader_html(audio_filepath, f'Audio_{idx}'), unsafe_allow_html=True)
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  if __name__ == "__main__":
119
  main()
 
 
6
  import numpy as np
7
  import base64
8
 
9
+ genres = ["Pop", "Rock", "Jazz", "Electronic", "Hip-Hop", "Classical",
10
+ "Lofi", "Chillpop","Country","R&G", "Folk","Heavy Metal",
11
  "EDM", "Soil", "Funk","Reggae", "Disco", "Punk Rock", "House",
12
+ "Techno","Indie Rock", "Grunge", "Ambient","Gospel" ]
13
 
14
  @st.cache_resource()
15
  def load_model():
16
  model = MusicGen.get_pretrained('facebook/musicgen-medium')
17
  return model
18
 
19
+ def generate_music_tensors(description, duration: int):
20
  model = load_model()
 
 
21
 
22
  model.set_generation_params(
23
  use_sampling=True,
 
25
  duration=duration
26
  )
27
 
28
+ with st.spinner("Generating Music..."):
29
  output = model.generate(
30
+ descriptions=description,
31
  progress=True,
32
  return_tokens=True
33
  )
 
35
  st.success("Music Generation Complete!")
36
  return output
37
 
38
+ def save_audio(samples: torch.Tensor, filename):
 
39
  sample_rate = 30000
40
+ save_path = "/content/drive/MyDrive/Colab Notebooks/audio_output"
41
  assert samples.dim() == 2 or samples.dim() == 3
42
 
43
  samples = samples.detach().cpu()
 
45
  samples = samples[None, ...]
46
 
47
  for idx, audio in enumerate(samples):
48
+ audio_path = os.path.join(save_path, f"{filename}_{idx}.wav")
49
  torchaudio.save(audio_path, audio, sample_rate)
50
+ return audio_path
51
 
52
  def get_binary_file_downloader_html(bin_file, file_label='File'):
53
  with open(bin_file, 'rb') as f:
 
62
  )
63
 
64
  def main():
65
+ st.title("🎧AI Composer Medium-Model 🎧")
66
+
67
+ st.subheader("Generate Music")
68
+ st.write("Craft your perfect melody! Fill in the blanks below to create your music masterpiece:")
69
+
70
+ bpm = st.number_input("Enter Speed in BPM", min_value=60)
71
+ text_area = st.text_area('Example: 80s rock song with guitar and drums')
72
+ selected_genre = st.selectbox("Select Genre", genres)
73
+ time_slider = st.slider("Select time duration (In Seconds)", 0, 30, 10)
74
+
75
+ st.write("Additional options")
76
+ mood = st.selectbox("Select Mood", ["Happy", "Sad", "Angry", "Relaxed", "Energetic"])
77
+ instrument = st.selectbox("Select Instrument", ["Piano", "Guitar", "Flute", "Violin", "Drums"])
78
+ tempo = st.selectbox("Select Tempo", ["Slow", "Moderate", "Fast"])
79
+ melody = st.text_input("Enter Melody or Chord Progression", "e.g., C D:min G:7 C, Twinkle Twinkle Little Star")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ if st.button('Let\'s Generate 🎶'):
82
+ st.text('\n\n')
83
+ st.subheader("Generated Music")
84
+
85
+ description = f"{text_area} {selected_genre} {bpm} BPM {mood} {instrument} {tempo} {melody}"
86
+ music_tensors = generate_music_tensors(description, time_slider)
87
+
88
+ idx = 0
89
+ audio_path = save_audio(music_tensors[idx], "audio_output")
90
+ audio_file = open(audio_path, 'rb')
91
+ audio_bytes = audio_file.read()
92
+
93
+ st.audio(audio_bytes, format='audio/wav')
94
+ st.markdown(get_binary_file_downloader_html(audio_path, f'Audio_{idx}'), unsafe_allow_html=True)
95
 
96
  if __name__ == "__main__":
97
  main()
98
+