fassabilf's picture
Upload folder using huggingface_hub
e83f0ea verified
Raw
History Blame Contribute Delete
3.72 kB
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import librosa
import librosa.display
import warnings
warnings.filterwarnings("ignore")
DATA_DIR = Path("output/linguawave")
SAMPLE_RATE = 16_000
DURATION = 10 # seconds
N_SAMPLES = SAMPLE_RATE * DURATION # 160_000
CLASSES = ["id", "ms", "vi", "th", "en", "zh", "ar", "fr"]
TONAL = {"vi", "th", "zh"}
train_df = pd.read_csv(DATA_DIR / "train.csv")
test_df = pd.read_csv(DATA_DIR / "test.csv")
print("Train shape:", train_df.shape)
print("Test shape:", test_df.shape)
train_df.head()
counts = train_df["language"].value_counts().reindex(CLASSES)
colors = ["#e15759" if c in TONAL else "#4e79a7" for c in CLASSES]
fig, ax = plt.subplots(figsize=(9, 4))
bars = ax.bar(CLASSES, counts.values, color=colors)
ax.set_title("Training samples per language")
ax.set_xlabel("Language")
ax.set_ylabel("Count")
# legend
from matplotlib.patches import Patch
legend_elements = [
Patch(facecolor="#e15759", label="Tonal (vi, th, zh)"),
Patch(facecolor="#4e79a7", label="Non-tonal"),
]
ax.legend(handles=legend_elements)
for bar, count in zip(bars, counts.values):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 5,
str(count), ha="center", va="bottom", fontsize=9)
plt.tight_layout()
plt.show()
print(counts)
fig, axes = plt.subplots(2, 4, figsize=(16, 6))
axes = axes.flatten()
for idx, lang in enumerate(CLASSES):
row = train_df[train_df["language"] == lang].iloc[0]
fpath = DATA_DIR / row["id"]
y, sr = librosa.load(fpath, sr=SAMPLE_RATE, duration=DURATION)
mel = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, n_fft=1024, hop_length=256)
mel_db = librosa.power_to_db(mel, ref=np.max)
ax = axes[idx]
librosa.display.specshow(mel_db, sr=sr, hop_length=256,
x_axis="time", y_axis="mel", ax=ax)
marker = " ♪" if lang in TONAL else ""
ax.set_title(f"{lang}{marker}", fontsize=12,
color="#e15759" if lang in TONAL else "#4e79a7")
ax.set_xlabel("")
ax.set_ylabel("")
fig.suptitle("Mel Spectrograms – one sample per language\n(red = tonal language)", y=1.02)
plt.tight_layout()
plt.show()
def extract_features_skeleton(fpath, sr=SAMPLE_RATE, n_mfcc=20):
"""Skeleton – returns None; replace with real implementation."""
y, _ = librosa.load(fpath, sr=sr, duration=DURATION)
# TODO: compute features
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc)
feats = np.concatenate([mfcc.mean(axis=1), mfcc.std(axis=1)]) # 40-dim
return feats
# Quick sanity check
sample_path = DATA_DIR / train_df.iloc[0]["id"]
feats = extract_features_skeleton(sample_path)
print("Feature vector shape:", feats.shape)
from sklearn.dummy import DummyClassifier
from sklearn.metrics import f1_score
from sklearn.preprocessing import LabelEncoder
# Encode labels
le = LabelEncoder()
le.fit(CLASSES)
# Dummy model (replace with real model)
dummy = DummyClassifier(strategy="most_frequent", random_state=42)
dummy.fit([[0]] * len(train_df), le.transform(train_df["language"]))
# Predict on test set
test_preds = dummy.predict([[0]] * len(test_df))
test_labels = le.inverse_transform(test_preds)
# Build submission CSV
sub = pd.DataFrame({"id": test_df["id"], "language": test_labels})
sub_dir = Path("submissions")
sub_dir.mkdir(exist_ok=True)
sub.to_csv(sub_dir / "sub_approach0_starter.csv", index=False)
print("Submission saved!")
print(sub.head())
print()
print("Macro F1 (on dummy val) – replace with real validation:")
# Example validation snippet
# val_preds = model.predict(X_val)
# f1 = f1_score(y_val, val_preds, average="macro")
# print(f"Macro F1: {f1:.4f}")