File size: 8,512 Bytes
330f477
 
 
 
8494801
 
330f477
 
 
 
 
 
 
 
 
8494801
 
 
 
 
 
330f477
8494801
330f477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8494801
330f477
 
 
 
8494801
330f477
 
 
 
 
 
 
 
 
8494801
330f477
 
 
 
 
8494801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330f477
 
 
 
 
 
 
8494801
330f477
 
 
 
8494801
 
 
 
 
 
 
 
330f477
8494801
330f477
 
 
 
 
 
8494801
330f477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8494801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330f477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8494801
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path

import numpy as np

from openmusic_analysis.analyzers import (
    BGEM3LyricsAnalyzer,
    BGEM3TextEncoder,
    ClapAudioEncoder,
    ClapGlobalAudioAnalyzer,
    ClapTemporalAudioAnalyzer,
    LyricsPreprocessor,
)
from openmusic_analysis.audio import AnalysisContext, AudioDecoder
from openmusic_analysis.domain import (
    AnalysisResponse,
    LyricsResolution,
    ResolvedTrackMetadata,
    TrackReference,
)
from openmusic_analysis.errors import AnalysisError
from openmusic_analysis.lyrics_resolution import LyricsLookupInput, LyricsResolver
from openmusic_analysis.registry import ModelRegistry
from openmusic_analysis.runtime import DeviceManager, InferenceGate
from openmusic_analysis.settings import Settings


DEFAULT_AUDIO_REPRESENTATIONS = ("audio.global", "audio.temporal")


