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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Taqbaylit TTS Reader
|
| 2 |
+
Copyright 2026 [Your Name]
|
| 3 |
+
|
| 4 |
+
This product includes software developed by third parties:
|
| 5 |
+
|
| 6 |
+
------------------------------------------------------------------------
|
| 7 |
+
OmniVoice (Python package and pretrained model)
|
| 8 |
+
Homepage: https://github.com/k2-fsa/OmniVoice
|
| 9 |
+
Model: https://huggingface.co/k2-fsa/OmniVoice
|
| 10 |
+
|
| 11 |
+
The OmniVoice source code is licensed under the Apache License, Version 2.0.
|
| 12 |
+
The pretrained model weights are licensed under the Creative Commons
|
| 13 |
+
Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0)
|
| 14 |
+
due to constraints from its training data (e.g., Emilia).
|
| 15 |
+
|
| 16 |
+
IMPORTANT: Because this application loads and runs the OmniVoice
|
| 17 |
+
pretrained model, use of this application is subject to the
|
| 18 |
+
non-commercial restriction of the model license. See:
|
| 19 |
+
https://creativecommons.org/licenses/by-nc/4.0/
|
| 20 |
+
|
| 21 |
+
------------------------------------------------------------------------
|
| 22 |
+
PyTorch, torchaudio
|
| 23 |
+
Homepage: https://pytorch.org
|
| 24 |
+
License: BSD-style (see https://github.com/pytorch/pytorch/blob/main/LICENSE)
|
| 25 |
+
|
| 26 |
+
------------------------------------------------------------------------
|
| 27 |
+
Streamlit
|
| 28 |
+
Homepage: https://streamlit.io
|
| 29 |
+
License: Apache License 2.0
|
| 30 |
+
|
| 31 |
+
------------------------------------------------------------------------
|
| 32 |
+
pdfplumber
|
| 33 |
+
Homepage: https://github.com/jsvine/pdfplumber
|
| 34 |
+
License: MIT License
|
| 35 |
+
|
| 36 |
+
------------------------------------------------------------------------
|
| 37 |
+
soundfile, psutil, NumPy
|
| 38 |
+
Licensed under their respective open-source licenses
|
| 39 |
+
(BSD, MIT, and BSD respectively).
|
README.md
CHANGED
|
@@ -1,15 +1,54 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
pinned: false
|
| 11 |
-
license:
|
| 12 |
-
short_description: Kabyle (Taqbaylit) TTS reader with OmniVoice
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Taqbaylit TTS Reader
|
| 3 |
+
emoji: 🎙️
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.0.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
python_version: "3.10"
|
| 10 |
+
pinned: false
|
| 11 |
+
license: apache-2.0
|
| 12 |
+
short_description: Kabyle (Taqbaylit) TTS reader with OmniVoice
|
| 13 |
+
tags:
|
| 14 |
+
- tts
|
| 15 |
+
- kabyle
|
| 16 |
+
- taqbaylit
|
| 17 |
+
- omnivoice
|
| 18 |
+
- audio
|
| 19 |
+
- gradio
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# Taqbaylit TTS Reader — OmniVoice
|
| 23 |
+
|
| 24 |
+
A Kabyle (Taqbaylit) text-to-speech reader powered by OmniVoice.
|
| 25 |
+
|
| 26 |
+
Upload a PDF or TXT file, or paste text directly. The app splits it into
|
| 27 |
+
paragraphs, generates audio in the background while you read, and highlights
|
| 28 |
+
the current paragraph. The Kabyle ɛ phoneme is preserved.
|
| 29 |
+
|
| 30 |
+
## How it works
|
| 31 |
+
|
| 32 |
+
- A separate console process (`tts_worker.py`) handles all model inference.
|
| 33 |
+
- The Streamlit UI (`app.py`) handles upload, navigation, and playback.
|
| 34 |
+
- Audio is cached by SHA-256 of text + voice, so replays are instant.
|
| 35 |
+
- No paid APIs. Runs on CPU.
|
| 36 |
+
|
| 37 |
+
## License and attribution
|
| 38 |
+
|
| 39 |
+
This application's source code is licensed under the
|
| 40 |
+
**Apache License 2.0** (see `LICENSE`).
|
| 41 |
+
|
| 42 |
+
It depends on the OmniVoice project:
|
| 43 |
+
|
| 44 |
+
- OmniVoice **source code** is licensed under **Apache 2.0**.
|
| 45 |
+
- The pretrained **model weights** (`k2-fsa/OmniVoice`) are licensed under
|
| 46 |
+
**CC BY-NC 4.0** (Attribution-NonCommercial) due to constraints from
|
| 47 |
+
their training data.
|
| 48 |
+
|
| 49 |
+
**Because this Space loads and runs the OmniVoice pretrained model, use
|
| 50 |
+
of this Space is subject to the non-commercial restriction of the model
|
| 51 |
+
license.** You may not use this Space or its output for commercial
|
| 52 |
+
purposes without obtaining separate permission from the model authors.
|
| 53 |
+
|
| 54 |
+
See `NOTICE` for full third-party attributions.
|
app.py
ADDED
|
@@ -0,0 +1,986 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kabyle OmniVoice Reader — Gradio UI. Gradio 6 compatible.
|
| 3 |
+
Native <audio> element (no Gradio player → no competing speed control).
|
| 4 |
+
3-column layout: menu | controls+player | text.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
import wave
|
| 12 |
+
import random
|
| 13 |
+
import string
|
| 14 |
+
import hashlib
|
| 15 |
+
import threading
|
| 16 |
+
import subprocess
|
| 17 |
+
import re
|
| 18 |
+
import unicodedata
|
| 19 |
+
import html as html_lib
|
| 20 |
+
import urllib.parse
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
|
| 24 |
+
# ────────────────────────────────────────────────────────────────
|
| 25 |
+
# CONFIG
|
| 26 |
+
# ────────────────────────────────────────────────────────────────
|
| 27 |
+
N_CPUS = os.cpu_count() or 2
|
| 28 |
+
|
| 29 |
+
if N_CPUS >= 4:
|
| 30 |
+
WORKER_CORES = list(range(0, max(1, N_CPUS // 2)))
|
| 31 |
+
WORKER_THREADS = min(8, len(WORKER_CORES))
|
| 32 |
+
else:
|
| 33 |
+
WORKER_CORES = []
|
| 34 |
+
WORKER_THREADS = max(1, N_CPUS)
|
| 35 |
+
|
| 36 |
+
HIGH_PRIORITY_CLASS = 0x00000080
|
| 37 |
+
|
| 38 |
+
TTS_CACHE_ABS = os.path.abspath("./tts_cache")
|
| 39 |
+
|
| 40 |
+
VOICES = [
|
| 41 |
+
("Amalay", "male"),
|
| 42 |
+
("Unti", "female"),
|
| 43 |
+
("Taqcict", "child"),
|
| 44 |
+
("Ilemẓi", "teenager"),
|
| 45 |
+
("Amɣar", "elderly"),
|
| 46 |
+
("Mmeckukeḍ", "whisper"),
|
| 47 |
+
]
|
| 48 |
+
VOICE_NAMES = [name for name, _ in VOICES]
|
| 49 |
+
VOICE_CODE = dict(VOICES)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ────────────────────────────────────────────────────────────────
|
| 53 |
+
# WORKER
|
| 54 |
+
# ────────────────────────────────────────────────────────────────
|
| 55 |
+
def build_env():
|
| 56 |
+
keep = ["PATH", "SYSTEMROOT", "TEMP", "TMP",
|
| 57 |
+
"USERPROFILE", "HOMEDRIVE", "HOMEPATH", "LD_LIBRARY_PATH"]
|
| 58 |
+
env = {k: os.environ[k] for k in keep if k in os.environ}
|
| 59 |
+
env.update({
|
| 60 |
+
"TTS_THREADS": str(WORKER_THREADS),
|
| 61 |
+
"OMP_NUM_THREADS": str(WORKER_THREADS),
|
| 62 |
+
"MKL_NUM_THREADS": str(WORKER_THREADS),
|
| 63 |
+
"OPENBLAS_NUM_THREADS": "1",
|
| 64 |
+
"KMP_BLOCKTIME": "0",
|
| 65 |
+
"TOKENIZERS_PARALLELISM": "false",
|
| 66 |
+
"TTS_COMPILE_CACHE": os.path.abspath("./tts_compile_cache"),
|
| 67 |
+
"TTS_CACHE": TTS_CACHE_ABS,
|
| 68 |
+
"TRANSFORMERS_VERBOSITY": "error",
|
| 69 |
+
"HF_HUB_DISABLE_PROGRESS_BARS": "1",
|
| 70 |
+
})
|
| 71 |
+
return env
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
WORKER = None
|
| 75 |
+
WORKER_LOCK = threading.Lock()
|
| 76 |
+
STDIN_LOCK = threading.Lock()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _spawn_worker():
|
| 80 |
+
global WORKER
|
| 81 |
+
|
| 82 |
+
print(f"[parent] spawning worker threads={WORKER_THREADS} cores={WORKER_CORES}")
|
| 83 |
+
|
| 84 |
+
proc = subprocess.Popen(
|
| 85 |
+
[sys.executable, "-u", "tts_worker.py"],
|
| 86 |
+
stdin=subprocess.PIPE,
|
| 87 |
+
stdout=subprocess.PIPE,
|
| 88 |
+
stderr=subprocess.STDOUT,
|
| 89 |
+
text=True,
|
| 90 |
+
bufsize=1,
|
| 91 |
+
creationflags=HIGH_PRIORITY_CLASS if os.name == "nt" else 0,
|
| 92 |
+
env=build_env(),
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
affinity_ok = False
|
| 96 |
+
if WORKER_CORES:
|
| 97 |
+
try:
|
| 98 |
+
import psutil
|
| 99 |
+
psutil.Process(proc.pid).cpu_affinity(WORKER_CORES)
|
| 100 |
+
affinity_ok = True
|
| 101 |
+
print(f"[parent] worker pinned to {WORKER_CORES}")
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f"[parent] affinity FAILED: {type(e).__name__}: {e}")
|
| 104 |
+
|
| 105 |
+
state = {
|
| 106 |
+
"proc": proc,
|
| 107 |
+
"results": {},
|
| 108 |
+
"ready": False,
|
| 109 |
+
"go_acked": False,
|
| 110 |
+
"log": [],
|
| 111 |
+
"affinity_ok": affinity_ok,
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def reader():
|
| 115 |
+
for raw in proc.stdout:
|
| 116 |
+
raw = raw.rstrip()
|
| 117 |
+
if not raw:
|
| 118 |
+
continue
|
| 119 |
+
try:
|
| 120 |
+
msg = json.loads(raw)
|
| 121 |
+
except Exception:
|
| 122 |
+
state["log"].append(raw)
|
| 123 |
+
continue
|
| 124 |
+
ev = msg.get("event")
|
| 125 |
+
if ev == "ready":
|
| 126 |
+
state["ready"] = True
|
| 127 |
+
elif ev == "go-ack":
|
| 128 |
+
state["go_acked"] = True
|
| 129 |
+
elif ev == "log":
|
| 130 |
+
state["log"].append(msg.get("msg", ""))
|
| 131 |
+
print(f"[worker] {msg.get('msg','')}")
|
| 132 |
+
elif ev == "result":
|
| 133 |
+
state["results"][msg.get("id")] = msg
|
| 134 |
+
|
| 135 |
+
threading.Thread(target=reader, daemon=True).start()
|
| 136 |
+
|
| 137 |
+
with STDIN_LOCK:
|
| 138 |
+
proc.stdin.write(json.dumps({"cmd": "go"}) + "\n")
|
| 139 |
+
proc.stdin.flush()
|
| 140 |
+
|
| 141 |
+
t0 = time.time()
|
| 142 |
+
while not state["ready"] and time.time() - t0 < 300:
|
| 143 |
+
time.sleep(0.2)
|
| 144 |
+
|
| 145 |
+
if not state["ready"]:
|
| 146 |
+
raise RuntimeError("Worker failed to become ready.")
|
| 147 |
+
|
| 148 |
+
print(f"[parent] worker ready pid={proc.pid} affinity_ok={affinity_ok}")
|
| 149 |
+
WORKER = state
|
| 150 |
+
return state
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def ensure_worker():
|
| 154 |
+
global WORKER
|
| 155 |
+
if WORKER is not None and WORKER.get("ready"):
|
| 156 |
+
return WORKER
|
| 157 |
+
with WORKER_LOCK:
|
| 158 |
+
if WORKER is not None and WORKER.get("ready"):
|
| 159 |
+
return WORKER
|
| 160 |
+
return _spawn_worker()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def submit(text, voice_code):
|
| 164 |
+
w = ensure_worker()
|
| 165 |
+
rid = hashlib.sha256(
|
| 166 |
+
f"{voice_code}::{text}::{time.time_ns()}".encode()
|
| 167 |
+
).hexdigest()[:16]
|
| 168 |
+
with STDIN_LOCK:
|
| 169 |
+
w["proc"].stdin.write(
|
| 170 |
+
json.dumps({"id": rid, "text": text, "voice": voice_code}) + "\n"
|
| 171 |
+
)
|
| 172 |
+
w["proc"].stdin.flush()
|
| 173 |
+
return rid
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def wait_for(rid, timeout=1800):
|
| 177 |
+
w = WORKER
|
| 178 |
+
t0 = time.time()
|
| 179 |
+
while rid not in w["results"]:
|
| 180 |
+
if time.time() - t0 > timeout:
|
| 181 |
+
return None
|
| 182 |
+
time.sleep(0.2)
|
| 183 |
+
return w["results"].pop(rid)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ────────────────────────────────────────────────────────────────
|
| 187 |
+
# SESSIONS
|
| 188 |
+
# ────────────────────────────────────────────────────────────────
|
| 189 |
+
SESSIONS = {}
|
| 190 |
+
SESSIONS_LOCK = threading.Lock()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def new_session_id():
|
| 194 |
+
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=12))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def get_session(sid):
|
| 198 |
+
if not sid:
|
| 199 |
+
return None
|
| 200 |
+
with SESSIONS_LOCK:
|
| 201 |
+
if sid not in SESSIONS:
|
| 202 |
+
SESSIONS[sid] = {
|
| 203 |
+
"chunks": [], "current": 0,
|
| 204 |
+
"paths": {}, "times": {}, "durs": {}, "errors": {},
|
| 205 |
+
"running": False, "stop": False, "total": 0,
|
| 206 |
+
"last_audio": None,
|
| 207 |
+
"last_rendered_current": -1,
|
| 208 |
+
"last_rendered_ready_para": -1,
|
| 209 |
+
}
|
| 210 |
+
return SESSIONS[sid]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# ────────────────────────────────────────────────────────────────
|
| 214 |
+
# TEXT UTILITIES
|
| 215 |
+
# ────────────────────────────────────────────────────────────────
|
| 216 |
+
_KABYLE_NFC_MAP = {
|
| 217 |
+
"g\u030c": "\u01e7", "G\u030c": "\u01e6",
|
| 218 |
+
"d\u0323": "\u1e0d", "D\u0323": "\u1e0c",
|
| 219 |
+
"t\u0323": "\u1e6d", "T\u0323": "\u1e6c",
|
| 220 |
+
"z\u0323": "\u1e93", "Z\u0323": "\u1e92",
|
| 221 |
+
"s\u0323": "\u1e63", "S\u0323": "\u1e62",
|
| 222 |
+
"r\u0323": "\u1e5b", "R\u0323": "\u1e5a",
|
| 223 |
+
"h\u0323": "\u1e25", "H\u0323": "\u1e24",
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _kabyle_nfc(text):
|
| 228 |
+
text = unicodedata.normalize("NFC", text)
|
| 229 |
+
for k, v in _KABYLE_NFC_MAP.items():
|
| 230 |
+
if k in text:
|
| 231 |
+
text = text.replace(k, v)
|
| 232 |
+
return text
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def clean_text(text):
|
| 236 |
+
if not text:
|
| 237 |
+
return ""
|
| 238 |
+
text = _kabyle_nfc(text)
|
| 239 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def split_into_paragraphs(text, target_words=55, max_chars=420):
|
| 243 |
+
sentences = re.split(r"(?<=[.!?:;])\s+", text)
|
| 244 |
+
paras, cur, wc, cc = [], [], 0, 0
|
| 245 |
+
for s in sentences:
|
| 246 |
+
s = s.strip()
|
| 247 |
+
if not s:
|
| 248 |
+
continue
|
| 249 |
+
w = len(s.split())
|
| 250 |
+
if cur and (wc + w > target_words or cc + len(s) > max_chars):
|
| 251 |
+
paras.append(" ".join(cur))
|
| 252 |
+
cur, wc, cc = [s], w, len(s)
|
| 253 |
+
else:
|
| 254 |
+
cur.append(s)
|
| 255 |
+
wc += w
|
| 256 |
+
cc += len(s)
|
| 257 |
+
if cur:
|
| 258 |
+
paras.append(" ".join(cur))
|
| 259 |
+
return paras
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def read_upload(file_obj):
|
| 263 |
+
if file_obj is None:
|
| 264 |
+
return ""
|
| 265 |
+
path = file_obj.name if hasattr(file_obj, "name") else str(file_obj)
|
| 266 |
+
name = os.path.basename(path).lower()
|
| 267 |
+
if name.endswith(".txt"):
|
| 268 |
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
| 269 |
+
return f.read()
|
| 270 |
+
if name.endswith(".pdf"):
|
| 271 |
+
import pdfplumber
|
| 272 |
+
parts = []
|
| 273 |
+
with pdfplumber.open(path) as pdf:
|
| 274 |
+
for page in pdf.pages:
|
| 275 |
+
parts.append(page.extract_text() or "")
|
| 276 |
+
return "\n".join(parts)
|
| 277 |
+
return ""
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def wav_duration(path):
|
| 281 |
+
try:
|
| 282 |
+
with wave.open(path, 'rb') as w:
|
| 283 |
+
return w.getnframes() / w.getframerate()
|
| 284 |
+
except Exception:
|
| 285 |
+
return 0.0
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# ────────────────────────────────────────────────────────────────
|
| 289 |
+
# AUDIO URL (native <audio> in gr.HTML)
|
| 290 |
+
# ────────────────────────────────────────────────────────────────
|
| 291 |
+
def audio_url(path):
|
| 292 |
+
p = os.path.abspath(path).replace("\\", "/")
|
| 293 |
+
return "/gradio_api/file=" + urllib.parse.quote(p, safe="/:")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def audio_html_value(path):
|
| 297 |
+
if not path:
|
| 298 |
+
return ""
|
| 299 |
+
url = audio_url(path)
|
| 300 |
+
return (
|
| 301 |
+
f"<audio id='kabyle-native-audio' controls preload='auto' "
|
| 302 |
+
f"src='{url}' style='width:100%;margin-top:4px;'></audio>"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ────────────────────────────────────────────────────────────────
|
| 307 |
+
# VIEWER HTML
|
| 308 |
+
# ────────────────────────────────────────────────────────────────
|
| 309 |
+
VIEWER_CSS = """
|
| 310 |
+
<style>
|
| 311 |
+
.docview {
|
| 312 |
+
max-height: 78vh;
|
| 313 |
+
overflow-y: auto;
|
| 314 |
+
padding: 16px 20px;
|
| 315 |
+
border: 1px solid #e7d9c4;
|
| 316 |
+
border-radius: 10px;
|
| 317 |
+
background: #fffdf8;
|
| 318 |
+
line-height: 1.95;
|
| 319 |
+
font-size: 17px;
|
| 320 |
+
font-family: 'Noto Serif', 'Charis SIL', 'Gentium Plus', 'Gentium',
|
| 321 |
+
'DejaVu Serif', 'Segoe UI', Georgia,
|
| 322 |
+
'Times New Roman', serif;
|
| 323 |
+
color: #3f2d1a;
|
| 324 |
+
text-rendering: optimizeLegibility;
|
| 325 |
+
}
|
| 326 |
+
.docview .para {
|
| 327 |
+
padding: 10px 14px;
|
| 328 |
+
margin: 8px 0;
|
| 329 |
+
border-left: 3px solid transparent;
|
| 330 |
+
border-radius: 4px;
|
| 331 |
+
color: #4a3520;
|
| 332 |
+
transition: background 0.2s;
|
| 333 |
+
}
|
| 334 |
+
.docview .para.current {
|
| 335 |
+
background: linear-gradient(120deg, #fff4d6, #ffe9b3);
|
| 336 |
+
border-left-color: #b45309;
|
| 337 |
+
font-weight: 500;
|
| 338 |
+
}
|
| 339 |
+
.docview .w { transition: color 0.12s, font-weight 0.12s; }
|
| 340 |
+
.docview .w.hl {
|
| 341 |
+
color: #FF9900 !important; # CCFFFF
|
| 342 |
+
font-weight: 700;
|
| 343 |
+
text-shadow: 0 0 1px rgba(192, 57, 43, 0.25);
|
| 344 |
+
}
|
| 345 |
+
</style>
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
VIEWER_PLACEHOLDER = (
|
| 349 |
+
VIEWER_CSS +
|
| 350 |
+
"<div class='docview'>"
|
| 351 |
+
"<p style='color:#a88a60; font-style:italic;'>"
|
| 352 |
+
"Sali-d afaylu neɣ aru aḍris, syen tekki « 🚀 Bdu »."
|
| 353 |
+
"</p></div>"
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def build_viewer_html(sess):
|
| 358 |
+
chunks = sess["chunks"]
|
| 359 |
+
if not chunks:
|
| 360 |
+
return VIEWER_PLACEHOLDER
|
| 361 |
+
cur = sess["current"]
|
| 362 |
+
dur = sess["durs"].get(cur, 0.0)
|
| 363 |
+
if dur <= 0 and cur in sess["paths"]:
|
| 364 |
+
dur = wav_duration(sess["paths"][cur])
|
| 365 |
+
|
| 366 |
+
parts = [VIEWER_CSS, "<div class='docview'>"]
|
| 367 |
+
for i, p in enumerate(chunks):
|
| 368 |
+
p = _kabyle_nfc(p)
|
| 369 |
+
if i == cur and dur > 0:
|
| 370 |
+
tokens = re.findall(r"\S+\s*", p) or [p]
|
| 371 |
+
total = sum(len(t) for t in tokens) or 1
|
| 372 |
+
cum = 0
|
| 373 |
+
spans = []
|
| 374 |
+
for t in tokens:
|
| 375 |
+
s = cum / total * dur
|
| 376 |
+
cum += len(t)
|
| 377 |
+
e = cum / total * dur
|
| 378 |
+
spans.append(
|
| 379 |
+
f"<span class='w' data-s='{s:.3f}' data-e='{e:.3f}'>"
|
| 380 |
+
f"{html_lib.escape(t)}</span>"
|
| 381 |
+
)
|
| 382 |
+
parts.append(
|
| 383 |
+
"<div class='para current'>" + "".join(spans) + "</div>"
|
| 384 |
+
)
|
| 385 |
+
elif i == cur:
|
| 386 |
+
parts.append(
|
| 387 |
+
f"<div class='para current'>{html_lib.escape(p)}</div>"
|
| 388 |
+
)
|
| 389 |
+
else:
|
| 390 |
+
parts.append(f"<div class='para'>{html_lib.escape(p)}</div>")
|
| 391 |
+
parts.append("</div>")
|
| 392 |
+
return "".join(parts)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ────────────────────────────────────────────────────────────────
|
| 396 |
+
# BACKGROUND GENERATION
|
| 397 |
+
# ────────────────────────────────────────────────────────────────
|
| 398 |
+
def generate_loop(sess, voice_code):
|
| 399 |
+
sess["running"] = True
|
| 400 |
+
sess["stop"] = False
|
| 401 |
+
try:
|
| 402 |
+
for i, chunk in enumerate(sess["chunks"]):
|
| 403 |
+
if sess["stop"]:
|
| 404 |
+
break
|
| 405 |
+
rid = submit(chunk, voice_code)
|
| 406 |
+
res = wait_for(rid)
|
| 407 |
+
if res is None:
|
| 408 |
+
sess["errors"][i] = "timeout"
|
| 409 |
+
continue
|
| 410 |
+
if res.get("ok"):
|
| 411 |
+
sess["paths"][i] = res["path"]
|
| 412 |
+
sess["times"][i] = res.get("gen_s", 0.0)
|
| 413 |
+
dur = res.get("dur", 0.0)
|
| 414 |
+
if dur <= 0:
|
| 415 |
+
dur = wav_duration(res["path"])
|
| 416 |
+
sess["durs"][i] = dur
|
| 417 |
+
else:
|
| 418 |
+
sess["errors"][i] = res.get("error", "unknown error")
|
| 419 |
+
finally:
|
| 420 |
+
sess["running"] = False
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# ────────────────────────────────────────────────────────────────
|
| 424 |
+
# CALLBACKS
|
| 425 |
+
# ────────────────────────────────────────────────────────────────
|
| 426 |
+
def init_session():
|
| 427 |
+
return new_session_id()
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def toggle_input_mode(mode):
|
| 431 |
+
return (
|
| 432 |
+
gr.update(visible=(mode == "Sali-d afaylu")),
|
| 433 |
+
gr.update(visible=(mode == "Aru aḍris dagi")),
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def _maybe_audio(sess):
|
| 438 |
+
"""Return gr.update(value=html) only when the audio path changed."""
|
| 439 |
+
cur = sess["current"]
|
| 440 |
+
if cur in sess["paths"]:
|
| 441 |
+
path = sess["paths"][cur]
|
| 442 |
+
if sess["last_audio"] != path:
|
| 443 |
+
sess["last_audio"] = path
|
| 444 |
+
return gr.update(value=audio_html_value(path))
|
| 445 |
+
return gr.update()
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _counter_text(sess):
|
| 449 |
+
if not sess["chunks"]:
|
| 450 |
+
return "### Taseddaṛt — / —"
|
| 451 |
+
return f"### Taseddaṛt {sess['current'] + 1} / {sess['total']}"
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def _fmt_time(sec):
|
| 455 |
+
if sec <= 0:
|
| 456 |
+
return "—"
|
| 457 |
+
m = int(sec) // 60
|
| 458 |
+
s = int(sec) % 60
|
| 459 |
+
if m:
|
| 460 |
+
return f"{m}m{s:02d}s"
|
| 461 |
+
return f"{s}s"
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _progress_md(sess):
|
| 465 |
+
if not sess["chunks"]:
|
| 466 |
+
return ""
|
| 467 |
+
ready = len(sess["paths"])
|
| 468 |
+
total = sess["total"]
|
| 469 |
+
pct = (ready / total * 100) if total else 0
|
| 470 |
+
cur = sess["current"]
|
| 471 |
+
wc = len(sess["chunks"][cur].split())
|
| 472 |
+
|
| 473 |
+
if cur in sess["paths"]:
|
| 474 |
+
dur = sess["durs"].get(cur, 0.0)
|
| 475 |
+
gen_s = sess["times"].get(cur, 0.0)
|
| 476 |
+
bits = [f"**{wc}w**", f"{_fmt_time(dur)} audio"]
|
| 477 |
+
if gen_s > 0:
|
| 478 |
+
bits.append(f"{_fmt_time(gen_s)} gen")
|
| 479 |
+
else:
|
| 480 |
+
bits.append("cache")
|
| 481 |
+
line = f"✅ Taseddaṛt {cur + 1}/{total} — " + " · ".join(bits)
|
| 482 |
+
elif cur in sess["errors"]:
|
| 483 |
+
line = f"❌ Taseddaṛt {cur + 1}/{total} — {sess['errors'][cur]}"
|
| 484 |
+
else:
|
| 485 |
+
line = f"⏳ Taseddaṛt {cur + 1}/{total} mazal d-tuli... ({wc}w)"
|
| 486 |
+
|
| 487 |
+
return f"{line}\n\n`{ready}/{total} ({pct:.0f}%) yewjed`"
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def start_conversion(sid, mode, file_obj, pasted, target_words, voice_name):
|
| 491 |
+
sess = get_session(sid)
|
| 492 |
+
|
| 493 |
+
for k in ("paths", "times", "durs", "errors"):
|
| 494 |
+
sess[k].clear()
|
| 495 |
+
sess["chunks"] = []
|
| 496 |
+
sess["current"] = 0
|
| 497 |
+
sess["running"] = False
|
| 498 |
+
sess["stop"] = False
|
| 499 |
+
sess["total"] = 0
|
| 500 |
+
sess["last_audio"] = None
|
| 501 |
+
sess["last_rendered_current"] = -1
|
| 502 |
+
sess["last_rendered_ready_para"] = -1
|
| 503 |
+
|
| 504 |
+
if mode == "Sali-d afaylu":
|
| 505 |
+
if file_obj is None:
|
| 506 |
+
return ("⚠️ Sali-d afaylu zik.", gr.update(),
|
| 507 |
+
gr.update(), "### Taseddaṛt — / —", sid)
|
| 508 |
+
try:
|
| 509 |
+
text = read_upload(file_obj)
|
| 510 |
+
except Exception as e:
|
| 511 |
+
return (f"⚠️ Ulac tɣuri n ufaylu: {e}", gr.update(),
|
| 512 |
+
gr.update(), "### Taseddaṛt — / —", sid)
|
| 513 |
+
else:
|
| 514 |
+
if not pasted or not pasted.strip():
|
| 515 |
+
return ("⚠️ Aru aḍris zik.", gr.update(),
|
| 516 |
+
gr.update(), "### Taseddaṛt — / —", sid)
|
| 517 |
+
text = pasted
|
| 518 |
+
|
| 519 |
+
text = clean_text(text)
|
| 520 |
+
if not text:
|
| 521 |
+
return ("⚠️ Ulac agbur i tɣuri.", gr.update(),
|
| 522 |
+
gr.update(), "### Taseddaṛt — / —", sid)
|
| 523 |
+
|
| 524 |
+
sess["chunks"] = split_into_paragraphs(text, target_words=int(target_words))
|
| 525 |
+
sess["total"] = len(sess["chunks"])
|
| 526 |
+
voice_code = VOICE_CODE.get(voice_name, "male")
|
| 527 |
+
|
| 528 |
+
threading.Thread(
|
| 529 |
+
target=generate_loop, args=(sess, voice_code), daemon=True
|
| 530 |
+
).start()
|
| 531 |
+
|
| 532 |
+
msg = _progress_md(sess)
|
| 533 |
+
viewer = build_viewer_html(sess)
|
| 534 |
+
sess["last_rendered_current"] = 0
|
| 535 |
+
counter = _counter_text(sess)
|
| 536 |
+
|
| 537 |
+
# Note: audio cleared until first paragraph is ready.
|
| 538 |
+
return msg, gr.update(value=""), viewer, counter, sid
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def navigate(sid, delta):
|
| 542 |
+
sess = get_session(sid)
|
| 543 |
+
if not sess or not sess["chunks"]:
|
| 544 |
+
return (gr.update(), gr.update(), "### Taseddaṛt — / —", sid)
|
| 545 |
+
total = sess["total"]
|
| 546 |
+
new_cur = max(0, min(total - 1, sess["current"] + delta))
|
| 547 |
+
sess["current"] = new_cur
|
| 548 |
+
|
| 549 |
+
audio_upd = _maybe_audio(sess)
|
| 550 |
+
sess["last_rendered_current"] = new_cur
|
| 551 |
+
sess["last_rendered_ready_para"] = (
|
| 552 |
+
new_cur if new_cur in sess["paths"] else -1
|
| 553 |
+
)
|
| 554 |
+
viewer = build_viewer_html(sess)
|
| 555 |
+
counter = _counter_text(sess)
|
| 556 |
+
|
| 557 |
+
return audio_upd, viewer, counter, sid
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def stop_generation(sid):
|
| 561 |
+
sess = get_session(sid)
|
| 562 |
+
if sess:
|
| 563 |
+
sess["stop"] = True
|
| 564 |
+
for k in ("paths", "times", "durs", "errors"):
|
| 565 |
+
sess[k].clear()
|
| 566 |
+
sess["chunks"] = []
|
| 567 |
+
sess["current"] = 0
|
| 568 |
+
sess["total"] = 0
|
| 569 |
+
sess["last_audio"] = None
|
| 570 |
+
sess["last_rendered_current"] = -1
|
| 571 |
+
sess["last_rendered_ready_para"] = -1
|
| 572 |
+
return ("⏹️ Yettwaḥbes.", gr.update(value=""),
|
| 573 |
+
VIEWER_PLACEHOLDER, "### Taseddaṛt — / —", sid)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def timer_update(sid):
|
| 577 |
+
sess = get_session(sid)
|
| 578 |
+
if not sess or not sess["chunks"]:
|
| 579 |
+
return (gr.update(), gr.update(), gr.update(),
|
| 580 |
+
gr.update(), sid)
|
| 581 |
+
|
| 582 |
+
audio_upd = _maybe_audio(sess)
|
| 583 |
+
|
| 584 |
+
cur = sess["current"]
|
| 585 |
+
needs_rerender = (
|
| 586 |
+
sess["last_rendered_current"] != cur
|
| 587 |
+
or (cur in sess["paths"]
|
| 588 |
+
and sess["last_rendered_ready_para"] != cur)
|
| 589 |
+
)
|
| 590 |
+
if needs_rerender:
|
| 591 |
+
viewer_upd = build_viewer_html(sess)
|
| 592 |
+
sess["last_rendered_current"] = cur
|
| 593 |
+
sess["last_rendered_ready_para"] = (
|
| 594 |
+
cur if cur in sess["paths"] else -1
|
| 595 |
+
)
|
| 596 |
+
else:
|
| 597 |
+
viewer_upd = gr.update()
|
| 598 |
+
|
| 599 |
+
return (_progress_md(sess), audio_upd, viewer_upd,
|
| 600 |
+
_counter_text(sess), sid)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def toggle_menu(visible):
|
| 604 |
+
return gr.update(visible=not visible), (not visible)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
# ────────────────────────────────────────────────────────────────
|
| 608 |
+
# HEAD SCRIPT — speed + karaoke for the native <audio>
|
| 609 |
+
# ────────────────────────────────────────────────────────────────
|
| 610 |
+
HEAD_JS = r"""
|
| 611 |
+
<script>
|
| 612 |
+
(function() {
|
| 613 |
+
if (window.__kabyle_installed) return;
|
| 614 |
+
window.__kabyle_installed = true;
|
| 615 |
+
window.__kabyle_speed = 0.9;
|
| 616 |
+
console.log('[kabyle] installer running');
|
| 617 |
+
|
| 618 |
+
function readSliderValue() {
|
| 619 |
+
var box = document.getElementById('kabyle-speed');
|
| 620 |
+
if (!box) return null;
|
| 621 |
+
var range = box.querySelector('input[type=range]');
|
| 622 |
+
if (range) {
|
| 623 |
+
var v = parseFloat(range.value);
|
| 624 |
+
if (!isNaN(v)) return v;
|
| 625 |
+
}
|
| 626 |
+
var num = box.querySelector('input[type=number]');
|
| 627 |
+
if (num) {
|
| 628 |
+
var v2 = parseFloat(num.value);
|
| 629 |
+
if (!isNaN(v2)) return v2;
|
| 630 |
+
}
|
| 631 |
+
var aria = box.querySelector('[aria-valuenow]');
|
| 632 |
+
if (aria) {
|
| 633 |
+
var v3 = parseFloat(aria.getAttribute('aria-valuenow'));
|
| 634 |
+
if (!isNaN(v3)) return v3;
|
| 635 |
+
}
|
| 636 |
+
return null;
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
function findAudio() {
|
| 640 |
+
return document.getElementById('kabyle-native-audio') ||
|
| 641 |
+
document.querySelector('audio');
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
function forceRate(audio) {
|
| 645 |
+
if (!audio) return;
|
| 646 |
+
var v = window.__kabyle_speed;
|
| 647 |
+
try {
|
| 648 |
+
if (Math.abs(audio.playbackRate - v) > 0.001) {
|
| 649 |
+
audio.playbackRate = v;
|
| 650 |
+
}
|
| 651 |
+
} catch (e) {}
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
+
function pollSlider() {
|
| 655 |
+
var v = readSliderValue();
|
| 656 |
+
if (v !== null && Math.abs(v - window.__kabyle_speed) > 0.001) {
|
| 657 |
+
window.__kabyle_speed = v;
|
| 658 |
+
console.log('[kabyle] speed ->', v);
|
| 659 |
+
forceRate(findAudio());
|
| 660 |
+
}
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
function hookAudio(audio) {
|
| 664 |
+
if (!audio) return;
|
| 665 |
+
// If the src changed (new paragraph), re-hook from scratch.
|
| 666 |
+
if (audio.__kabyle_src !== audio.src) {
|
| 667 |
+
audio.__kabyle_src = audio.src;
|
| 668 |
+
audio.__kabyle_hooked = false;
|
| 669 |
+
audio.__kabyle_last = -1;
|
| 670 |
+
}
|
| 671 |
+
if (audio.__kabyle_hooked) {
|
| 672 |
+
forceRate(audio);
|
| 673 |
+
return;
|
| 674 |
+
}
|
| 675 |
+
audio.__kabyle_hooked = true;
|
| 676 |
+
|
| 677 |
+
// Aggressively force our rate whenever anything changes it.
|
| 678 |
+
audio.addEventListener('ratechange', function() {
|
| 679 |
+
forceRate(audio);
|
| 680 |
+
});
|
| 681 |
+
['play', 'playing', 'loadstart', 'loadedmetadata', 'canplay',
|
| 682 |
+
'canplaythrough', 'seeked', 'durationchange'].forEach(function(evt) {
|
| 683 |
+
audio.addEventListener(evt, function() { forceRate(audio); });
|
| 684 |
+
});
|
| 685 |
+
|
| 686 |
+
// Karaoke: red on the current word.
|
| 687 |
+
audio.addEventListener('timeupdate', function() {
|
| 688 |
+
var words = document.querySelectorAll('.docview .w');
|
| 689 |
+
if (!words.length) return;
|
| 690 |
+
var t = audio.currentTime;
|
| 691 |
+
var cur = -1;
|
| 692 |
+
for (var k = 0; k < words.length; k++) {
|
| 693 |
+
var s = parseFloat(words[k].getAttribute('data-s') || '0');
|
| 694 |
+
var en = parseFloat(words[k].getAttribute('data-e') || '0');
|
| 695 |
+
if (t >= s && t < en) { cur = k; break; }
|
| 696 |
+
}
|
| 697 |
+
if (cur !== audio.__kabyle_last) {
|
| 698 |
+
for (var j = 0; j < words.length; j++) {
|
| 699 |
+
words[j].classList.remove('hl');
|
| 700 |
+
}
|
| 701 |
+
if (cur >= 0) {
|
| 702 |
+
words[cur].classList.add('hl');
|
| 703 |
+
try {
|
| 704 |
+
words[cur].scrollIntoView({behavior:'smooth', block:'center'});
|
| 705 |
+
} catch (e) {}
|
| 706 |
+
}
|
| 707 |
+
audio.__kabyle_last = cur;
|
| 708 |
+
}
|
| 709 |
+
});
|
| 710 |
+
|
| 711 |
+
forceRate(audio);
|
| 712 |
+
console.log('[kabyle] audio hooked');
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
function scan() {
|
| 716 |
+
pollSlider();
|
| 717 |
+
var a = findAudio();
|
| 718 |
+
if (a) { forceRate(a); hookAudio(a); }
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
if (document.readyState === 'loading') {
|
| 722 |
+
document.addEventListener('DOMContentLoaded', scan);
|
| 723 |
+
} else {
|
| 724 |
+
scan();
|
| 725 |
+
}
|
| 726 |
+
setInterval(scan, 200);
|
| 727 |
+
})();
|
| 728 |
+
</script>
|
| 729 |
+
"""
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
# ────────────────────────────────────────────────────────────────
|
| 733 |
+
# THEME / CSS
|
| 734 |
+
# ────────────────────────────────────────────────────────────────
|
| 735 |
+
CUSTOM_CSS = """
|
| 736 |
+
:root {
|
| 737 |
+
--kabyle-bg: #fdf8f0;
|
| 738 |
+
--kabyle-panel: #ffffff;
|
| 739 |
+
--kabyle-border: #e7d9c4;
|
| 740 |
+
--kabyle-accent: #b45309;
|
| 741 |
+
--kabyle-text: #3f2d1a;
|
| 742 |
+
--kabyle-muted: #a88a60;
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
.gradio-container {
|
| 746 |
+
background: var(--kabyle-bg) !important;
|
| 747 |
+
color: var(--kabyle-text) !important;
|
| 748 |
+
max-width: 1600px !important;
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
.kabyle-panel {
|
| 752 |
+
background: var(--kabyle-panel) !important;
|
| 753 |
+
border: 1px solid var(--kabyle-border) !important;
|
| 754 |
+
border-radius: 12px !important;
|
| 755 |
+
padding: 14px !important;
|
| 756 |
+
box-shadow: 0 1px 3px rgba(120, 80, 40, 0.04) !important;
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
.kabyle-sec {
|
| 760 |
+
display: flex; align-items: center; gap: 6px;
|
| 761 |
+
margin: 10px 0 4px 0; font-size: 13px; font-weight: 600;
|
| 762 |
+
color: var(--kabyle-accent); letter-spacing: 0.02em;
|
| 763 |
+
}
|
| 764 |
+
.kabyle-sec .info {
|
| 765 |
+
cursor: help; color: var(--kabyle-muted); font-weight: normal;
|
| 766 |
+
font-size: 14px;
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
#kabyle-title h1 {
|
| 770 |
+
font-family: 'Noto Serif', 'Charis SIL', Georgia, serif;
|
| 771 |
+
color: var(--kabyle-accent);
|
| 772 |
+
font-weight: 700;
|
| 773 |
+
margin: 0 0 4px 0;
|
| 774 |
+
}
|
| 775 |
+
|
| 776 |
+
button.primary, .gr-button-primary {
|
| 777 |
+
background: var(--kabyle-accent) !important;
|
| 778 |
+
border-color: var(--kabyle-accent) !important;
|
| 779 |
+
color: #fff !important;
|
| 780 |
+
}
|
| 781 |
+
button.primary:hover, .gr-button-primary:hover {
|
| 782 |
+
background: #92400e !important;
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
/* Native audio player width */
|
| 786 |
+
#kabyle-audio-shell audio { width: 100% !important; }
|
| 787 |
+
"""
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def section_html(title, tip):
|
| 791 |
+
esc = html_lib.escape(tip, quote=True)
|
| 792 |
+
return gr.HTML(
|
| 793 |
+
f"<div class='kabyle-sec'>"
|
| 794 |
+
f"<span>{title}</span>"
|
| 795 |
+
f"<span class='info' title=\"{esc}\">ⓘ</span>"
|
| 796 |
+
f"</div>",
|
| 797 |
+
sanitize_html=False,
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
# ────────────────────────────────────────────────────────────────
|
| 802 |
+
# UI — 3 columns
|
| 803 |
+
# ────────────────────────────────────────────────────────────────
|
| 804 |
+
with gr.Blocks(title="Taqbaylit TTS Reader") as demo:
|
| 805 |
+
|
| 806 |
+
session_state = gr.State(value=None)
|
| 807 |
+
menu_visible = gr.State(value=True)
|
| 808 |
+
|
| 809 |
+
# Title row with menu toggle
|
| 810 |
+
with gr.Row():
|
| 811 |
+
with gr.Column(scale=0, min_width=60):
|
| 812 |
+
btn_menu = gr.Button("☰", size="sm")
|
| 813 |
+
with gr.Column(scale=10):
|
| 814 |
+
gr.HTML("""
|
| 815 |
+
<div id='kabyle-title' style='padding: 0 4px 8px 4px;'>
|
| 816 |
+
<h1>🎙️ Taqbaylit TTS Reader</h1>
|
| 817 |
+
<div style='color:#a88a60; font-size:13px;'>
|
| 818 |
+
OmniVoice · CPU · Kabyle (Taqbaylit)
|
| 819 |
+
</div>
|
| 820 |
+
</div>
|
| 821 |
+
""", sanitize_html=False)
|
| 822 |
+
|
| 823 |
+
with gr.Row(equal_height=False):
|
| 824 |
+
|
| 825 |
+
# ── Column 1: MENU ──────────────────────────────────────
|
| 826 |
+
with gr.Column(scale=1, min_width=280,
|
| 827 |
+
elem_classes="kabyle-panel") as menu_col:
|
| 828 |
+
|
| 829 |
+
section_html("📁 Aḍris",
|
| 830 |
+
"Sali-d afaylu PDF/TXT neɣ sekcem aḍris s ufus")
|
| 831 |
+
input_mode = gr.Radio(
|
| 832 |
+
choices=["Sali-d afaylu", "Aru aḍris dagi"],
|
| 833 |
+
value="Sali-d afaylu",
|
| 834 |
+
show_label=False,
|
| 835 |
+
)
|
| 836 |
+
file_input = gr.File(
|
| 837 |
+
file_types=[".pdf", ".txt"],
|
| 838 |
+
show_label=False,
|
| 839 |
+
)
|
| 840 |
+
paste_input = gr.Textbox(
|
| 841 |
+
placeholder="Aru aḍris-ik dagi...",
|
| 842 |
+
lines=6,
|
| 843 |
+
visible=False,
|
| 844 |
+
show_label=False,
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
section_html("🎙️ Anallas",
|
| 848 |
+
"Fren anallas/anallast i tɣuri")
|
| 849 |
+
voice_dd = gr.Dropdown(
|
| 850 |
+
choices=VOICE_NAMES,
|
| 851 |
+
value="Unti",
|
| 852 |
+
show_label=False,
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
section_html("📐 Tisekkiwin",
|
| 856 |
+
"Acḥal n wawalen deg tseddaṛt")
|
| 857 |
+
target_words = gr.Slider(
|
| 858 |
+
30, 120, value=55, step=5,
|
| 859 |
+
show_label=False,
|
| 860 |
+
interactive=True,
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
with gr.Row():
|
| 864 |
+
btn_start = gr.Button("🚀 Bdu", variant="primary", scale=1)
|
| 865 |
+
btn_stop = gr.Button("⏹️ Sfeḍ", scale=1)
|
| 866 |
+
|
| 867 |
+
# ── Column 2: CONTROLS + PLAYER ─────────────────────────
|
| 868 |
+
with gr.Column(scale=1, min_width=340, elem_classes="kabyle-panel"):
|
| 869 |
+
|
| 870 |
+
with gr.Row():
|
| 871 |
+
btn_prev = gr.Button("⏮️ Deffir", scale=1)
|
| 872 |
+
btn_next = gr.Button("⏭️ Sdat", scale=1)
|
| 873 |
+
|
| 874 |
+
para_counter = gr.Markdown(
|
| 875 |
+
"### Taseddaṛt — / —",
|
| 876 |
+
elem_id="para-counter",
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
section_html("📊 Addad n Uselket",
|
| 880 |
+
"Aselmed n tseddaṛin akked wakud")
|
| 881 |
+
progress_md = gr.Markdown("")
|
| 882 |
+
|
| 883 |
+
section_html("🎧 Ameslaw",
|
| 884 |
+
"Ameslaw n tseddaṛt tettwafren")
|
| 885 |
+
audio_shell = gr.HTML(
|
| 886 |
+
"<div id='kabyle-audio-shell'></div>",
|
| 887 |
+
sanitize_html=False,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
section_html("🎵 Arured",
|
| 891 |
+
"0.50 = ẓẓay · 0.90 = amagnu · 1.20 = zerb")
|
| 892 |
+
speed_slider = gr.Slider(
|
| 893 |
+
0.50, 1.20, value=0.90, step=0.05,
|
| 894 |
+
show_label=False,
|
| 895 |
+
interactive=True,
|
| 896 |
+
elem_id="kabyle-speed",
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
# ── Column 3: TEXT ──────────────────────────────────────
|
| 900 |
+
with gr.Column(scale=1, elem_classes="kabyle-panel"):
|
| 901 |
+
doc_viewer = gr.HTML(VIEWER_PLACEHOLDER, sanitize_html=False)
|
| 902 |
+
|
| 903 |
+
timer = gr.Timer(2.0, active=True)
|
| 904 |
+
|
| 905 |
+
# ── Wiring ───────────────────────────────────────────────────
|
| 906 |
+
demo.load(fn=init_session, outputs=session_state)
|
| 907 |
+
|
| 908 |
+
btn_menu.click(
|
| 909 |
+
fn=toggle_menu,
|
| 910 |
+
inputs=[menu_visible],
|
| 911 |
+
outputs=[menu_col, menu_visible],
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
input_mode.change(
|
| 915 |
+
fn=toggle_input_mode,
|
| 916 |
+
inputs=input_mode,
|
| 917 |
+
outputs=[file_input, paste_input],
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
_out_start = [progress_md, audio_shell, doc_viewer, para_counter, session_state]
|
| 921 |
+
_out_nav = [audio_shell, doc_viewer, para_counter, session_state]
|
| 922 |
+
_out_timer = [progress_md, audio_shell, doc_viewer, para_counter, session_state]
|
| 923 |
+
|
| 924 |
+
btn_start.click(
|
| 925 |
+
fn=start_conversion,
|
| 926 |
+
inputs=[session_state, input_mode, file_input, paste_input,
|
| 927 |
+
target_words, voice_dd],
|
| 928 |
+
outputs=_out_start,
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
btn_stop.click(
|
| 932 |
+
fn=stop_generation,
|
| 933 |
+
inputs=[session_state],
|
| 934 |
+
outputs=_out_start,
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
btn_prev.click(
|
| 938 |
+
fn=lambda sid: navigate(sid, -1),
|
| 939 |
+
inputs=[session_state],
|
| 940 |
+
outputs=_out_nav,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
btn_next.click(
|
| 944 |
+
fn=lambda sid: navigate(sid, +1),
|
| 945 |
+
inputs=[session_state],
|
| 946 |
+
outputs=_out_nav,
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
timer.tick(
|
| 950 |
+
fn=timer_update,
|
| 951 |
+
inputs=[session_state],
|
| 952 |
+
outputs=_out_timer,
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
# ── Preload worker in background ────────────────────────────────
|
| 957 |
+
def _preload_worker():
|
| 958 |
+
try:
|
| 959 |
+
ensure_worker()
|
| 960 |
+
except Exception as e:
|
| 961 |
+
print(f"[parent] worker preload failed: {e}")
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
threading.Thread(target=_preload_worker, daemon=True).start()
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
if __name__ == "__main__":
|
| 968 |
+
demo.launch(
|
| 969 |
+
theme=gr.themes.Base(
|
| 970 |
+
primary_hue=gr.themes.colors.amber,
|
| 971 |
+
secondary_hue=gr.themes.colors.stone,
|
| 972 |
+
neutral_hue=gr.themes.colors.stone,
|
| 973 |
+
).set(
|
| 974 |
+
body_background_fill="#fdf8f0",
|
| 975 |
+
body_background_fill_dark="#1c1815",
|
| 976 |
+
block_background_fill="#ffffff",
|
| 977 |
+
block_border_color="#e7d9c4",
|
| 978 |
+
block_radius="12px",
|
| 979 |
+
button_primary_background_fill="#b45309",
|
| 980 |
+
button_primary_background_fill_hover="#92400e",
|
| 981 |
+
button_primary_text_color="#ffffff",
|
| 982 |
+
),
|
| 983 |
+
css=CUSTOM_CSS,
|
| 984 |
+
head=HEAD_JS,
|
| 985 |
+
allowed_paths=[TTS_CACHE_ABS],
|
| 986 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
|
| 3 |
+
gradio>=5.0
|
| 4 |
+
torch
|
| 5 |
+
torchaudio
|
| 6 |
+
omnivoice
|
| 7 |
+
soundfile
|
| 8 |
+
numpy<2
|
| 9 |
+
pdfplumber
|
| 10 |
+
psutil
|
runtime.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
python-3.10
|
tts_worker.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pure-console OmniVoice worker.
|
| 3 |
+
No Streamlit. No Gradio. No Flask. No web imports of any kind.
|
| 4 |
+
|
| 5 |
+
Protocol (JSON lines on stdin/stdout):
|
| 6 |
+
parent -> worker: {"cmd": "go"}
|
| 7 |
+
{"id": "...", "text": "...", "voice": "female"}
|
| 8 |
+
worker -> parent: {"event": "ready"}
|
| 9 |
+
{"event": "go-ack"}
|
| 10 |
+
{"event": "log", "msg": "..."}
|
| 11 |
+
{"event": "result", "id": "...", "ok": true,
|
| 12 |
+
"path": "tts_cache/xxxx.wav", "gen_s": 42.3,
|
| 13 |
+
"cached": false, "dur": 17.6}
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
# ────────────────────────────────────────────────────────────────
|
| 20 |
+
# ALL environment settings MUST be set before importing torch.
|
| 21 |
+
# ────────────────────────────────────────────────────────────────
|
| 22 |
+
THREADS = int(os.environ.get("TTS_THREADS", "8"))
|
| 23 |
+
os.environ["OMP_NUM_THREADS"] = str(THREADS)
|
| 24 |
+
os.environ["MKL_NUM_THREADS"] = str(THREADS)
|
| 25 |
+
os.environ["OPENBLAS_NUM_THREADS"] = "1"
|
| 26 |
+
os.environ["KMP_BLOCKTIME"] = "0"
|
| 27 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 28 |
+
|
| 29 |
+
# Persist the torch.compile (inductor) cache across process restarts.
|
| 30 |
+
COMPILE_CACHE = os.path.abspath(
|
| 31 |
+
os.environ.get("TTS_COMPILE_CACHE", "./tts_compile_cache")
|
| 32 |
+
)
|
| 33 |
+
os.makedirs(COMPILE_CACHE, exist_ok=True)
|
| 34 |
+
os.environ["TORCHINDUCTOR_CACHE_DIR"] = COMPILE_CACHE
|
| 35 |
+
os.environ["TRITON_CACHE_DIR"] = COMPILE_CACHE
|
| 36 |
+
|
| 37 |
+
# Silence the transformers image-processor import noise.
|
| 38 |
+
os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error")
|
| 39 |
+
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
|
| 40 |
+
|
| 41 |
+
import time
|
| 42 |
+
import json
|
| 43 |
+
import hashlib
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
|
| 46 |
+
import numpy as np
|
| 47 |
+
import torch
|
| 48 |
+
torch.set_num_threads(THREADS)
|
| 49 |
+
|
| 50 |
+
torch.set_num_interop_threads(1)
|
| 51 |
+
|
| 52 |
+
import soundfile as sf
|
| 53 |
+
from omnivoice import OmniVoice
|
| 54 |
+
|
| 55 |
+
CACHE_DIR = Path(os.environ.get("TTS_CACHE", "./tts_cache")).resolve()
|
| 56 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
|
| 58 |
+
SAMPLE_RATE = 24000
|
| 59 |
+
NUM_STEP = 12
|
| 60 |
+
GUIDANCE = 2.0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# ────────────────────────────────────────────────────────────────
|
| 64 |
+
# IPC helpers
|
| 65 |
+
# ────────────────────────────────────────────────────────────────
|
| 66 |
+
def emit(obj):
|
| 67 |
+
sys.stdout.write(json.dumps(obj) + "\n")
|
| 68 |
+
sys.stdout.flush()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def log(msg):
|
| 72 |
+
emit({"event": "log", "msg": msg})
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def read_line():
|
| 76 |
+
line = sys.stdin.readline()
|
| 77 |
+
if not line:
|
| 78 |
+
return None
|
| 79 |
+
line = line.strip()
|
| 80 |
+
return line if line else None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ────────────────────────────────────────────────────────────────
|
| 84 |
+
# Model loading
|
| 85 |
+
# ────────────────────────────────────────────────────────────────
|
| 86 |
+
def load_and_compile():
|
| 87 |
+
log(f"loading model (threads={THREADS}, inductor cache={COMPILE_CACHE})")
|
| 88 |
+
model = OmniVoice.from_pretrained(
|
| 89 |
+
"k2-fsa/OmniVoice",
|
| 90 |
+
device_map="cpu",
|
| 91 |
+
dtype=torch.float32,
|
| 92 |
+
attn_implementation="sdpa",
|
| 93 |
+
)
|
| 94 |
+
log("applying torch.compile(mode='reduce-overhead')...")
|
| 95 |
+
model = torch.compile(model, mode="reduce-overhead")
|
| 96 |
+
|
| 97 |
+
log("warm-up (pays compile cost here, not on first user request)...")
|
| 98 |
+
t0 = time.time()
|
| 99 |
+
with torch.inference_mode():
|
| 100 |
+
_ = model.generate(
|
| 101 |
+
text="azul",
|
| 102 |
+
language="kab",
|
| 103 |
+
instruct="male",
|
| 104 |
+
speed=1.0,
|
| 105 |
+
num_step=NUM_STEP,
|
| 106 |
+
guidance_scale=GUIDANCE,
|
| 107 |
+
denoise=True,
|
| 108 |
+
postprocess_output=True,
|
| 109 |
+
)
|
| 110 |
+
log(f"warm-up done in {time.time() - t0:.1f}s")
|
| 111 |
+
return model
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def cache_path(text, voice):
|
| 115 |
+
h = hashlib.sha256(f"{voice}::{text}".encode("utf-8")).hexdigest()
|
| 116 |
+
return CACHE_DIR / f"{h}.wav"
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def normalize(audio):
|
| 120 |
+
arr = audio
|
| 121 |
+
if hasattr(arr, "detach"):
|
| 122 |
+
arr = arr.detach().cpu().float().numpy()
|
| 123 |
+
arr = np.asarray(arr, dtype=np.float32).squeeze()
|
| 124 |
+
if arr.ndim > 1:
|
| 125 |
+
arr = arr.squeeze(0) if arr.shape[0] == 1 else arr.mean(axis=0)
|
| 126 |
+
return arr
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ────────────────────────────────────────────────────────────────
|
| 130 |
+
# Main loop
|
| 131 |
+
# ───────────────────────────��────────────────────────────────────
|
| 132 |
+
def main():
|
| 133 |
+
log("waiting for go...")
|
| 134 |
+
log(f"threads={torch.get_num_threads()} "
|
| 135 |
+
f"interop={torch.get_num_interop_threads()} "
|
| 136 |
+
f"OMP={os.environ.get('OMP_NUM_THREADS')} "
|
| 137 |
+
f"MKL={os.environ.get('MKL_NUM_THREADS')}")
|
| 138 |
+
# Handshake: wait for parent's "go" before touching torch so that
|
| 139 |
+
# the parent has time to set priority and CPU affinity.
|
| 140 |
+
log("waiting for go...")
|
| 141 |
+
while True:
|
| 142 |
+
line = read_line()
|
| 143 |
+
if line is None:
|
| 144 |
+
return
|
| 145 |
+
try:
|
| 146 |
+
msg = json.loads(line)
|
| 147 |
+
except Exception:
|
| 148 |
+
continue
|
| 149 |
+
if msg.get("cmd") == "go":
|
| 150 |
+
break
|
| 151 |
+
emit({"event": "go-ack"})
|
| 152 |
+
|
| 153 |
+
model = load_and_compile()
|
| 154 |
+
emit({"event": "ready"})
|
| 155 |
+
|
| 156 |
+
while True:
|
| 157 |
+
line = read_line()
|
| 158 |
+
if line is None:
|
| 159 |
+
return
|
| 160 |
+
try:
|
| 161 |
+
req = json.loads(line)
|
| 162 |
+
except Exception as e:
|
| 163 |
+
emit({"event": "result", "id": None, "ok": False,
|
| 164 |
+
"error": f"bad json: {e}"})
|
| 165 |
+
continue
|
| 166 |
+
|
| 167 |
+
rid = req.get("id")
|
| 168 |
+
text = (req.get("text") or "").strip()
|
| 169 |
+
voice = (req.get("voice") or "male").lower()
|
| 170 |
+
|
| 171 |
+
if not text:
|
| 172 |
+
emit({"event": "result", "id": rid, "ok": False,
|
| 173 |
+
"error": "empty text"})
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
out = cache_path(text, voice)
|
| 177 |
+
if out.exists():
|
| 178 |
+
emit({"event": "result", "id": rid, "ok": True,
|
| 179 |
+
"path": str(out), "cached": True, "gen_s": 0.0,
|
| 180 |
+
"sr": SAMPLE_RATE, "dur": 0.0})
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
t0 = time.time()
|
| 184 |
+
try:
|
| 185 |
+
with torch.inference_mode():
|
| 186 |
+
audio = model.generate(
|
| 187 |
+
text=text,
|
| 188 |
+
language="kab",
|
| 189 |
+
instruct=voice,
|
| 190 |
+
speed=1.0, # playback speed handled by browser
|
| 191 |
+
num_step=NUM_STEP,
|
| 192 |
+
guidance_scale=GUIDANCE,
|
| 193 |
+
denoise=True,
|
| 194 |
+
postprocess_output=True,
|
| 195 |
+
)
|
| 196 |
+
arr = normalize(audio[0])
|
| 197 |
+
sf.write(str(out), arr, SAMPLE_RATE, format="WAV")
|
| 198 |
+
gen_s = time.time() - t0
|
| 199 |
+
dur = len(arr) / SAMPLE_RATE
|
| 200 |
+
log(f"chunk done in {gen_s:.1f}s ({dur:.1f}s audio, "
|
| 201 |
+
f"{dur/gen_s:.2f}x realtime) -> {out.name}")
|
| 202 |
+
emit({"event": "result", "id": rid, "ok": True,
|
| 203 |
+
"path": str(out), "cached": False, "gen_s": gen_s,
|
| 204 |
+
"sr": SAMPLE_RATE, "dur": dur})
|
| 205 |
+
except Exception as e:
|
| 206 |
+
emit({"event": "result", "id": rid, "ok": False,
|
| 207 |
+
"error": str(e), "gen_s": time.time() - t0})
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
main()
|