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

Sync from https://github.com/JacobLinCool/forced-alignment-app

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,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import json
4
+ import torch
5
+ import numpy as np
6
+ import librosa
7
+ from accelerate.utils.imports import is_cuda_available
8
+ from iso639 import iter_langs
9
+ from ctc_forced_aligner import (
10
+ load_alignment_model,
11
+ generate_emissions,
12
+ preprocess_text,
13
+ get_alignments,
14
+ get_spans,
15
+ postprocess_results,
16
+ )
17
+
18
+ device = "cuda" if is_cuda_available() else "cpu"
19
+ dtype = torch.float16 if is_cuda_available() else torch.float32
20
+
21
+
22
+ alignment_model, alignment_tokenizer = load_alignment_model(
23
+ device,
24
+ dtype=dtype,
25
+ )
26
+
27
+
28
+ def process_alignment(audio_waveform, text, language="eng"):
29
+ print(f"{audio_waveform.shape=}, {text=}, {language=}")
30
+ # Generate emissions
31
+ emissions, stride = generate_emissions(
32
+ alignment_model, audio_waveform, batch_size=16
33
+ )
34
+
35
+ # Preprocess text
36
+ tokens_starred, text_starred = preprocess_text(
37
+ text,
38
+ romanize=True,
39
+ language=language,
40
+ )
41
+
42
+ # Get alignments
43
+ segments, scores, blank_id = get_alignments(
44
+ emissions,
45
+ tokens_starred,
46
+ alignment_tokenizer,
47
+ )
48
+
49
+ # Get spans and word timestamps
50
+ spans = get_spans(tokens_starred, segments, blank_id)
51
+ word_timestamps = postprocess_results(text_starred, spans, stride, scores)
52
+
53
+ return word_timestamps
54
+
55
+
56
+ def trim_audio(audio_array, sample_rate, word_timestamps):
57
+ start_time = int(word_timestamps[0]["start"] * sample_rate)
58
+ end_time = int(word_timestamps[-1]["end"] * sample_rate)
59
+ print(f"{start_time=}, {end_time=}")
60
+ trimmed_audio = audio_array[start_time:end_time]
61
+ return (sample_rate, trimmed_audio)
62
+
63
+
64
+ def get_language_choices():
65
+ return [f"{lang.pt3} - {lang.name}" for lang in iter_langs() if lang.pt3]
66
+
67
+
68
+ @spaces.GPU
69
+ def align(audio, text, language="eng - English"):
70
+ # Extract the ISO 639-3 code from the selected language
71
+ iso_code = language.split(" - ")[0]
72
+
73
+ # Convert the input audio to 16kHz mono
74
+ sample_rate, audio_array = audio
75
+ audio_array = (
76
+ audio_array.astype(np.float32) / 32768.0
77
+ ) # Convert to float32 and normalize
78
+ print(f"{sample_rate=}, {audio_array.shape=}")
79
+
80
+ if len(audio_array.shape) > 1:
81
+ audio_array = audio_array.mean(axis=1) # Convert to mono if stereo
82
+ audio_array = librosa.resample(audio_array, orig_sr=sample_rate, target_sr=16000)
83
+
84
+ # Convert to torch tensor and move to the correct device
85
+ audio_waveform = torch.from_numpy(audio_array).to(device=device, dtype=dtype)
86
+
87
+ # Process the alignment
88
+ word_timestamps = process_alignment(audio_waveform, text, iso_code)
89
+
90
+ # Trim the audio
91
+ trimmed_audio = trim_audio(audio_array, 16000, word_timestamps)
92
+
93
+ # Create JSON output
94
+ output_json = {
95
+ "input_text": text,
96
+ "word_timestamps": word_timestamps,
97
+ "language": language,
98
+ }
99
+
100
+ return trimmed_audio, json.dumps(output_json, indent=2)
101
+
102
+
103
+ @spaces.GPU
104
+ def align_result_only(audio, text, language="eng - English"):
105
+ # Extract the ISO 639-3 code from the selected language
106
+ iso_code = language.split(" - ")[0]
107
+
108
+ # Convert the input audio to 16kHz mono
109
+ sample_rate, audio_array = audio
110
+ audio_array = (
111
+ audio_array.astype(np.float32) / 32768.0
112
+ ) # Convert to float32 and normalize
113
+ print(f"{sample_rate=}, {audio_array.shape=}")
114
+
115
+ if len(audio_array.shape) > 1:
116
+ audio_array = audio_array.mean(axis=1) # Convert to mono if stereo
117
+ audio_array = librosa.resample(audio_array, orig_sr=sample_rate, target_sr=16000)
118
+
119
+ # Convert to torch tensor and move to the correct device
120
+ audio_waveform = torch.from_numpy(audio_array).to(device=device, dtype=dtype)
121
+
122
+ # Process the alignment
123
+ word_timestamps = process_alignment(audio_waveform, text, iso_code)
124
+
125
+ # Create JSON output
126
+ output_json = {
127
+ "input_text": text,
128
+ "word_timestamps": word_timestamps,
129
+ "language": language,
130
+ }
131
+
132
+ return json.dumps(output_json, indent=2)
133
+
134
+
135
+ # Create Gradio blocks
136
+ with gr.Blocks() as demo:
137
+ gr.Markdown("# Forced Alignment")
138
+
139
+ gr.Markdown(
140
+ """
141
+ This tool aligns audio with text and provides word-level timestamps.
142
+
143
+ ## How to use:
144
+ 1. Upload an audio file or record audio
145
+ 2. Enter the corresponding text
146
+ 3. Select the language
147
+ 4. Click 'Process' to get the alignment results
148
+ """
149
+ )
150
+
151
+ with gr.Row():
152
+ with gr.Column():
153
+ audio_input = gr.Audio(label="Input Audio")
154
+ text_input = gr.Textbox(label="Input Text")
155
+ language_input = gr.Dropdown(
156
+ choices=get_language_choices(), label="Language", value="eng - English"
157
+ )
158
+ submit_button = gr.Button(
159
+ "Get Alignment and Trimmed Audio", variant="primary"
160
+ )
161
+ submit_button_result_only = gr.Button(
162
+ "Get Alignment Only", variant="secondary"
163
+ )
164
+
165
+ with gr.Column():
166
+ audio_output = gr.Audio(label="Trimmed Output Audio")
167
+ json_output = gr.JSON(label="Alignment Results")
168
+
169
+ submit_button.click(
170
+ fn=align,
171
+ inputs=[audio_input, text_input, language_input],
172
+ outputs=[audio_output, json_output],
173
+ )
174
+
175
+ submit_button_result_only.click(
176
+ fn=align_result_only,
177
+ inputs=[audio_input, text_input, language_input],
178
+ outputs=[json_output],
179
+ )
180
+
181
+ gr.Markdown("## Examples")
182
+ gr.Examples(
183
+ examples=[
184
+ ["examples/example1.mp3", "我們搭上公車要回台北了", "zho - Chinese"],
185
+ [
186
+ "examples/example2.wav",
187
+ "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",
188
+ "eng - English",
189
+ ],
190
+ ],
191
+ inputs=[audio_input, text_input, language_input],
192
+ )
193
+
194
+ # Launch the demo
195
+ if __name__ == "__main__":
196
+ 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,6 @@
 
 
 
 
 
 
 
1
+ spaces
2
+ gradio
3
+ accelerate
4
+ iso639-lang
5
+ librosa
6
+ git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git