File size: 9,072 Bytes
30755d9
 
 
 
 
 
c43c03a
30755d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3672ad1
 
 
 
 
 
 
 
 
 
 
 
 
 
30755d9
 
c43c03a
3672ad1
 
 
 
 
 
 
c43c03a
 
 
30755d9
3672ad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30755d9
 
 
3672ad1
30755d9
 
 
3672ad1
c43c03a
30755d9
 
 
 
c43c03a
 
30755d9
3672ad1
c43c03a
3672ad1
 
c43c03a
 
 
 
 
 
 
3672ad1
 
 
 
 
 
c43c03a
30755d9
 
c43c03a
30755d9
 
3672ad1
30755d9
3672ad1
c43c03a
 
3672ad1
 
 
 
 
 
c43c03a
 
 
3672ad1
 
 
 
 
 
 
 
 
 
 
 
30755d9
3672ad1
 
 
 
30755d9
3672ad1
 
 
 
 
c43c03a
30755d9
3672ad1
c43c03a
 
 
 
 
 
 
3672ad1
 
c43c03a
 
 
 
 
 
 
 
 
 
 
 
 
30755d9
3672ad1
c43c03a
3672ad1
c43c03a
3672ad1
 
 
 
 
 
 
 
 
30755d9
 
c43c03a
 
 
 
30755d9
 
c43c03a
3672ad1
c43c03a
3672ad1
30755d9
c43c03a
30755d9
c43c03a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import random
import argparse
import glob
import json
import os
import time
import rtmidi
from concurrent.futures import ThreadPoolExecutor

import gradio as gr
import numpy as np
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from transformers import DynamicCache

import MIDI
from midi_model import MIDIModel, MIDIModelConfig
from midi_synthesizer import MidiSynthesizer

MAX_SEED = np.iinfo(np.int32).max
in_space = os.getenv("SYSTEM") == "spaces"

# Chord definitions and emoji mappings remain the same
# ... (keeping your CHORD_EMOJIS and CHORD_NOTES dictionaries)

# Example song data for "Do You Believe in Love"
SONG_DATA = {
    "title": "Do You Believe in Love",
    "artist": "Huey Lewis and the News",
    "progression": ["G", "D", "Em", "C"],  # Simplified progression
    "lyrics": [
        "I was walking down a one-way street",
        "Just a-looking for someone to meet",
        "One woman who was looking for a man",
        "Now I'm hoping that the feeling is right"
    ]
}

class MIDIDeviceManager:
    # ... (keeping your existing MIDIDeviceManager class)
    def get_device_info(self):
        """Return detailed info about connected MIDI devices"""
        devices = self.get_available_devices()
        if not devices:
            return "No MIDI devices detected"
        return "\n".join([f"Port {i}: {name}" for i, name in enumerate(devices)])

# Global MIDI manager
midi_manager = MIDIDeviceManager()

def analyze_midi_file(midi_file_path):
    """Analyze uploaded MIDI file to extract chord progression"""
    try:
        midi = MIDI.load(midi_file_path)
        # Simple chord detection (this could be expanded with proper analysis)
        detected_chords = []
        for track in midi.tracks:
            current_chord = []
            for event in track.events:
                if event.type == 'note_on' and event.velocity > 0:
                    current_chord.append(event.note)
                if len(current_chord) >= 3:  # Basic triad detection
                    for chord_name, notes in CHORD_NOTES.items():
                        if set(current_chord[:3]) == set(notes[:3]):
                            detected_chords.append(chord_name)
                            current_chord = []
                            break
        return detected_chords if detected_chords else SONG_DATA["progression"]
    except Exception as e:
        return SONG_DATA["progression"]  # Fallback to example progression

