github-actions[bot] commited on
Commit
c145336
·
0 Parent(s):

Sync to HuggingFace Spaces

Browse files
.gitattributes ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+
4
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
5
+ *.wav filter=lfs diff=lfs merge=lfs -text
.github/workflows/sync.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face Spaces
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ sync:
10
+ name: Sync
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout Repository
15
+ uses: actions/checkout@v4
16
+ with:
17
+ lfs: true
18
+
19
+ - name: Sync to Hugging Face Spaces
20
+ uses: JacobLinCool/huggingface-sync@v1
21
+ with:
22
+ github: ${{ secrets.GITHUB_TOKEN }}
23
+ user: jacoblincool # Hugging Face username or organization name
24
+ space: forced-alignment # Hugging Face space name
25
+ token: ${{ secrets.HF_TOKEN }} # Hugging Face token
26
+ configuration: headers.yaml
.gitignore ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+
162
+ # pixi environments
163
+ .pixi
164
+ *.egg-info
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 JacobLinCool
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Forced Alignment
3
+ emoji: 🎯
4
+ colorFrom: red
5
+ colorTo: gray
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
+ license: mit
10
+ ---
11
+
12
+ # Forced Alignment
13
+
14
+ Gradio app to do forced alignment.
15
+
16
+ <https://huggingface.co/spaces/JacobLinCool/forced-alignment>
app.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import torch
4
+ import numpy as np
5
+ import librosa
6
+ from accelerate.utils.imports import is_cuda_available
7
+ from iso639 import iter_langs
8
+ from ctc_forced_aligner import (
9
+ load_alignment_model,
10
+ generate_emissions,
11
+ preprocess_text,
12
+ get_alignments,
13
+ get_spans,
14
+ postprocess_results,
15
+ )
16
+
17
+ device = "cuda" if is_cuda_available() else "cpu"
18
+ dtype = torch.float16 if is_cuda_available() else torch.float32
19
+
20
+
21
+ alignment_model, alignment_tokenizer = load_alignment_model(
22
+ device,
23
+ dtype=dtype,
24
+ )
25
+
26
+
27
+ def process_alignment(audio_waveform, text, language="eng"):
28
+ print(f"{audio_waveform.shape=}, {text=}, {language=}")
29
+ # Generate emissions
30
+ emissions, stride = generate_emissions(
31
+ alignment_model, audio_waveform, batch_size=16
32
+ )
33
+
34
+ # Preprocess text
35
+ tokens_starred, text_starred = preprocess_text(
36
+ text,
37
+ romanize=True,
38
+ language=language,
39
+ )
40
+
41
+ # Get alignments
42
+ segments, scores, blank_id = get_alignments(
43
+ emissions,
44
+ tokens_starred,
45
+ alignment_tokenizer,
46
+ )
47
+
48
+ # Get spans and word timestamps
49
+ spans = get_spans(tokens_starred, segments, blank_id)
50
+ word_timestamps = postprocess_results(text_starred, spans, stride, scores)
51
+
52
+ return word_timestamps
53
+
54
+
55
+ def trim_audio(audio_array, sample_rate, word_timestamps):
56
+ start_time = int(word_timestamps[0]["start"] * sample_rate)
57
+ end_time = int(word_timestamps[-1]["end"] * sample_rate)
58
+ print(f"{start_time=}, {end_time=}")
59
+ trimmed_audio = audio_array[start_time:end_time]
60
+ return (sample_rate, trimmed_audio)
61
+
62
+
63
+ def get_language_choices():
64
+ return [f"{lang.pt3} - {lang.name}" for lang in iter_langs() if lang.pt3]
65
+
66
+
67
+ def align(audio, text, language="eng - English"):
68
+ # Extract the ISO 639-3 code from the selected language
69
+ iso_code = language.split(" - ")[0]
70
+
71
+ # Convert the input audio to 16kHz mono
72
+ sample_rate, audio_array = audio
73
+ audio_array = (
74
+ audio_array.astype(np.float32) / 32768.0
75
+ ) # Convert to float32 and normalize
76
+ print(f"{sample_rate=}, {audio_array.shape=}")
77
+
78
+ if len(audio_array.shape) > 1:
79
+ audio_array = audio_array.mean(axis=1) # Convert to mono if stereo
80
+ audio_array = librosa.resample(audio_array, orig_sr=sample_rate, target_sr=16000)
81
+
82
+ # Convert to torch tensor and move to the correct device
83
+ audio_waveform = torch.from_numpy(audio_array).to(device=device, dtype=dtype)
84
+
85
+ # Process the alignment
86
+ word_timestamps = process_alignment(audio_waveform, text, iso_code)
87
+
88
+ # Trim the audio
89
+ trimmed_audio = trim_audio(audio_array, 16000, word_timestamps)
90
+
91
+ # Create JSON output
92
+ output_json = {
93
+ "input_text": text,
94
+ "word_timestamps": word_timestamps,
95
+ "language": language,
96
+ }
97
+
98
+ return trimmed_audio, json.dumps(output_json, indent=2)
99
+
100
+
101
+ def align_result_only(audio, text, language="eng - English"):
102
+ # Extract the ISO 639-3 code from the selected language
103
+ iso_code = language.split(" - ")[0]
104
+
105
+ # Convert the input audio to 16kHz mono
106
+ sample_rate, audio_array = audio
107
+ audio_array = (
108
+ audio_array.astype(np.float32) / 32768.0
109
+ ) # Convert to float32 and normalize
110
+ print(f"{sample_rate=}, {audio_array.shape=}")
111
+
112
+ if len(audio_array.shape) > 1:
113
+ audio_array = audio_array.mean(axis=1) # Convert to mono if stereo
114
+ audio_array = librosa.resample(audio_array, orig_sr=sample_rate, target_sr=16000)
115
+
116
+ # Convert to torch tensor and move to the correct device
117
+ audio_waveform = torch.from_numpy(audio_array).to(device=device, dtype=dtype)
118
+
119
+ # Process the alignment
120
+ word_timestamps = process_alignment(audio_waveform, text, iso_code)
121
+
122
+ # Create JSON output
123
+ output_json = {
124
+ "input_text": text,
125
+ "word_timestamps": word_timestamps,
126
+ "language": language,
127
+ }
128
+
129
+ return json.dumps(output_json, indent=2)
130
+
131
+
132
+ # Create Gradio blocks
133
+ with gr.Blocks() as demo:
134
+ gr.Markdown("# Forced Alignment")
135
+
136
+ gr.Markdown(
137
+ """
138
+ This tool aligns audio with text and provides word-level timestamps.
139
+
140
+ ## How to use:
141
+ 1. Upload an audio file or record audio
142
+ 2. Enter the corresponding text
143
+ 3. Select the language
144
+ 4. Click 'Process' to get the alignment results
145
+ """
146
+ )
147
+
148
+ with gr.Row():
149
+ with gr.Column():
150
+ audio_input = gr.Audio(label="Input Audio")
151
+ text_input = gr.Textbox(label="Input Text")
152
+ language_input = gr.Dropdown(
153
+ choices=get_language_choices(), label="Language", value="eng - English"
154
+ )
155
+ submit_button = gr.Button(
156
+ "Get Alignment and Trimmed Audio", variant="primary"
157
+ )
158
+ submit_button_result_only = gr.Button(
159
+ "Get Alignment Only", variant="secondary"
160
+ )
161
+
162
+ with gr.Column():
163
+ audio_output = gr.Audio(label="Trimmed Output Audio")
164
+ json_output = gr.JSON(label="Alignment Results")
165
+
166
+ submit_button.click(
167
+ fn=align,
168
+ inputs=[audio_input, text_input, language_input],
169
+ outputs=[audio_output, json_output],
170
+ )
171
+
172
+ submit_button_result_only.click(
173
+ fn=align_result_only,
174
+ inputs=[audio_input, text_input, language_input],
175
+ outputs=[json_output],
176
+ )
177
+
178
+ gr.Markdown("## Examples")
179
+ gr.Examples(
180
+ examples=[
181
+ ["examples/example1.mp3", "我們搭上公車要回台北了", "zho - Chinese"],
182
+ [
183
+ "examples/example2.wav",
184
+ "ON SATURDAY MORNINGS WHEN THE SODALITY MET IN THE CHAPEL TO RECITE THE LITTLE OFFICE HIS PLACE WAS A CUSHIONED KNEELING DESK AT THE RIGHT OF THE ALTAR FROM WHICH HE LED HIS WING OF BOYS THROUGH THE RESPONSES",
185
+ "eng - English",
186
+ ],
187
+ ],
188
+ inputs=[audio_input, text_input, language_input],
189
+ )
190
+
191
+ # Launch the demo
192
+ if __name__ == "__main__":
193
+ demo.launch()
examples/example1.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b460bb7d06ed482472cabccda799b3c812080d2d6bbb6e65ff7e9c721b90cee0
3
+ size 31054
examples/example2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:097baaee33039db64dd47e7f1bf9880530be8e4f693d70dc022059c7fef2cc69
3
+ size 398284
headers.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ title: Forced Alignment
2
+ emoji: 🎯
3
+ colorFrom: red
4
+ colorTo: gray
5
+ sdk: gradio
6
+ app_file: app.py
7
+ pinned: false
8
+ license: mit
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ accelerate
3
+ iso639-lang
4
+ librosa
5
+ git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git