ohfiftyb252 commited on
Commit
9e06a06
Β·
verified Β·
1 Parent(s): c0e93a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -56
app.py CHANGED
@@ -1,26 +1,24 @@
1
  #!/usr/bin/env python3
2
- """Music Transcriber..."""
3
 
4
  import gradio as gr
5
- import spaces # ← ADD THIS LINE
6
  from pathlib import Path
7
  import tempfile
8
  import os
9
 
10
- # Redirect caches to /tmp for HF Spaces
11
  os.environ['HF_HOME'] = '/tmp/hf_cache'
12
  os.environ['TORCH_HOME'] = '/tmp/hf_cache/torch'
13
  os.environ['TRANSFORMERS_CACHE'] = '/tmp/hf_cache'
14
 
 
15
  def transcribe_audio(audio_file, model_size, instruments):
16
- """Transcribe audio to MIDI with progress tracking."""
17
  if audio_file is None:
18
  return None, "❌ Please upload an audio file first.", 0
19
 
20
  from muscriptor import TranscriptionModel
21
  from muscriptor.events import ProgressEvent
22
 
23
- # Parse instrument filter
24
  instrument_group = None
25
  instrument_names = []
26
  if instruments:
@@ -42,18 +40,17 @@ def transcribe_audio(audio_file, model_size, instruments):
42
 
43
  try:
44
  note_events = []
45
- progress_status = "Starting..."
46
 
47
  for event in model.transcribe(str(audio_file), instrument_group=instrument_group):
48
- if isinstance(event, ProgressEvent):
49
- progress_status = f"🎹 Processing: {int(event.fraction * 100)}%"
50
  elif hasattr(event, 'note_id'):
51
  note_events.append(event)
52
 
53
  midi_bytes = model.transcribe_to_midi(str(audio_file), instrument_group=instrument_group)
54
  output_path.write_bytes(midi_bytes)
55
 
56
- msg = f"βœ… Complete!\n🎼 {len(note_events)} notes detected\nπŸ“ MIDI ready for download"
57
  if instrument_names:
58
  msg += f"\nπŸ” Filtered: {', '.join(instrument_names)}"
59
 
@@ -65,77 +62,46 @@ def transcribe_audio(audio_file, model_size, instruments):
65
  return None, f"❌ Error: {e}", 0
66
 
67
  def list_instruments():
68
- """Return list of available instruments."""
69
  try:
70
  from muscriptor.tokenizer.mt3 import MT3_FULL_PLUS_GROUP_NAMES
71
- instruments = sorted(MT3_FULL_PLUS_GROUP_NAMES.keys())
72
- return "\n".join(f"β€’ {name}" for name in instruments)
73
  except Exception:
74
- return "Could not load instrument list. Install muscriptor first."
75
 
76
- # Build Gradio Interface
77
- with gr.Blocks(
78
- title="🎡 Music Transcriber",
79
- theme=gr.themes.Soft(primary_hue="purple"),
80
- css="""
81
- .gradio-container { max-width: 900px !important; }
82
- .note-count { font-size: 2rem; font-weight: bold; color: #8b5cf6; text-align: center; padding: 1rem; }
83
- .instructions { font-size: 0.9rem; color: #6b7280; }
84
- """
85
- ) as demo:
86
 
87
- gr.Markdown("# 🎡 Music Transcriber\nTurn audio into MIDI using AI. Upload a song, select model size, and get your transcription!")
88
 
89
  with gr.Row():
90
  with gr.Column(scale=1):
91
- audio_input = gr.Audio(
92
- type="filepath",
93
- label="Upload Audio (MP3, WAV, FLAC, OGG, M4A)",
94
- interactive=True
 
 
95
  )
96
-
97
- with gr.Row():
98
- model_select = gr.Radio(
99
- choices=[("Small (~100M) - Fastest ⚑", "small"),
100
- ("Medium (~300M) - Balanced πŸ‘", "medium"),
101
- ("Large (~1.3B) - Best Quality 🌟", "large")],
102
- value="medium",
103
- label="Model Size"
104
- )
105
-
106
- instrument_input = gr.Textbox(
107
- label="Filter Instruments (optional)",
108
- placeholder="e.g., acoustic_piano, acoustic_guitar, electric_bass",
109
- info="Comma-separated instrument names. Leave blank for all instruments."
110
- )
111
-
112
  transcribe_btn = gr.Button("🎹 Transcribe Audio", variant="primary", size="lg")
113
 
114
  with gr.Column(scale=1):
115
  status_output = gr.Textbox(label="Status", lines=4)
116
- note_count_output = gr.HTML('<div class="note-count">0</div>')
117
  midi_output = gr.File(label="Download MIDI", visible=False)
118
 
119
- # List instruments accordion
120
  with gr.Accordion("πŸ“‹ View Available Instruments", open=False):
121
- gr.Markdown("```")
122
- inst_list = gr.Markdown(label="Instruments")
123
- gr.Markdown("```")
124
 
