File size: 6,407 Bytes
7acbfbc
9efec35
5fcd2c4
 
7acbfbc
9efec35
 
 
 
 
e2d00e1
 
7acbfbc
9efec35
ad89268
e2d00e1
ad89268
e2d00e1
9efec35
7acbfbc
 
23f8cc2
7acbfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9efec35
 
 
 
 
 
 
 
7acbfbc
 
e2d00e1
5fcd2c4
e2d00e1
7acbfbc
 
 
 
 
9efec35
 
7acbfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2d00e1
 
 
5fcd2c4
e2d00e1
 
 
 
 
 
 
 
 
 
 
 
9efec35
e2d00e1
 
9efec35
e2d00e1
 
9efec35
e2d00e1
 
 
 
 
 
 
 
 
9efec35
e2d00e1
 
 
 
 
 
 
9efec35
e2d00e1
989811e
5fcd2c4
 
 
 
 
 
 
 
 
 
9efec35
 
7acbfbc
9efec35
7acbfbc
 
9efec35
 
7acbfbc
9efec35
 
 
7acbfbc
 
 
 
9efec35
7acbfbc
 
 
16a8746
 
 
9efec35
 
7acbfbc
9efec35
 
 
e2d00e1
 
7acbfbc
 
989811e
 
7acbfbc
 
989811e
 
9efec35
 
7acbfbc
e2d00e1
9efec35
 
7acbfbc
 
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
import os
import torch

# import spacy
import spotipy
import numpy as np
import gradio as gr
import torch.nn as nn
import torch.nn.functional as F

from sklearn.preprocessing import StandardScaler
from transformers import AutoModel, AutoTokenizer
from spotipy.oauth2 import SpotifyClientCredentials

# from dotenv import load_dotenv

# load_dotenv()


class ConfigApp:
    REPO_NAME = "PunGrumpy/music-genre-classification"
    GENRE_MAPPING = {"pop": 0, "rap": 1, "rock": 2, "r&b": 3, "edm": 4}
    AUDIO_FEATURES = {
        "acousticness": 0,
        "danceability": 0,
        "energy": 0,
        "instrumentalness": 0,
        "key": 0,
        "liveness": 0,
        "loudness": 0,
        "mode": 0,
        "speechiness": 0,
        "tempo": 0,
        "valence": 0,
    }
    SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
    SPOTIFY_ACCESS_TOKEN = os.getenv("SPOTIFY_ACCESS_TOKEN")


class LyricsAudioModelInference:
    def __init__(self, model_name, num_labels=5):
        self.model = AutoModel.from_pretrained(model_name)
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.num_labels = num_labels
        self.classifier = nn.Linear(
            self.model.config.hidden_size + len(ConfigApp.AUDIO_FEATURES), num_labels
        )
        self.scaler = StandardScaler()
        # self.nlp = spacy.load("en_core_web_sm")

        self.sp = spotipy.Spotify(
            client_credentials_manager=SpotifyClientCredentials(
                client_id=ConfigApp.SPOTIFY_CLIENT_ID,
                client_secret=ConfigApp.SPOTIFY_ACCESS_TOKEN,
            )
        )

    def get_audio_features(self, spotify_track_link: str) -> list:
        track_id = spotify_track_link.split("/")[-1].split("?")[0]
        audio_features = self.sp.audio_features(track_id)
        audio_features = [
            audio_features[0][feature] for feature in ConfigApp.AUDIO_FEATURES
        ]
        return audio_features

    def get_track_info(self, spotify_track_link: str) -> dict:
        track_id = spotify_track_link.split("/")[-1].split("?")[0]
        track_info = self.sp.track(track_id)
        song_name = track_info.get("name", "Unknown")
        artist_name = ", ".join(
            [artist["name"] for artist in track_info.get("artists", [])]
        )
        return {"Song Name": song_name, "Artist Name": artist_name}

    def predict_genre(self, lyrics: str, spotify_track_link: str) -> dict:
        with torch.no_grad():
            self.model.eval()

            # lyrics = self._preprocess_lyrics(lyrics)
            input_lyrics = self.tokenizer(
                lyrics,
                None,
                return_tensors="pt",
                padding=True,
                truncation=True,
                max_length=512,
            )
            audio_features = self.get_audio_features(spotify_track_link)
            audio_features = self.scaler.fit_transform(
                np.array(audio_features).reshape(1, -1)
            )

            outputs = self.model(**input_lyrics)
            lyrics_embedding = outputs.last_hidden_state.mean(dim=1)

            if audio_features is not None:
                audio_features = list(audio_features)

                input_features = torch.cat(
                    [lyrics_embedding, torch.tensor(audio_features).float()],
                    dim=1,
                )
            else:
                input_features = lyrics_embedding

            logits = self.classifier(input_features)
            probs = F.softmax(logits, dim=1)

            top1_genre = torch.argmax(probs, dim=1)
            genre_label = [
                key.capitalize()
                for key, value in ConfigApp.GENRE.items()
                if value == top1_genre
            ][0]
            result = {genre_label: probs[0][top1_genre].item()}

            return result

    # def _preprocess_lyrics(self, text):
    #     doc = self.nlp(text)
    #     processed_text = " ".join(
    #         [
    #             token.lemma_.lower().strip()
    #             for token in doc
    #             if not token.is_stop and token.lemma_.isalpha() and not token.is_punct
    #         ]
    #     )
    #     return processed_text


with gr.Blocks() as demo:
    iface = gr.Interface(
        api_name="Music Genre Classifier",
        fn=LyricsAudioModelInference(model_name=ConfigApp.REPO_NAME).predict_genre,
        inputs=[
            gr.Textbox(
                lines=5,
                placeholder="Enter lyrics here...",
                label="Lyrics",
            ),
            gr.Textbox(
                lines=1,
                placeholder="Enter Spotify Track Link here...",
                label="Spotify Track Link",
            ),
        ],
        outputs=[
            gr.Label(
                num_top_classes=1,
                label="Predicted Genre",
                elem_id="genre",
            ),
        ],
        title="🎷 Music Genre Classifier",
        description="This model predicts the genre of a song based on its lyrics and audio features.",
        examples=[
            [
                "Standing in the rain, with his head hung low Couldn't get a ticket, it was a sold out show Heard the roar of the crowd, he could picture the scene Put his ear to the wall, then like a distant scream He heard one guitar, just blew him away He saw stars in his eyes, and the very next day Bought a beat up six string in a secondhand store",
                "https://open.spotify.com/track/00qOE7OjRl0BpYiCiweZB2",
            ],
            [
                "Intro They say, or at least they say that they say That reality is only what your mind chooses to believe If that's true, believe this I don't rap",
                "https://open.spotify.com/track/2j3JzMfQI2cGw4w2juWoD4",
            ],
            [
                "Mmmm, ay-oh Hey... Ratatat, yeah! Na-na-na-nah Na-na-na-nah Crush a bit, little bit, roll it up, take a hit Feelin' lit, feelin' right, 2 AM, summer night I don't care, hand on the wheel Driving drunk, I'm doing my thing Rolling in the Midwest side and out Living my life, getting out dreams People told me slow my roll, I'm screaming out 'Fuck that'",
                "https://open.spotify.com/track/3Uqn6QvA1IzVjhY0ngcZ9B",
            ],
        ],
        analytics_enabled=True,
        cache_examples=False,
    )


demo.launch(debug=True, show_api=True)