File size: 8,026 Bytes
bd48fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6f934064",
   "metadata": {},
   "source": [
    "# CIIL Anuvani-LID: quick start\n",
    "\n",
    "Anuvani-LID tells you **which language is spoken** in a recording, for the 22 scheduled languages of India and English.\n",
    "\n",
    "**How to use this notebook:** run the cells from top to bottom (click a cell, then press **Shift + Enter**), or choose **Runtime → Run all**. A CPU runtime is enough; a GPU is not needed.\n",
    "\n",
    "Every code cell below is copied from the [model card](https://huggingface.co/CIIL/Anuvani-LID); the short cells between them only prepare the audio files the card's examples use."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6793c3e4",
   "metadata": {},
   "source": [
    "## 1. Install\n",
    "\n",
    "Google Colab already has PyTorch, Transformers, soundfile and librosa. This adds the two packages the long-audio and ONNX examples need. (Outside Colab: `pip install transformers torch soundfile librosa silero-vad onnxruntime`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40ffaedb",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q silero-vad onnxruntime"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3568f6da",
   "metadata": {},
   "source": [
    "## 2. Get a test recording\n",
    "\n",
    "The repository ships five short clips (FLEURS, CC BY 4.0). This saves the Hindi one as `audio.wav`, the file name the card's examples use."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "295fec36",
   "metadata": {},
   "outputs": [],
   "source": [
    "import soundfile as sf\n",
    "from huggingface_hub import hf_hub_download\n",
    "\n",
    "wav, sr = sf.read(hf_hub_download(\"CIIL/Anuvani-LID\", \"samples/hi_in.wav\"))\n",
    "sf.write(\"audio.wav\", wav, sr)\n",
    "print(f\"audio.wav: {len(wav) / sr:.1f} s at {sr} Hz\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b07fa57",
   "metadata": {},
   "source": [
    "## 3. Identify the language with `pipeline`\n",
    "\n",
    "The first run downloads the model (about 465 MB). The result lists the most likely languages with their scores."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fdc35307",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "repo = \"CIIL/Anuvani-LID\"\n",
    "clf = pipeline(\"audio-classification\", model=repo, feature_extractor=repo, trust_remote_code=True)\n",
    "# [{'label': 'hindi', 'score': 0.98}, ...]\n",
    "print(clf(\"audio.wav\")[:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d34898a",
   "metadata": {},
   "source": [
    "The same on the repository's sample clips:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84b9918f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import hf_hub_download\n",
    "print(clf(hf_hub_download(repo, \"samples/hi_in.wav\"))[:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb4489ba",
   "metadata": {},
   "source": [
    "## 4. The same with `AutoModel`\n",
    "\n",
    "Useful when you want the raw scores (logits) yourself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71559636",
   "metadata": {},
   "outputs": [],
   "source": [
    "import soundfile as sf, torch\n",
    "from transformers import AutoModelForAudioClassification, AutoFeatureExtractor\n",
    "repo = \"CIIL/Anuvani-LID\"\n",
    "# native Wav2Vec2FeatureExtractor\n",
    "fe = AutoFeatureExtractor.from_pretrained(repo)\n",
    "model = AutoModelForAudioClassification.from_pretrained(repo, trust_remote_code=True).eval()\n",
    "# 16 kHz mono\n",
    "wav, sr = sf.read(\"audio.wav\")\n",
    "logits = model(**fe(wav, sampling_rate=sr, return_tensors=\"pt\")).logits\n",
    "print(model.config.id2label[logits.argmax(-1).item()])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34e729fa",
   "metadata": {},
   "source": [
    "## 5. Long audio: a language timeline\n",
    "\n",
    "For recordings longer than about two minutes, `classify_long_audio` finds the speech with Silero VAD, classifies each phrase and reports a timeline. To show it, this joins the five sample clips (Hindi, Bengali, Marathi, Tamil, Telugu) into one recording, `lecture_1hour.mp3`, the file name the card's example uses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb8dad25",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np, soundfile as sf\n",
    "from huggingface_hub import hf_hub_download\n",
    "\n",
    "pause = np.zeros(8000)                                              # 0.5 s of silence between clips\n",
    "parts = [sf.read(hf_hub_download(\"CIIL/Anuvani-LID\", f\"samples/{c}.wav\"))[0]\n",
    "         for c in [\"hi_in\", \"bn_in\", \"mr_in\", \"ta_in\", \"te_in\"]]\n",
    "sf.write(\"lecture_1hour.mp3\", np.concatenate([np.concatenate([p, pause]) for p in parts]), 16000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec7f8eb0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import librosa\n",
    "# any format/length\n",
    "wav, _ = librosa.load(\"lecture_1hour.mp3\", sr=16000, mono=True)\n",
    "# needs: pip install silero-vad\n",
    "out = model.classify_long_audio(wav)\n",
    "# overall (duration-weighted over the speech pieces)\n",
    "print(out[\"label\"], out[\"score\"])\n",
    "# share of speech time per language\n",
    "print(out[\"dominant_by_time\"], out[\"language_time_share\"])\n",
    "# per phrase piece — surfaces code-switching\n",
    "for p in out[\"timeline\"]:\n",
    "    print(f\"{p['start']:7.1f}-{p['end']:7.1f}s  {p['label']}  {p['score']:.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13d597cb",
   "metadata": {},
   "source": [
    "Each line of the timeline is one stretch of speech and its language, so a recording that switches language shows every language in turn."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dde8ce79",
   "metadata": {},
   "source": [
    "## 6. ONNX (optional)\n",
    "\n",
    "The most portable way to run the model, without PyTorch or Transformers. It downloads a further 464 MB."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbe6efca",
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnxruntime as ort, soundfile as sf, numpy as np\n",
    "from huggingface_hub import hf_hub_download\n",
    "repo = \"CIIL/Anuvani-LID\"\n",
    "sess = ort.InferenceSession(hf_hub_download(repo, \"triton_inference/assets/model/anuvani_lid.onnx\"))\n",
    "labels = open(hf_hub_download(repo, \"labels.txt\")).read().split()\n",
    "# 16 kHz mono\n",
    "wav, _ = sf.read(\"audio.wav\", dtype=\"float32\")\n",
    "logits = sess.run([\"logits\"], {\"audio\": wav[None], \"audio_length\": np.array([len(wav)], np.int64)})[0]\n",
    "print(labels[int(logits.argmax())])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1faaac1c",
   "metadata": {},
   "source": [
    "## 7. Try your own recording\n",
    "\n",
    "Run the cell below and choose a file (WAV, MP3, M4A, OGG, ...). It runs last so that **Run all** finishes the examples above first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b520a373",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from google.colab import files\n",
    "    for name in files.upload():\n",
    "        print(name, clf(name)[:3])\n",
    "except ImportError:\n",
    "    print(\"Not running in Google Colab: call clf(\\\"path/to/your_audio.wav\\\") instead.\")"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "CIIL Anuvani-LID quick start",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}