125
- # Button callbacks
126
  transcribe_btn.click(
127
  fn=transcribe_audio,
128
  inputs=[audio_input, model_select, instrument_input],
129
  outputs=[midi_output, status_output, note_count_output]
130
  ).then(
131
- lambda path, notes: (gr.update(visible=bool(path)), f"<div class='note-count'>{notes}</div>"),
 
132
  inputs=[midi_output, note_count_output],
133
  outputs=[midi_output, note_count_output]
134
  )
135
-
136
- # Initialize instrument list
137
- gr.Markdown("Click the accordion above to see all available instruments.")
138
- inst_list.value = list_instruments()
139
 
140
  if __name__ == "__main__":
141
- demo.launch()
 
1
  #!/usr/bin/env python3
2
+ """Music Transcriber - Gradio Web App for Hugging Face Spaces (ZeroGPU)"""
3
 
4
  import gradio as gr
5
+ import spaces # ← REQUIRED FOR ZEROGPU
6
  from pathlib import Path
7
  import tempfile
8
  import os
9
 
 
10
  os.environ['HF_HOME'] = '/tmp/hf_cache'
11
  os.environ['TORCH_HOME'] = '/tmp/hf_cache/torch'
12
  os.environ['TRANSFORMERS_CACHE'] = '/tmp/hf_cache'
13
 
14
+ @spaces.GPU(duration=600) # ← THIS IS THE KEY FIX
15
  def transcribe_audio(audio_file, model_size, instruments):
 
16
  if audio_file is None:
17
  return None, "❌ Please upload an audio file first.", 0
18
 
19
  from muscriptor import TranscriptionModel
20
  from muscriptor.events import ProgressEvent
21
 
 
22
  instrument_group = None
23
  instrument_names = []
24
  if instruments:
 
40
 
41
  try:
42
  note_events = []
 
43
 
44
  for event in model.transcribe(str(audio_file), instrument_group=instrument_group):
45
+ if hasattr(event, 'fraction'):
46
+ pass # Progress tracked internally
47
  elif hasattr(event, 'note_id'):
48
  note_events.append(event)
49
 
50
  midi_bytes = model.transcribe_to_midi(str(audio_file), instrument_group=instrument_group)
51
  output_path.write_bytes(midi_bytes)
52
 
53
+ msg = f"βœ… Complete!\n🎼 {len(note_events)} notes detected"
54
  if instrument_names:
55
  msg += f"\nπŸ” Filtered: {', '.join(instrument_names)}"
56
 
 
62
  return None, f"❌ Error: {e}", 0
63
 
64
  def list_instruments():
 
65
  try:
66
  from muscriptor.tokenizer.mt3 import MT3_FULL_PLUS_GROUP_NAMES
67
+ return "\n".join(f"β€’ {name}" for name in sorted(MT3_FULL_PLUS_GROUP_NAMES.keys()))
 
68
  except Exception:
69
+ return "Could not load instrument list."
70
 
71
+ with gr.Blocks(title="🎡 Music Transcriber") as demo:
 
 
 
 
 
 
 
 
 
72
 
73
+ gr.Markdown("# 🎡 Music Transcriber\nTurn audio into MIDI using AI!")
74
 
75
  with gr.Row():
76
  with gr.Column(scale=1):
77
+ audio_input = gr.Audio(type="filepath", label="Upload Audio (MP3, WAV, FLAC)")
78
+ model_select = gr.Radio(
79
+ choices=[("Small (~100M) - Fastest ⚑", "small"),
80
+ ("Medium (~300M) - Balanced πŸ‘", "medium"),
81
+ ("Large (~1.3B) - Best Quality 🌟", "large")],
82
+ value="medium", label="Model Size"
83
  )
84
+ instrument_input = gr.Textbox(label="Filter Instruments (optional)", placeholder="e.g., acoustic_piano, acoustic_guitar")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  transcribe_btn = gr.Button("🎹 Transcribe Audio", variant="primary", size="lg")
86
 
87
  with gr.Column(scale=1):
88
  status_output = gr.Textbox(label="Status", lines=4)
89
+ note_count_output = gr.HTML('<div style="font-size: 2rem; font-weight: bold; color: #8b5cf6; text-align: center; padding: 1rem;">0</div>')
90
  midi_output = gr.File(label="Download MIDI", visible=False)
91
 
 
92
  with gr.Accordion("πŸ“‹ View Available Instruments", open=False):
93
+ gr.Markdown(list_instruments())
 
 
94
 
 
95
  transcribe_btn.click(
96
  fn=transcribe_audio,
97
  inputs=[audio_input, model_select, instrument_input],
98
  outputs=[midi_output, status_output, note_count_output]
99
  ).then(
100
+ lambda path, notes: (gr.update(visible=bool(path)),
101
+ f"<div style=\"font-size: 2rem; font-weight: bold; color: #8b5cf6; text-align: center; padding: 1rem;\">{notes}</div>"),
102
  inputs=[midi_output, note_count_output],
103
  outputs=[midi_output, note_count_output]
104
  )
 
 
 
 
105
 
106
  if __name__ == "__main__":
107
+ demo.launch(theme=gr.themes.Soft(primary_hue="purple"), show_error=True)