def generate_chord_sheet(chords, lyrics):
    """Generate a formatted chord sheet with chords and lyrics"""
    sheet = ""
    for i, (chord, lyric) in enumerate(zip(chords * (len(lyrics) // len(chords) + 1), lyrics)):
        sheet += f"{CHORD_EMOJIS.get(chord, 'šŸŽµ')} {chord}\n"
        sheet += f"{lyric}\n\n"
    return sheet

def create_chord_visualizer(chords, lyrics):
    """Create HTML visualization for chord sheet"""
    html = "<div style='font-family: monospace; line-height: 1.5;'>"
    for i, (chord, lyric) in enumerate(zip(chords * (len(lyrics) // len(chords) + 1), lyrics)):
        html += f"<div style='margin-bottom: 10px;'>"
        html += f"<span style='color: #2196F3; font-weight: bold;'>{CHORD_EMOJIS.get(chord, 'šŸŽµ')} {chord}</span>"
        html += f"<br>{lyric}</div>"
    html += "</div>"
    return html

# ... (keeping your existing helper functions like create_msg, etc.)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # ... (keeping your existing parser arguments)
    opt = parser.parse_args()
    OUTPUT_BATCH_SIZE = opt.batch
    
    # Initialize MIDI components
    midi_manager = MIDIDeviceManager()
    soundfont_path = hf_hub_download_retry(repo_id="skytnt/midi-model", filename="soundfont.sf2")
    thread_pool = ThreadPoolExecutor(max_workers=OUTPUT_BATCH_SIZE)
    synthesizer = MidiSynthesizer(soundfont_path)
    
    chord_types = ['', 'm', '7', 'maj7', 'm7']
    keyboard = create_virtual_keyboard(chord_types)
    
    # Enhanced CSS with visualizer styling
    keyboard_css = """
    .chord-button { /* ... existing styles ... */ }
    .chord-queue { /* ... existing styles ... */ }
    .root-c { background-color: #FFCDD2; }
    .root-d { background-color: #F8BBD0; }
    .root-e { background-color: #E1BEE7; }
    .root-f { background-color: #D1C4E9; }
    .root-g { background-color: #C5CAE9; }
    .root-a { background-color: #BBDEFB; }
    .root-b { background-color: #B3E5FC; }
    .visualizer-container {
        background: #f9f9f9;
        padding: 15px;
        border-radius: 8px;
        margin-top: 15px;
    }
    """
    
    load_javascript()
    app = gr.Blocks(theme=gr.themes.Soft(), css=keyboard_css)
    
    with app:
        gr.Markdown("<h1 style='text-align: center;'>šŸŽµ Chord Sheet Generator & Visualizer šŸŽµ</h1>")
        
        # MIDI Device Info
        with gr.Row():
            with gr.Column(scale=3):
                midi_device = gr.Dropdown(label="MIDI Output Device",
                                        choices=midi_manager.get_available_devices(),
                                        type="index")
                device_info = gr.Textbox(label="Connected MIDI Devices",
                                       value=midi_manager.get_device_info(),
                                       readonly=True)
                refresh_button = gr.Button("šŸ”„ Refresh MIDI Devices")
            
            with gr.Column(scale=1):
                tempo = gr.Slider(label="Tempo (BPM)",
                                minimum=40,
                                maximum=200,
                                value=120,
                                step=1)

        # MIDI File Upload and Chord Sheet Generation
        with gr.Row():
            midi_upload = gr.File(label="Upload MIDI File for Analysis")
            chord_output = gr.Textbox(label="Generated Chord Sheet",
                                    lines=10,
                                    value=generate_chord_sheet(SONG_DATA["progression"], SONG_DATA["lyrics"]))
        
        # Chord Visualizer
        visualizer = gr.HTML(label="Chord Sheet Visualizer",
                           value=create_chord_visualizer(SONG_DATA["progression"], SONG_DATA["lyrics"]),
                           elem_classes=["visualizer-container"])
        
        # Chord Queue and Playback
        chord_queue = gr.State([])
        queue_display = gr.Markdown("### Current Chord Queue\n*No chords in queue*",
                                  elem_classes=["chord-queue"])
        play_queue_button = gr.Button("ā–¶ļø Play Chord Sequence", variant="primary")
        clear_queue_button = gr.Button("šŸ—‘ļø Clear Queue", variant="secondary")
        
        # Virtual Keyboard
        gr.Markdown("## Virtual Chord Keyboard")
        for root in ['C', 'D', 'E', 'F', 'G', 'A', 'B']:
            with gr.Row():
                gr.Markdown(f"### {root}")
                for chord_type in chord_types:
                    chord_name, emoji = keyboard[root][chord_type]
                    display_name = chord_name if chord_type == '' else chord_name
                    button = gr.Button(f"{emoji} {display_name}",
                                     elem_classes=[f"chord-button root-{root.lower()}"])
                    button.click(
                        fn=play_chord_on_device,
                        inputs=[gr.State(chord_name), midi_device],
                        outputs=None
                    ).then(
                        fn=add_chord_to_queue,
                        inputs=[gr.State(chord_name), chord_queue],
                        outputs=[chord_queue]
                    ).then(
                        fn=lambda q: f"### Current Chord Queue\n" + " ā†’ ".join(q) if q else "*No chords in queue*",
                        inputs=[chord_queue],
                        outputs=[queue_display]
                    )
        
        # Event Handlers
        refresh_button.click(
            fn=lambda: (midi_manager.get_available_devices(), midi_manager.get_device_info()),
            inputs=None,
            outputs=[midi_device, device_info]
        )
        
        midi_upload.change(
            fn=lambda file: (analyze_midi_file(file.name),
                           generate_chord_sheet(analyze_midi_file(file.name), SONG_DATA["lyrics"]),
                           create_chord_visualizer(analyze_midi_file(file.name), SONG_DATA["lyrics"])),
            inputs=[midi_upload],
            outputs=[chord_queue, chord_output, visualizer]
        )
        
        play_queue_button.click(
            fn=play_chord_sequence,
            inputs=[chord_queue, midi_device, tempo],
            outputs=[chord_queue]
        )
        
        clear_queue_button.click(
            fn=lambda: ([], "### Current Chord Queue\n*No chords in queue*"),
            inputs=None,
            outputs=[chord_queue, queue_display]
        )
    
    app.queue().launch(server_port=opt.port, share=opt.share, inbrowser=True, ssr_mode=False)
    midi_manager.close()