aditya20t commited on
Commit
0481720
·
1 Parent(s): 22a419e

Deploy music classifier app

Browse files
Files changed (3) hide show
  1. app.py +19 -0
  2. main.py +97 -0
  3. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Point this to your new Hub model ID
5
+ model_id = "aditya20t/distilhubert-musicClassifier"
6
+ classifier = pipeline("audio-classification", model=model_id)
7
+
8
+ def predict(audio):
9
+ preds = classifier(audio)
10
+ return {p["label"]: p["score"] for p in preds}
11
+
12
+ demo = gr.Interface(
13
+ fn=predict,
14
+ inputs=gr.Audio(type="filepath"),
15
+ outputs=gr.Label(num_top_classes=5),
16
+ title="Music Genre Classifier"
17
+ )
18
+
19
+ demo.launch()
main.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset, Audio
2
+ from transformers import AutoFeatureExtractor, AutoModelForAudioClassification, TrainingArguments, Trainer
3
+ import evaluate
4
+ import numpy as np
5
+ import gradio as gr
6
+
7
+ # Load the GTZAN dataset
8
+ gtzan = load_dataset("marsyas/gtzan", "all")
9
+ gtzan = gtzan["train"].train_test_split(seed=42, shuffle=True, test_size=0.1)
10
+ gtzan = gtzan.cast_column("audio", Audio(sampling_rate=16000))
11
+ print(gtzan['train'][0])
12
+
13
+ # Load the feature extractor
14
+ model_id = "ntu-spml/distilhubert"
15
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
16
+ model_id, do_normalize=True, return_attention_mask=True
17
+ )
18
+
19
+ max_duration = 30.0
20
+
21
+
22
+ def preprocess_function(examples):
23
+ audio_arrays = [x["array"] for x in examples["audio"]]
24
+ inputs = feature_extractor(
25
+ audio_arrays,
26
+ sampling_rate=feature_extractor.sampling_rate,
27
+ max_length=int(feature_extractor.sampling_rate * max_duration),
28
+ truncation=True,
29
+ return_attention_mask=True,
30
+ )
31
+ return inputs
32
+
33
+ gtzan_encoded = gtzan.map(
34
+ preprocess_function,
35
+ remove_columns=["audio", "file"],
36
+ batched=True,
37
+ batch_size=100,
38
+ num_proc=1,
39
+ )
40
+ gtzan_encoded = gtzan_encoded.rename_column("genre", "label")
41
+
42
+ id2label_fn = gtzan["train"].features["genre"].int2str
43
+ id2label = {
44
+ str(i): id2label_fn(i)
45
+ for i in range(len(gtzan_encoded["train"].features["label"].names))
46
+ }
47
+ label2id = {v: k for k, v in id2label.items()}
48
+
49
+ num_labels = len(id2label)
50
+
51
+ model = AutoModelForAudioClassification.from_pretrained(
52
+ model_id,
53
+ num_labels=num_labels,
54
+ label2id=label2id,
55
+ id2label=id2label,
56
+ )
57
+
58
+ model_name = model_id.split("/")[-1]
59
+ batch_size = 32
60
+ gradient_accumulation_steps = 1
61
+ num_train_epochs = 10
62
+
63
+ training_args = TrainingArguments(
64
+ f"{model_name}-finetuned-gtzan",
65
+ eval_strategy="epoch",
66
+ save_strategy="epoch",
67
+ learning_rate=5e-5,
68
+ per_device_train_batch_size=batch_size,
69
+ gradient_accumulation_steps=gradient_accumulation_steps,
70
+ per_device_eval_batch_size=batch_size,
71
+ num_train_epochs=num_train_epochs,
72
+ warmup_steps=100,
73
+ logging_steps=5,
74
+ load_best_model_at_end=True,
75
+ metric_for_best_model="accuracy",
76
+ fp16=True,
77
+ push_to_hub=False,
78
+ )
79
+
80
+ metric = evaluate.load("accuracy")
81
+
82
+
83
+ def compute_metrics(eval_pred):
84
+ """Computes accuracy on a batch of predictions"""
85
+ predictions = np.argmax(eval_pred.predictions, axis=1)
86
+ return metric.compute(predictions=predictions, references=eval_pred.label_ids)
87
+
88
+ trainer = Trainer(
89
+ model=model,
90
+ args=training_args,
91
+ train_dataset=gtzan_encoded["train"],
92
+ eval_dataset=gtzan_encoded["test"],
93
+ processing_class=feature_extractor,
94
+ compute_metrics=compute_metrics,
95
+ )
96
+
97
+ trainer.train()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ librosa
4
+ evaluate