Ubuntu commited on
Commit
a62f55f
·
1 Parent(s): ecf06c4
KAGGLE_NOTEBOOK.md DELETED
@@ -1,191 +0,0 @@
1
- # 🎵 Spotify Genre Classifier - Kaggle Notebook
2
-
3
- ## Cell 1: Install Dependencies
4
- ```python
5
- !pip install -q transformers datasets accelerate evaluate scikit-learn python-dotenv tqdm
6
- ```
7
-
8
- ## Cell 2: Import and Setup Secrets
9
- ```python
10
- from kaggle_secrets import UserSecretsClient
11
- import os
12
-
13
- # Get secrets from Kaggle
14
- user_secrets = UserSecretsClient()
15
- os.environ['HF_TOKEN'] = user_secrets.get_secret("HF_TOKEN")
16
- os.environ['HF_USERNAME'] = user_secrets.get_secret("HF_USERNAME")
17
-
18
- print(f"✓ Logged in as: {os.environ['HF_USERNAME']}")
19
- ```
20
-
21
- ## Cell 3: Check GPU
22
- ```python
23
- import torch
24
-
25
- if torch.cuda.is_available():
26
- print(f"✓ GPU Available: {torch.cuda.get_device_name(0)}")
27
- print(f" GPU Count: {torch.cuda.device_count()}")
28
- else:
29
- print("⚠ No GPU - using CPU (slower)")
30
- ```
31
-
32
- ## Cell 4: Load Dataset
33
- ```python
34
- from datasets import load_dataset
35
-
36
- print("📊 Loading dataset...")
37
- dataset = load_dataset("maharshipandya/spotify-tracks-dataset")
38
- print(f"✓ Loaded {len(dataset['train'])} tracks")
39
- ```
40
-
41
- ## Cell 5: Load Model
42
- ```python
43
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
44
-
45
- model_name = "gpt2"
46
- print(f"🤖 Loading model: {model_name}")
47
-
48
- tokenizer = AutoTokenizer.from_pretrained(model_name)
49
- if tokenizer.pad_token is None:
50
- tokenizer.pad_token = tokenizer.eos_token
51
-
52
- # Get unique genres
53
- genres = sorted(set(dataset['train']['track_genre']))
54
- num_labels = len(genres)
55
- label2id = {g: i for i, g in enumerate(genres)}
56
- id2label = {i: g for i, g in enumerate(genres)}
57
-
58
- model = AutoModelForSequenceClassification.from_pretrained(
59
- model_name,
60
- num_labels=num_labels,
61
- id2label=id2label,
62
- label2id=label2id
63
- )
64
-
65
- print(f"✓ Model loaded: {num_labels} genres")
66
- ```
67
-
68
- ## Cell 6: Preprocess Data
69
- ```python
70
- def tokenize(ex):
71
- texts = [str(t) if t else "" for t in ex['track_name']]
72
- tokenized = tokenizer(texts, padding='max_length', truncation=True, max_length=128)
73
- tokenized['labels'] = [label2id[l] for l in ex['track_genre']]
74
- return tokenized
75
-
76
- print("🔧 Preprocessing...")
77
- tokenized_dataset = dataset.map(tokenize, batched=True, remove_columns=dataset['train'].column_names)
78
-
79
- # Create validation split
80
- splits = tokenized_dataset['train'].train_test_split(test_size=0.1)
81
- tokenized_dataset = {
82
- 'train': splits['train'],
83
- 'validation': splits['test']
84
- }
85
-
86
- print(f"✓ Train: {len(tokenized_dataset['train'])}, Val: {len(tokenized_dataset['validation'])}")
87
- ```
88
-
89
- ## Cell 7: Training
90
- ```python
91
- from transformers import TrainingArguments, Trainer
92
- import numpy as np
93
- import evaluate
94
-
95
- # Metrics
96
- def compute_metrics(eval_pred):
97
- predictions = np.argmax(eval_pred.predictions, axis=1)
98
- accuracy = evaluate.load("accuracy")
99
- f1 = evaluate.load("f1")
100
- return {
101
- 'accuracy': accuracy.compute(predictions=predictions, references=eval_pred.label_ids)['accuracy'],
102
- 'f1_macro': f1.compute(predictions=predictions, references=eval_pred.label_ids, average='macro')['f1']
103
- }
104
-
105
- # Training args
106
- training_args = TrainingArguments(
107
- output_dir="./model",
108
- num_train_epochs=3,
109
- per_device_train_batch_size=16,
110
- per_device_eval_batch_size=32,
111
- learning_rate=5e-5,
112
- fp16=True, # Use mixed precision on GPU
113
- eval_strategy="epoch",
114
- save_strategy="epoch",
115
- load_best_model_at_end=True,
116
- logging_steps=50,
117
- report_to="none"
118
- )
119
-
120
- # Trainer
121
- trainer = Trainer(
122
- model=model,
123
- args=training_args,
124
- train_dataset=tokenized_dataset['train'],
125
- eval_dataset=tokenized_dataset['validation'],
126
- processing_class=tokenizer,
127
- compute_metrics=compute_metrics
128
- )
129
-
130
- print("🚀 Starting training...")
131
- trainer.train()
132
- print("✓ Training complete!")
133
- ```
134
-
135
- ## Cell 8: Evaluate
136
- ```python
137
- print("📈 Evaluating...")
138
- metrics = trainer.evaluate()
139
- print(f"Final Accuracy: {metrics['eval_accuracy']:.4f}")
140
- print(f"Final F1: {metrics['eval_f1_macro']:.4f}")
141
- ```
142
-
143
- ## Cell 9: Save Model
144
- ```python
145
- model.save_pretrained("./final_model")
146
- tokenizer.save_pretrained("./final_model")
147
- print("💾 Model saved to ./final_model")
148
- ```
149
-
150
- ## Cell 10: Test Predictions
151
- ```python
152
- import torch
153
-
154
- test_tracks = [
155
- "Bohemian Rhapsody",
156
- "Shape of You",
157
- "Old Town Road",
158
- "Blinding Lights",
159
- "Bad Guy"
160
- ]
161
-
162
- model.eval()
163
- print("\n🎵 Predictions:")
164
- for track in test_tracks:
165
- inputs = tokenizer(track, return_tensors='pt', truncation=True, max_length=128)
166
- if torch.cuda.is_available():
167
- inputs = {k: v.cuda() for k, v in inputs.items()}
168
-
169
- with torch.no_grad():
170
- outputs = model(**inputs)
171
- pred_id = torch.argmax(outputs.logits, dim=-1).item()
172
- conf = torch.softmax(outputs.logits, dim=-1)[0, pred_id].item()
173
-
174
- print(f" '{track}' → {id2label[pred_id]} ({conf:.2%})")
175
- ```
176
-
177
- ## Cell 11: Push to Hub (Optional)
178
- ```python
179
- from huggingface_hub import login
180
-
181
- hf_token = os.environ['HF_TOKEN']
182
- username = os.environ['HF_USERNAME']
183
-
184
- login(token=hf_token)
185
-
186
- repo_name = "spotify-genre-classifier"
187
- model.push_to_hub(f"{username}/{repo_name}")
188
- tokenizer.push_to_hub(f"{username}/{repo_name}")
189
-
190
- print(f"✅ Model pushed to: https://huggingface.co/{username}/{repo_name}")
191
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
QUICKSTART.md DELETED
@@ -1,16 +0,0 @@
1
- # Quick Start
2
-
3
- ```bash
4
- cd ~/code/hf-training
5
- pip install -r requirements.txt
6
- cp .env.example .env
7
- nano .env # Add: HF_TOKEN=hf_xxxxx
8
- ./run.sh spotify
9
- ```
10
-
11
- ## Commands
12
-
13
- ```bash
14
- ./run.sh spotify # BERT
15
- ./run.sh gpt2_spotify # GPT-2
16
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deploy_space.sh DELETED
@@ -1,108 +0,0 @@
1
- #!/bin/bash
2
- #
3
- # Create and deploy Hugging Face Space
4
- # Usage: ./deploy_space.sh [space_name]
5
- #
6
-
7
- set -e
8
-
9
- SPACE_NAME="${1:-spotify-genre-classifier}"
10
-
11
- echo "=========================================="
12
- echo " Hugging Face Space Deployment"
13
- echo "=========================================="
14
- echo ""
15
-
16
- # Check HF token
17
- if [ ! -f ".env" ]; then
18
- echo "❌ .env not found"
19
- exit 1
20
- fi
21
-
22
- source .env
23
- if [ -z "$HF_TOKEN" ]; then
24
- echo "❌ HF_TOKEN not set in .env"
25
- exit 1
26
- fi
27
-
28
- echo "✓ HF_TOKEN found"
29
- echo ""
30
-
31
- # Username
32
- USERNAME="maxxcarl"
33
-
34
- echo "✓ Username: $USERNAME"
35
- echo ""
36
-
37
- SPACE_ID="$USERNAME/$SPACE_NAME"
38
-
39
- echo "Creating Space: $SPACE_ID"
40
- echo ""
41
-
42
- # Create space if not exists
43
- hf repo create "$SPACE_ID" --type space --space_sdk gradio --exists-ok || true
44
-
45
- # Copy files to temp space folder
46
- TEMP_DIR="/tmp/hf-space-$SPACE_NAME"
47
- rm -rf "$TEMP_DIR"
48
- mkdir -p "$TEMP_DIR"
49
-
50
- # Copy all necessary files
51
- cp app.py "$TEMP_DIR/"
52
- cp requirements_sp.txt "$TEMP_DIR/requirements.txt"
53
-
54
- # Copy trained model if exists
55
- if [ -d "outputs/final_model" ]; then
56
- echo "Copying trained model..."
57
- cp -r outputs/final_model "$TEMP_DIR/model/"
58
- fi
59
-
60
- # Create README for space
61
- cat > "$TEMP_DIR/README.md" << 'EOF'
62
- ---
63
- title: Spotify Genre Classifier
64
- emoji: 🎵
65
- colorFrom: blue
66
- colorTo: purple
67
- sdk: gradio
68
- sdk_version: 4.44.0
69
- app_file: app.py
70
- pinned: false
71
- license: mit
72
- ---
73
-
74
- # 🎵 Spotify Genre Classifier
75
-
76
- This model predicts the genre of a song based on its track name.
77
-
78
- ## Features
79
- - Fine-tuned GPT-2 model
80
- - 114 different genres
81
- - Real-time predictions
82
-
83
- ## How to Use
84
- 1. Enter a track name
85
- 2. Click "Predict Genre"
86
- 3. See the predicted genre and confidence
87
-
88
- ## Training Your Own
89
- Check out the training pipeline: https://github.com/huggingface/transformers
90
- EOF
91
-
92
- # Upload to space
93
- echo ""
94
- echo "Uploading files to Space..."
95
- cd "$TEMP_DIR"
96
- hf upload "$SPACE_ID" "." "." --repo-type space
97
- cd - > /dev/null
98
-
99
- echo ""
100
- echo "=========================================="
101
- echo "✅ Space deployed successfully!"
102
- echo "=========================================="
103
- echo ""
104
- echo "🌐 View your Space:"
105
- echo " https://huggingface.co/spaces/$SPACE_ID"
106
- echo ""
107
- echo "📝 Note: First build may take 2-3 minutes"
108
- echo ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
kaggle_auto.ipynb DELETED
@@ -1,82 +0,0 @@
1
- # 🎵 Spotify Genre Classifier - Automatic Training
2
- #
3
- # Kaggle Notebook: Just run this single cell!
4
- #
5
- # Setup:
6
- # 1. Add secrets in Kaggle: HF_TOKEN and HF_USERNAME
7
- # 2. Run this cell
8
- # 3. Wait for training to complete (~15-20 min on GPU)
9
- # 4. Model will be saved and optionally pushed to HF Hub
10
-
11
- print("=" * 60)
12
- print(" Spotify Genre Classifier - Automatic Training")
13
- print("=" * 60)
14
-
15
- # Step 1: Get secrets
16
- from kaggle_secrets import UserSecretsClient
17
- import os
18
-
19
- user_secrets = UserSecretsClient()
20
- os.environ['HF_TOKEN'] = user_secrets.get_secret("HF_TOKEN")
21
- os.environ['HF_USERNAME'] = user_secrets.get_secret("HF_USERNAME")
22
-
23
- print(f"\n✓ Logged in as: {os.environ['HF_USERNAME']}")
24
-
25
- # Step 2: Install dependencies
26
- print("\n📦 Installing dependencies...")
27
- !pip install -q transformers datasets accelerate evaluate scikit-learn python-dotenv tqdm
28
-
29
- # Step 3: Clone repo
30
- print("\n📥 Cloning training repo...")
31
- !git clone https://huggingface.co/maxxcarl/spotify-training
32
- %cd spotify-training
33
-
34
- # Step 4: Check GPU
35
- print("\n🔍 Checking GPU...")
36
- import torch
37
- if torch.cuda.is_available():
38
- print(f"✓ GPU: {torch.cuda.get_device_name(0)}")
39
- else:
40
- print("⚠ No GPU - using CPU")
41
-
42
- # Step 5: Run training
43
- print("\n" + "=" * 60)
44
- print(" Starting Training")
45
- print("=" * 60)
46
-
47
- !chmod +x run.sh
48
- !./run.sh gpt2_spotify
49
-
50
- # Step 6: Test model
51
- print("\n" + "=" * 60)
52
- print(" Testing Model")
53
- print("=" * 60)
54
-
55
- !./run.sh test
56
-
57
- # Step 7: Push to Hub (optional)
58
- print("\n" + "=" * 60)
59
- print(" Push to Hugging Face Hub?")
60
- print("=" * 60)
61
-
62
- from huggingface_hub import login
63
-
64
- hf_token = os.environ['HF_TOKEN']
65
- username = os.environ['HF_USERNAME']
66
-
67
- login(token=hf_token)
68
-
69
- repo_name = "spotify-genre-classifier"
70
- print(f"\nPushing to: {username}/{repo_name}")
71
-
72
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
73
-
74
- model = AutoModelForSequenceClassification.from_pretrained("./outputs/final_model")
75
- tokenizer = AutoTokenizer.from_pretrained("./outputs/final_model")
76
-
77
- model.push_to_hub(f"{username}/{repo_name}")
78
- tokenizer.push_to_hub(f"{username}/{repo_name}")
79
-
80
- print(f"\n✅ Complete!")
81
- print(f"📊 Model: https://huggingface.co/{username}/{repo_name}")
82
- print(f"🌐 Space: https://huggingface.co/spaces/{username}/pool")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
kaggle_single_cell.py DELETED
@@ -1,57 +0,0 @@
1
- # Kaggle Auto-Training Notebook
2
- # Copy this entire file into a single Kaggle notebook cell
3
-
4
- print("=" * 60)
5
- print(" Spotify Genre Classifier - Automatic Training")
6
- print("=" * 60)
7
-
8
- # Get secrets
9
- from kaggle_secrets import UserSecretsClient
10
- import os
11
-
12
- user_secrets = UserSecretsClient()
13
- os.environ['HF_TOKEN'] = user_secrets.get_secret("HF_TOKEN")
14
- os.environ['HF_USERNAME'] = user_secrets.get_secret("HF_USERNAME")
15
-
16
- print(f"\n✓ Logged in as: {os.environ['HF_USERNAME']}")
17
-
18
- # Install
19
- print("\n📦 Installing...")
20
- !pip install -q transformers datasets accelerate evaluate scikit-learn python-dotenv tqdm
21
-
22
- # Clone
23
- print("\n📥 Cloning...")
24
- !git clone https://huggingface.co/maxxcarl/spotify-training
25
- %cd spotify-training
26
-
27
- # Check GPU
28
- print("\n🔍 GPU:")
29
- import torch
30
- if torch.cuda.is_available():
31
- print(f"✓ {torch.cuda.get_device_name(0)}")
32
- else:
33
- print("⚠ CPU only")
34
-
35
- # Train
36
- print("\n🚀 Training...")
37
- !chmod +x run.sh
38
- !./run.sh gpt2_spotify
39
-
40
- # Test
41
- print("\n📈 Testing...")
42
- !./run.sh test
43
-
44
- # Push to Hub
45
- print("\n💾 Pushing to Hub...")
46
- from huggingface_hub import login
47
- login(token=os.environ['HF_TOKEN'])
48
-
49
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
50
- model = AutoModelForSequenceClassification.from_pretrained("./outputs/final_model")
51
- tokenizer = AutoTokenizer.from_pretrained("./outputs/final_model")
52
-
53
- username = os.environ['HF_USERNAME']
54
- model.push_to_hub(f"{username}/spotify-genre-classifier")
55
- tokenizer.push_to_hub(f"{username}/spotify-genre-classifier")
56
-
57
- print(f"\n✅ Done! https://huggingface.co/{username}/spotify-genre-classifier")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,23 +0,0 @@
1
- # Core Hugging Face & PyTorch
2
- transformers>=4.35.0
3
- datasets>=2.14.0
4
- torch>=2.0.0
5
- accelerate>=0.24.0
6
-
7
- # Training & Evaluation
8
- scikit-learn>=1.3.0
9
- evaluate>=0.4.1
10
- seqeval>=1.2.2
11
-
12
- # Configuration & Environment
13
- python-dotenv>=1.0.0
14
- hydra-core>=1.3.0
15
- omegaconf>=2.3.0
16
-
17
- # Progress & Logging
18
- tqdm>=4.66.0
19
- wandb>=0.15.0
20
-
21
- # Utilities
22
- pandas>=2.0.0
23
- numpy>=1.24.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements_sp.txt DELETED
@@ -1,3 +0,0 @@
1
- transformers>=4.35.0
2
- torch>=2.0.0
3
- gradio>=4.0.0