class MusicAnalysisService:
    def __init__(
        self,
        *,
        registry: ModelRegistry,
        decoder: AudioDecoder,
        device: str,
        lyrics_resolver: LyricsResolver | None = None,
    ) -> None:
        self.registry = registry
        self.decoder = decoder
        self.device = device
        self.lyrics_resolver = lyrics_resolver

    async def analyze(
        self,
        source_path: str | Path,
        *,
        lyrics: str | None,
        requested_representations: list[str] | None,
        track_id: str | None,
        content_identity: str | None,
        lyrics_metadata: LyricsLookupInput | None = None,
    ) -> AnalysisResponse:
        if lyrics is not None and not lyrics.strip():
            raise AnalysisError(
                "INVALID_LYRICS", "Lyrics must contain non-whitespace text.", status_code=422
            )
        should_resolve_lyrics = requested_representations is None or (
            "lyrics.global" in requested_representations
        )
        lyrics_resolution: LyricsResolution | None = None
        effective_lyrics = lyrics
        if lyrics is not None or should_resolve_lyrics:
            lyrics_resolution = await self.resolve_lyrics(
                source_path,
                provided_lyrics=lyrics,
                supplied_metadata=lyrics_metadata,
            )
            effective_lyrics = lyrics_resolution.text

        requested = self._resolve_representations(
            requested_representations, effective_lyrics
        )
        context = AnalysisContext(source_path, self.decoder)
        results = {}
        for representation in requested:
            analyzer = self.registry.analyzer(representation)
            if analyzer.input_kind == "audio":
                result = await analyzer.analyze(context)
            elif analyzer.input_kind == "lyrics":
                if effective_lyrics is None:
                    raise AnalysisError(
                        "LYRICS_REQUIRED",
                        f"Representation '{representation}' requires lyrics.",
                        status_code=422,
                        details={
                            "fallback_errors": [
                                error.model_dump()
                                for error in (
                                    lyrics_resolution.errors if lyrics_resolution else []
                                )
                            ]
                        },
                    )
                result = await analyzer.analyze(effective_lyrics)
            else:
                raise RuntimeError(f"Unknown analyzer input kind: {analyzer.input_kind}")
            results[representation] = result
        return AnalysisResponse(
            track=TrackReference(track_id=track_id, content_identity=content_identity),
            representations=results,
            lyrics=lyrics_resolution,
        )

    def _resolve_representations(
        self, requested: list[str] | None, lyrics: str | None
    ) -> list[str]:
        if requested is None:
            values = list(DEFAULT_AUDIO_REPRESENTATIONS)
            if lyrics is not None:
                values.append("lyrics.global")
        else:
            values = list(dict.fromkeys(requested))
            if not values:
                raise AnalysisError(
                    "INVALID_REPRESENTATIONS",
                    "requested_representations must not be empty.",
                    status_code=422,
                )
        unsupported = [value for value in values if value not in self.registry.representations]
        if unsupported:
            raise AnalysisError(
                "UNSUPPORTED_REPRESENTATION",
                f"Unsupported representation(s): {', '.join(unsupported)}.",
                status_code=422,
                details={"supported": list(self.registry.representations)},
            )
        return values

    async def load_models(self) -> None:
        seen: set[int] = set()
        for representation in self.registry.representations:
            analyzer = self.registry.analyzer(representation)
            encoder = getattr(analyzer, "encoder", None)
            if encoder is not None and id(encoder) not in seen:
                seen.add(id(encoder))
                await encoder.ready()

    async def rank_similar_audio(
        self,
        target_source_path: str | Path,
        candidate_source_paths: list[str | Path],
    ) -> list[tuple[int, float]]:
        """Rank candidates by cosine similarity in the global CLAP space."""
        analyzer = self.registry.analyzer("audio.global")
        target = await analyzer.analyze(AnalysisContext(target_source_path, self.decoder))
        target_embedding = np.asarray(target.embedding, dtype=np.float32)

        scores: list[tuple[int, float]] = []
        for index, source_path in enumerate(candidate_source_paths):
            candidate = await analyzer.analyze(AnalysisContext(source_path, self.decoder))
            candidate_embedding = np.asarray(candidate.embedding, dtype=np.float32)
            similarity = float(np.dot(target_embedding, candidate_embedding))
            scores.append((index, float(np.clip(similarity, -1.0, 1.0))))

        return sorted(scores, key=lambda item: (-item[1], item[0]))

    async def resolve_lyrics(
        self,
        source_path: str | Path,
        *,
        provided_lyrics: str | None = None,
        supplied_metadata: LyricsLookupInput | None = None,
    ) -> LyricsResolution:
        metadata = supplied_metadata or LyricsLookupInput()
        if provided_lyrics and provided_lyrics.strip():
            return LyricsResolution(
                text=provided_lyrics,
                source="request",
                metadata=ResolvedTrackMetadata(
                    title=metadata.title,
                    artist=metadata.artist,
                    album=metadata.album,
                    isrc=metadata.isrc,
                    duration_seconds=metadata.duration_seconds,
                ),
            )
        if self.lyrics_resolver is None:
            return LyricsResolution()
        return await self.lyrics_resolver.resolve(
            source_path,
            provided_lyrics=provided_lyrics,
            supplied_metadata=metadata,
        )


def build_service(settings: Settings | None = None) -> MusicAnalysisService:
    settings = settings or Settings.from_env()
    device = DeviceManager.select(settings.device)
    gate = InferenceGate(settings.inference_concurrency)
    clap_encoder = ClapAudioEncoder(
        device, gate, batch_size=settings.global_audio.inference_batch_size
    )
    text_encoder = BGEM3TextEncoder(device, gate)
    analyzers = [
        ClapGlobalAudioAnalyzer(clap_encoder, settings.global_audio),
        ClapTemporalAudioAnalyzer(clap_encoder, settings.temporal_audio),
        BGEM3LyricsAnalyzer(text_encoder, LyricsPreprocessor(), settings.lyrics),
    ]
    registry = ModelRegistry(analyzers)
    decoder = AudioDecoder(
        ffmpeg_binary=settings.ffmpeg_binary,
        ffprobe_binary=settings.ffprobe_binary,
        canonical_sample_rate=settings.global_audio.sample_rate,
        max_audio_seconds=settings.limits.max_audio_seconds,
        timeout_seconds=settings.limits.decode_timeout_seconds,
    )
    lyrics_resolver = LyricsResolver(
        settings.lyrics_fallback,
        ffmpeg_binary=settings.ffmpeg_binary,
        ffprobe_binary=settings.ffprobe_binary,
    )
    return MusicAnalysisService(
        registry=registry,
        decoder=decoder,
        device=device,
        lyrics_resolver=lyrics_resolver,
    )