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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""
Score loader module for converting MIDI/MusicXML files into our data structures.

This module provides a robust wrapper around music21 to handle various input formats
and edge cases while producing clean, validated Score objects.
"""

from pathlib import Path
from fractions import Fraction
from typing import Optional, List, Tuple, Dict
import logging

try:
    from music21 import converter, stream, note, chord as m21_chord, meter, tempo
    from music21.stream import Score as M21Score, Part, Measure, Voice
except ImportError:
    raise ImportError(
        "music21 is required for score loading. Install with: pip install music21"
    )

from .data_structures import (
    Score,
    MusicalEvent,
    TimeSignature,
)

logger = logging.getLogger(__name__)


class ScoreLoadError(Exception):
    """Raised when a score cannot be loaded."""
    pass


class ScoreLoader:
    """
    Loads musical scores from MIDI or MusicXML files into Score objects.
    
    This class handles:
    - Multiple file formats (MIDI, MusicXML, etc.)
    - Multi-voice and multi-part scores
    - Time signature detection and changes
    - Proper temporal alignment
    - Beat strength calculation
    - Metadata extraction
    """
    
    def __init__(
        self,
        quantize_tolerance: Optional[Fraction] = None,
        separate_voices: bool = True,
    ):
        """
        Initialize the score loader.

        Args:
            quantize_tolerance: Optional tolerance for quantizing note onsets.
                              If None, no quantization is performed.
            separate_voices: When True, preserve separate voices/parts (needed
                           for chorales). When False, flatten everything to
                           voice 0 (appropriate for monophonic scores like
                           cello suites).
        """
        self.quantize_tolerance = quantize_tolerance
        self.separate_voices = separate_voices
        self._cached_time_sigs: Optional[List[Tuple[Fraction, TimeSignature]]] = None
        self._cached_time_sigs_score_id: Optional[int] = None
    
    def load(self, filepath: str | Path) -> Score:
        """
        Load a score from a file.
        
        Args:
            filepath: Path to MIDI or MusicXML file
            
        Returns:
            Score object with all musical events and metadata
            
        Raises:
            ScoreLoadError: If the file cannot be loaded or parsed
        """
        filepath = Path(filepath)
        
        if not filepath.exists():
            raise ScoreLoadError(f"File not found: {filepath}")
        
        # Validate file extension
        valid_extensions = {'.mid', '.midi', '.xml', '.mxl', '.musicxml'}
        if filepath.suffix.lower() not in valid_extensions:
            raise ScoreLoadError(
                f"Unsupported file format: {filepath.suffix}. "
                f"Supported formats: {', '.join(valid_extensions)}"
            )
        
        logger.info(f"Loading score from: {filepath}")
        
        try:
            # Load score with music21
            m21_score = converter.parse(str(filepath))
            
            # Extract components
            events = self._extract_events(m21_score)
            time_signatures = self._extract_time_signatures(m21_score)
            metadata = self._extract_metadata(m21_score, filepath)
            
            # Create Score object
            score = Score(
                events=events,
                time_signatures=time_signatures,
                title=metadata.get('title'),
                composer=metadata.get('composer'),
                tempo=metadata.get('tempo'),
                metadata=metadata
            )
            
            logger.info(
                f"Loaded score: {len(events)} events, "
                f"{score.num_voices} voices, "
                f"duration={float(score.duration):.2f} quarters"
            )
            
            return score

        except Exception as e:
            raise ScoreLoadError(f"Failed to load {filepath}: {str(e)}") from e

    def load_from_m21(self, m21_score, filepath: str = "<corpus>") -> Score:
        """
        Convert an already-parsed music21 Score into our Score type.

        Useful when the caller has loaded a music21 score via corpus.parse()
        or any other means and wants to run it through our pipeline.

        Args:
            m21_score: A music21 Score (or stream) object.
            filepath:  Optional label for logging — not used for file access.

        Returns:
            Score object with all musical events and metadata.
        """
        events = self._extract_events(m21_score)
        time_signatures = self._extract_time_signatures(m21_score)
        metadata = self._extract_metadata(m21_score, Path(filepath))
        return Score(
            events=events,
            time_signatures=time_signatures,
            title=metadata.get('title'),
            composer=metadata.get('composer'),
            tempo=metadata.get('tempo'),
            metadata=metadata,
        )

    def load_corpus(self, bwv: str) -> Score:
        """
        Load a score from music21's built-in corpus by BWV number.

        Args:
            bwv: BWV number as a string, e.g. '846', '66.6', '1007'.

        Returns:
            Score object ready for the analysis pipeline.

        Raises:
            ScoreLoadError: If the corpus entry cannot be found or parsed.
        """
        try:
            from music21 import corpus
            m21_score = corpus.parse(f'bwv{bwv}')
            return self.load_from_m21(m21_score, filepath=f"<corpus:bwv{bwv}>")
        except Exception as e:
            raise ScoreLoadError(f"Failed to load corpus bwv{bwv}: {e}") from e

    def _extract_events(self, m21_score: M21Score) -> List[MusicalEvent]:
        """
        Extract all musical events from a music21 score.
        
        Args:
            m21_score: music21 Score object
            
        Returns:
            List of MusicalEvent objects
        """
        events: List[MusicalEvent] = []

        # Get all parts (instruments/voices)
        parts = m21_score.parts if hasattr(m21_score, 'parts') else [m21_score]

        if not self.separate_voices:
            # Flatten everything into voice 0
            flat = m21_score.flatten()
            events.extend(self._extract_voice_events(flat, 0, m21_score))
            return events

        global_voice = 0
        for part_idx, part in enumerate(parts):
            voice_streams = self._get_voices(part)
            for voice_stream in voice_streams:
                voice_events = self._extract_voice_events(
                    voice_stream, global_voice, m21_score
                )
                events.extend(voice_events)
                global_voice += 1

        return events
    
    def _get_voices(self, part: Part) -> List[stream.Stream]:
        """
        Get all voices from a part, handling both single-voice and multi-voice parts.

        Iterates through measures, collects Voice objects, and builds per-voice
        streams with correct global offsets.

        Args:
            part: music21 Part object

        Returns:
            List of voice streams (one per distinct voice found)
        """
        # Discover the maximum number of voices across all measures
        voice_ids: Dict[str, int] = {}
        for m in part.getElementsByClass(Measure):
            for v in m.voices:
                vid = v.id
                if vid not in voice_ids:
                    voice_ids[vid] = len(voice_ids)

        if not voice_ids:
            # Single-voice part — return the flattened part
            return [part.flatten()]

        # Build one stream per voice, collecting notes from each measure
        voice_streams: List[stream.Stream] = [stream.Stream() for _ in voice_ids]

        for m in part.getElementsByClass(Measure):
            measure_offset = m.offset
            m_voices = m.voices
            if m_voices:
                for v in m_voices:
                    idx = voice_ids.get(v.id)
                    if idx is None:
                        continue
                    for el in v.notesAndRests:
                        imported = el
                        voice_streams[idx].insert(
                            measure_offset + el.offset, imported
                        )
            else:
                # Measure has no explicit voices — assign to voice 0
                for el in m.notesAndRests:
                    voice_streams[0].insert(measure_offset + el.offset, el)

        return voice_streams
    
    def _extract_voice_events(
        self, 
        voice_stream: stream.Stream, 
        voice_num: int,
        m21_score: M21Score
    ) -> List[MusicalEvent]:
        """
        Extract events from a single voice.
        
        Args:
            voice_stream: music21 stream for this voice
            voice_num: Global voice number
            m21_score: Full score for context
            
        Returns:
            List of MusicalEvent objects
        """
        events = []
        
        # Get all notes and rests
        for element in voice_stream.flatten().notesAndRests:
            onset = Fraction(element.offset)
            duration = Fraction(element.quarterLength)
            
            # Get measure and beat information
            measure_num, beat_pos = self._get_measure_and_beat(element, m21_score)
            
            # Get time signature at this position
            time_sig = self._get_time_signature_at_offset(m21_score, onset)
            
            # Calculate beat strength
            beat_strength = self._calculate_beat_strength(beat_pos, time_sig)
            
            # Handle notes vs rests
            if isinstance(element, note.Rest):
                event = MusicalEvent(
                    pitch=None,
                    onset=onset,
                    duration=duration,
                    velocity=0,
                    measure=measure_num,
                    beat=beat_pos,
                    beat_strength=beat_strength,
                    voice=voice_num,
                    is_rest=True
                )
                events.append(event)
            
            elif isinstance(element, note.Note):
                event = MusicalEvent(
                    pitch=element.pitch.midi,
                    onset=onset,
                    duration=duration,
                    velocity=element.volume.velocity or 64,
                    measure=measure_num,
                    beat=beat_pos,
                    beat_strength=beat_strength,
                    voice=voice_num,
                    is_rest=False
                )
                events.append(event)
            
            elif isinstance(element, m21_chord.Chord):
                # Expand chords into individual notes with same onset
                for pitch in element.pitches:
                    event = MusicalEvent(
                        pitch=pitch.midi,
                        onset=onset,
                        duration=duration,
                        velocity=element.volume.velocity or 64,
                        measure=measure_num,
                        beat=beat_pos,
                        beat_strength=beat_strength,
                        voice=voice_num,
                        is_rest=False
                    )
                    events.append(event)
        
        return events
    
    def _get_measure_and_beat(
        self, 
        element: note.GeneralNote, 
        m21_score: M21Score
    ) -> Tuple[int, Fraction]:
        """
        Get the measure number and beat position for an element.
        
        Args:
            element: music21 note or rest
            m21_score: Full score for context
            
        Returns:
            Tuple of (measure_number, beat_position)
        """
        # Try to get measure number from the element's context
        try:
            measure = element.getContextByClass(Measure)
            if measure and measure.number is not None:
                measure_num = measure.number
            else:
                measure_num = 1
        except:
            measure_num = 1
        
        # Calculate beat position within measure
        try:
            measure = element.getContextByClass(Measure)
            if measure:
                beat_pos = Fraction(element.offset - measure.offset)
            else:
                # Fallback: use offset modulo measure length
                time_sig = self._get_time_signature_at_offset(
                    m21_score, 
                    Fraction(element.offset)
                )
                measure_length = Fraction(
                    time_sig.numerator * 4,
                    time_sig.denominator
                )
                beat_pos = Fraction(element.offset) % measure_length
        except:
            beat_pos = Fraction(0)
        
        return measure_num, beat_pos
    
    def _calculate_beat_strength(
        self, 
        beat_pos: Fraction, 
        time_sig: TimeSignature
    ) -> float:
        """
        Calculate metric strength for a position in a measure.
        
        This is a preliminary implementation. Will be replaced by
        meter_analyzer.py for more sophisticated metric hierarchy.
        
        Args:
            beat_pos: Position within measure in quarter notes
            time_sig: Current time signature
            
        Returns:
            Beat strength from 0.0 (weakest) to 1.0 (downbeat)
        """
        # Downbeat is always strongest
        if beat_pos == 0:
            return 1.0
        
        # Convert position to beat units
        beat_duration = time_sig.beat_duration
        beat_number = beat_pos / beat_duration
        
        # Simple metric hierarchy based on beat position
        if time_sig.is_compound:
            # Compound meters: strong on 1, medium on other main beats
            beat_in_measure = int(beat_number)
            if beat_in_measure == 0:
                return 1.0
            elif beat_number == int(beat_number):  # On main beat
                return 0.6
            else:
                return 0.3
        else:
            # Simple meters
            beat_in_measure = int(beat_number)
            subdivision = beat_number - beat_in_measure
            
            if beat_in_measure == 0:
                return 1.0
            elif beat_in_measure == 2 and time_sig.numerator == 4:
                # Beat 3 in 4/4
                return 0.5
            elif subdivision == 0:
                # On a main beat
                return 0.6
            elif subdivision == 0.5:
                # Eighth note subdivision
                return 0.3
            else:
                # Finer subdivision
                return 0.2
    
    def _extract_time_signatures(
        self, 
        m21_score: M21Score
    ) -> List[Tuple[Fraction, TimeSignature]]:
        """
        Extract all time signatures and their positions from the score.
        
        Args:
            m21_score: music21 Score object
            
        Returns:
            List of (onset, TimeSignature) tuples
        """
        time_signatures = []
        
        # Get all time signature elements
        for ts in m21_score.flatten().getElementsByClass(meter.TimeSignature):
            onset = Fraction(ts.offset)
            time_sig = TimeSignature(
                numerator=int(ts.numerator),
                denominator=int(ts.denominator)
            )
            time_signatures.append((onset, time_sig))
        
        # If no time signatures found, default to 4/4
        if not time_signatures:
            logger.warning("No time signature found, defaulting to 4/4")
            time_signatures.append((Fraction(0), TimeSignature(4, 4)))
        
        return time_signatures
    
    def _get_time_signature_at_offset(
        self,
        m21_score: M21Score,
        onset: Fraction
    ) -> TimeSignature:
        """
        Get the time signature in effect at a given offset.

        Uses a per-score cache so that ``_extract_time_signatures`` is only
        called once per score rather than once per note.

        Args:
            m21_score: music21 Score object
            onset: Position in quarter notes

        Returns:
            TimeSignature in effect at that position
        """
        score_id = id(m21_score)
        if self._cached_time_sigs is None or self._cached_time_sigs_score_id != score_id:
            self._cached_time_sigs = self._extract_time_signatures(m21_score)
            self._cached_time_sigs_score_id = score_id

        current_ts = self._cached_time_sigs[0][1]
        for ts_onset, ts in self._cached_time_sigs:
            if ts_onset > onset:
                break
            current_ts = ts

        return current_ts
    
    def _extract_metadata(
        self, 
        m21_score: M21Score, 
        filepath: Path
    ) -> Dict[str, any]:
        """
        Extract metadata from the score.
        
        Args:
            m21_score: music21 Score object
            filepath: Path to the source file
            
        Returns:
            Dictionary of metadata
        """
        metadata = {
            'source_file': str(filepath),
            'file_format': filepath.suffix.lower()
        }
        
        # Extract title
        if hasattr(m21_score, 'metadata') and m21_score.metadata:
            if m21_score.metadata.title:
                metadata['title'] = m21_score.metadata.title
            if m21_score.metadata.composer:
                metadata['composer'] = m21_score.metadata.composer
        
        # Use filename as fallback title
        if 'title' not in metadata:
            metadata['title'] = filepath.stem
        
        # Extract tempo (MetronomeMark.number may be None for text-only marks)
        tempo_marks = m21_score.flatten().getElementsByClass(tempo.MetronomeMark)
        if tempo_marks and tempo_marks[0].number is not None:
            metadata['tempo'] = int(tempo_marks[0].number)
        
        # Count parts and measures
        parts = m21_score.parts if hasattr(m21_score, 'parts') else [m21_score]
        metadata['num_parts'] = len(parts)
        
        measures = m21_score.flatten().getElementsByClass(Measure)
        if measures:
            metadata['num_measures'] = len(measures)
        
        return metadata


def load_score(filepath: str | Path, **kwargs) -> Score:
    """
    Convenience function to load a score.
    
    Args:
        filepath: Path to MIDI or MusicXML file
        **kwargs: Additional arguments passed to ScoreLoader
        
    Returns:
        Score object
        
    Example:
        >>> score = load_score("bach_cello_suite_1.mid")
        >>> print(f"Loaded {len(score.events)} events")
    """
    loader = ScoreLoader(**kwargs)
    return loader.load(filepath)