kmaes commited on
Commit
f861d58
·
verified ·
1 Parent(s): c25d408

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -35
app.py CHANGED
@@ -9,6 +9,7 @@ import os
9
  import sys
10
  import pickle
11
  import tempfile
 
12
  from huggingface_hub import hf_hub_download
13
 
14
  # Add text2midi model to path
@@ -124,52 +125,64 @@ def midi_to_wav(midi_path: str, wav_path: str, sample_rate: int = 44100) -> bool
124
  return os.path.exists(wav_path)
125
 
126
  def generate_music(prompt: str):
127
- """Generate music from text prompt. Returns audio file path."""
128
  if not prompt or not prompt.strip():
129
  return None
130
 
 
 
 
131
  try:
132
- # Create temporary files
133
- midi_file = tempfile.NamedTemporaryFile(suffix='.mid', delete=False)
134
- midi_path = midi_file.name
135
- midi_file.close()
136
-
137
- wav_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
138
- wav_path = wav_file.name
139
- wav_file.close()
140
-
141
- try:
142
- # Generate MIDI
143
- if MODEL_LOADED:
144
- generate_midi_with_model(prompt, midi_path, max_len=512, temperature=0.9)
145
- else:
146
- from midiutil import MIDIFile
147
- midi = MIDIFile(1)
148
- midi.addTempo(0, 0, 120)
149
- notes = [60, 62, 64, 65, 67, 69, 71, 72]
150
- for i, note in enumerate(notes[:min(len(prompt.split()), 8)]):
151
- midi.addNote(0, 0, note, i, 1, 100)
152
- with open(midi_path, "wb") as f:
153
- midi.writeFile(f)
154
-
155
- # Convert to WAV
156
- if SOUNDFONT_PATH and midi_to_wav(midi_path, wav_path):
 
 
 
157
  return wav_path
158
  else:
 
159
  return None
160
-
161
- finally:
162
- try:
163
- os.unlink(midi_path)
164
- except:
165
- pass
166
 
167
  except Exception as e:
 
168
  import traceback
169
  traceback.print_exc()
170
  return None
 
 
 
 
 
 
 
171
 
172
- # Create simple Gradio Interface (avoids schema generation bugs in gr.Blocks)
173
  demo = gr.Interface(
174
  fn=generate_music,
175
  inputs=gr.Textbox(
@@ -186,8 +199,10 @@ demo = gr.Interface(
186
  ["A slow emotional classical piece with violin"],
187
  ["Epic cinematic soundtrack with dark atmosphere"],
188
  ],
189
- allow_flagging="never"
 
190
  )
191
 
192
  # Launch
193
- demo.launch(show_api=True)
 
 
9
  import sys
10
  import pickle
11
  import tempfile
12
+ import shutil
13
  from huggingface_hub import hf_hub_download
14
 
15
  # Add text2midi model to path
 
125
  return os.path.exists(wav_path)
126
 
127
  def generate_music(prompt: str):
128
+ """Generate music from text prompt. Returns audio file path or tuple (sample_rate, audio_data)."""
129
  if not prompt or not prompt.strip():
130
  return None
131
 
132
+ midi_path = None
133
+ wav_path = None
134
+
135
  try:
136
+ # Create persistent output directory
137
+ output_dir = "output"
138
+ os.makedirs(output_dir, exist_ok=True)
139
+
140
+ # Create files with proper names in persistent directory
141
+ import time
142
+ timestamp = int(time.time() * 1000)
143
+ midi_path = os.path.join(output_dir, f"music_{timestamp}.mid")
144
+ wav_path = os.path.join(output_dir, f"music_{timestamp}.wav")
145
+
146
+ # Generate MIDI
147
+ if MODEL_LOADED:
148
+ generate_midi_with_model(prompt, midi_path, max_len=512, temperature=0.9)
149
+ else:
150
+ from midiutil import MIDIFile
151
+ midi = MIDIFile(1)
152
+ midi.addTempo(0, 0, 120)
153
+ notes = [60, 62, 64, 65, 67, 69, 71, 72]
154
+ for i, note in enumerate(notes[:min(len(prompt.split()), 8)]):
155
+ midi.addNote(0, 0, note, i, 1, 100)
156
+ with open(midi_path, "wb") as f:
157
+ midi.writeFile(f)
158
+
159
+ # Convert to WAV
160
+ if SOUNDFONT_PATH and midi_to_wav(midi_path, wav_path):
161
+ # Verify the file exists and has content
162
+ if os.path.exists(wav_path) and os.path.getsize(wav_path) > 0:
163
+ print(f"Generated audio file: {wav_path} ({os.path.getsize(wav_path)} bytes)")
164
  return wav_path
165
  else:
166
+ print(f"WAV file is empty or doesn't exist")
167
  return None
168
+ else:
169
+ print("Failed to convert MIDI to WAV")
170
+ return None
 
 
 
171
 
172
  except Exception as e:
173
+ print(f"Error generating music: {e}")
174
  import traceback
175
  traceback.print_exc()
176
  return None
177
+ finally:
178
+ # Clean up MIDI file but keep WAV for Gradio to serve
179
+ if midi_path and os.path.exists(midi_path):
180
+ try:
181
+ os.unlink(midi_path)
182
+ except:
183
+ pass
184
 
185
+ # Create simple Gradio Interface
186
  demo = gr.Interface(
187
  fn=generate_music,
188
  inputs=gr.Textbox(
 
199
  ["A slow emotional classical piece with violin"],
200
  ["Epic cinematic soundtrack with dark atmosphere"],
201
  ],
202
+ allow_flagging="never",
203
+ cache_examples=False
204
  )
205
 
206
  # Launch
207
+ if __name__ == "__main__":
208
+ demo.launch(show_api=True)