phoonnx 0.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phoonnx/__init__.py +0 -0
- phoonnx/config.py +490 -0
- phoonnx/locale/ca/phonetic_spellings.txt +2 -0
- phoonnx/locale/en/phonetic_spellings.txt +1 -0
- phoonnx/locale/gl/phonetic_spellings.txt +2 -0
- phoonnx/locale/pt/phonetic_spellings.txt +2 -0
- phoonnx/phoneme_ids.py +453 -0
- phoonnx/phonemizers/__init__.py +45 -0
- phoonnx/phonemizers/ar.py +42 -0
- phoonnx/phonemizers/base.py +216 -0
- phoonnx/phonemizers/en.py +250 -0
- phoonnx/phonemizers/fa.py +46 -0
- phoonnx/phonemizers/gl.py +142 -0
- phoonnx/phonemizers/he.py +67 -0
- phoonnx/phonemizers/ja.py +119 -0
- phoonnx/phonemizers/ko.py +97 -0
- phoonnx/phonemizers/mul.py +606 -0
- phoonnx/phonemizers/vi.py +44 -0
- phoonnx/phonemizers/zh.py +308 -0
- phoonnx/thirdparty/__init__.py +0 -0
- phoonnx/thirdparty/arpa2ipa.py +249 -0
- phoonnx/thirdparty/cotovia/cotovia_aarch64 +0 -0
- phoonnx/thirdparty/cotovia/cotovia_x86_64 +0 -0
- phoonnx/thirdparty/hangul2ipa.py +783 -0
- phoonnx/thirdparty/ko_tables/aspiration.csv +20 -0
- phoonnx/thirdparty/ko_tables/assimilation.csv +31 -0
- phoonnx/thirdparty/ko_tables/double_coda.csv +17 -0
- phoonnx/thirdparty/ko_tables/hanja.tsv +8525 -0
- phoonnx/thirdparty/ko_tables/ipa.csv +22 -0
- phoonnx/thirdparty/ko_tables/neutralization.csv +11 -0
- phoonnx/thirdparty/ko_tables/tensification.csv +56 -0
- phoonnx/thirdparty/ko_tables/yale.csv +22 -0
- phoonnx/thirdparty/kog2p/__init__.py +385 -0
- phoonnx/thirdparty/kog2p/rulebook.txt +212 -0
- phoonnx/thirdparty/mantoq/__init__.py +67 -0
- phoonnx/thirdparty/mantoq/buck/__init__.py +0 -0
- phoonnx/thirdparty/mantoq/buck/phonetise_buckwalter.py +569 -0
- phoonnx/thirdparty/mantoq/buck/symbols.py +64 -0
- phoonnx/thirdparty/mantoq/buck/tokenization.py +105 -0
- phoonnx/thirdparty/mantoq/num2words.py +37 -0
- phoonnx/thirdparty/mantoq/pyarabic/__init__.py +12 -0
- phoonnx/thirdparty/mantoq/pyarabic/arabrepr.py +64 -0
- phoonnx/thirdparty/mantoq/pyarabic/araby.py +1647 -0
- phoonnx/thirdparty/mantoq/pyarabic/named_const.py +227 -0
- phoonnx/thirdparty/mantoq/pyarabic/normalize.py +161 -0
- phoonnx/thirdparty/mantoq/pyarabic/number.py +826 -0
- phoonnx/thirdparty/mantoq/pyarabic/number_const.py +1704 -0
- phoonnx/thirdparty/mantoq/pyarabic/stack.py +52 -0
- phoonnx/thirdparty/mantoq/pyarabic/trans.py +517 -0
- phoonnx/thirdparty/mantoq/unicode_symbol2label.py +4173 -0
- phoonnx/thirdparty/tashkeel/LICENSE +22 -0
- phoonnx/thirdparty/tashkeel/SOURCE +1 -0
- phoonnx/thirdparty/tashkeel/__init__.py +212 -0
- phoonnx/thirdparty/tashkeel/hint_id_map.json +18 -0
- phoonnx/thirdparty/tashkeel/input_id_map.json +56 -0
- phoonnx/thirdparty/tashkeel/model.onnx +0 -0
- phoonnx/thirdparty/tashkeel/target_id_map.json +17 -0
- phoonnx/thirdparty/zh_num.py +238 -0
- phoonnx/util.py +705 -0
- phoonnx/version.py +6 -0
- phoonnx/voice.py +521 -0
- phoonnx-0.0.0.dist-info/METADATA +255 -0
- phoonnx-0.0.0.dist-info/RECORD +86 -0
- phoonnx-0.0.0.dist-info/WHEEL +5 -0
- phoonnx-0.0.0.dist-info/top_level.txt +2 -0
- phoonnx_train/__main__.py +151 -0
- phoonnx_train/export_onnx.py +109 -0
- phoonnx_train/norm_audio/__init__.py +92 -0
- phoonnx_train/norm_audio/trim.py +54 -0
- phoonnx_train/norm_audio/vad.py +54 -0
- phoonnx_train/preprocess.py +420 -0
- phoonnx_train/vits/__init__.py +0 -0
- phoonnx_train/vits/attentions.py +427 -0
- phoonnx_train/vits/commons.py +147 -0
- phoonnx_train/vits/config.py +330 -0
- phoonnx_train/vits/dataset.py +214 -0
- phoonnx_train/vits/lightning.py +352 -0
- phoonnx_train/vits/losses.py +58 -0
- phoonnx_train/vits/mel_processing.py +139 -0
- phoonnx_train/vits/models.py +732 -0
- phoonnx_train/vits/modules.py +527 -0
- phoonnx_train/vits/monotonic_align/__init__.py +20 -0
- phoonnx_train/vits/monotonic_align/setup.py +13 -0
- phoonnx_train/vits/transforms.py +212 -0
- phoonnx_train/vits/utils.py +16 -0
- phoonnx_train/vits/wavfile.py +860 -0
@@ -0,0 +1,22 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2023 Musharraf
|
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.
|
22
|
+
|
@@ -0,0 +1 @@
|
|
1
|
+
https://github.com/mush42/libtashkeel
|
@@ -0,0 +1,212 @@
|
|
1
|
+
"""Python implementation of libtashkeel.
|
2
|
+
|
3
|
+
See: https://github.com/mush42/libtashkeel
|
4
|
+
|
5
|
+
Ported with the help of ChatGPT 2025-05-01.
|
6
|
+
"""
|
7
|
+
|
8
|
+
import json
|
9
|
+
from pathlib import Path
|
10
|
+
from typing import Optional, Union
|
11
|
+
|
12
|
+
import numpy as np
|
13
|
+
from onnxruntime import InferenceSession
|
14
|
+
|
15
|
+
TASHKEEL_DIR = Path(__file__).parent
|
16
|
+
CHAR_LIMIT = 12000
|
17
|
+
PAD = "_"
|
18
|
+
NUMERAL_SYMBOL = "#"
|
19
|
+
NUMERALS = set("0123456789٠١٢٣٤٥٦٧٨٩")
|
20
|
+
HARAKAT_CHARS = {"\u064c", "\u064d", "\u064e", "\u064f", "\u0650", "\u0651", "\u0652"}
|
21
|
+
ARABIC_DIACRITICS = set(map(chr, [1618, 1617, 1614, 1615, 1616, 1611, 1612, 1613]))
|
22
|
+
NORMALIZED_DIAC_MAP = {"َّ": "َّ", "ًّ": "ًّ", "ُّ": "ُّ", "ٌّ": "ٌّ", "ِّ": "ِّ", "ٍّ": "ٍّ"}
|
23
|
+
SUKOON = chr(0x652)
|
24
|
+
|
25
|
+
|
26
|
+
class TashkeelError(Exception):
|
27
|
+
"""Error for tashkeel."""
|
28
|
+
|
29
|
+
|
30
|
+
class TashkeelDiacritizer:
|
31
|
+
"""Add diacritics for Arabic text with libtashkeel."""
|
32
|
+
|
33
|
+
def __init__(self, model_dir: Union[str, Path] = TASHKEEL_DIR) -> None:
|
34
|
+
"""Initialize diacritizer."""
|
35
|
+
model_dir = Path(model_dir)
|
36
|
+
self.session = InferenceSession(model_dir / "model.onnx")
|
37
|
+
|
38
|
+
# Load JSON maps
|
39
|
+
with open(
|
40
|
+
model_dir / "input_id_map.json", "r", encoding="utf-8"
|
41
|
+
) as input_id_map_file:
|
42
|
+
self.input_id_map: dict[str, int] = json.load(input_id_map_file)
|
43
|
+
|
44
|
+
with open(
|
45
|
+
model_dir / "target_id_map.json", "r", encoding="utf-8"
|
46
|
+
) as target_id_map_file:
|
47
|
+
target_id_map: dict[str, int] = json.load(target_id_map_file)
|
48
|
+
self.id_target_map: dict[int, str] = {
|
49
|
+
i: c for c, i in target_id_map.items()
|
50
|
+
}
|
51
|
+
|
52
|
+
self.target_id_meta_chars: set[int] = {target_id_map[c] for c in [PAD]}
|
53
|
+
|
54
|
+
with open(
|
55
|
+
model_dir / "hint_id_map.json", "r", encoding="utf-8"
|
56
|
+
) as hint_id_map_file:
|
57
|
+
self.hint_id_map: dict[str, int] = json.load(hint_id_map_file)
|
58
|
+
|
59
|
+
def __call__(self, text: str, taskeen_threshold: Optional[float] = None) -> str:
|
60
|
+
"""Add diacritics using libtashkeel."""
|
61
|
+
return self.diacritize(text)
|
62
|
+
|
63
|
+
def diacritize(self, text: str, taskeen_threshold=None) -> str:
|
64
|
+
"""Add diacritics using libtashkeel."""
|
65
|
+
text = text.strip()
|
66
|
+
|
67
|
+
if len(text) > CHAR_LIMIT:
|
68
|
+
raise TashkeelError(f"Text length cannot exceed {CHAR_LIMIT}")
|
69
|
+
|
70
|
+
input_text, removed_chars = self._to_valid_chars(text)
|
71
|
+
input_text, diacritics = self._extract_chars_and_diacritics(
|
72
|
+
input_text, normalize_diacritics=True
|
73
|
+
)
|
74
|
+
|
75
|
+
input_ids = self._input_to_ids(input_text)
|
76
|
+
diac_ids = self._hint_to_ids(diacritics)
|
77
|
+
seq_length = len(input_ids)
|
78
|
+
|
79
|
+
if seq_length == 0:
|
80
|
+
return text
|
81
|
+
|
82
|
+
target_ids, logits = self._infer(input_ids, diac_ids, seq_length)
|
83
|
+
|
84
|
+
diacritics = self._target_to_diacritics(target_ids)
|
85
|
+
if taskeen_threshold is None:
|
86
|
+
return self._annotate_text_with_diacritics(text, diacritics, removed_chars)
|
87
|
+
|
88
|
+
return self._annotate_text_with_diacritics_taskeen(
|
89
|
+
text, diacritics, removed_chars, logits, taskeen_threshold
|
90
|
+
)
|
91
|
+
|
92
|
+
def _infer(
|
93
|
+
self, input_ids: list[int], diac_ids: list[int], seq_length: int
|
94
|
+
) -> tuple[list[int], list[float]]:
|
95
|
+
"""Infer target ids and logits."""
|
96
|
+
input_ids_arr = np.array(input_ids, dtype=np.int64).reshape(1, seq_length)
|
97
|
+
diac_ids_arr = np.array(diac_ids, dtype=np.int64).reshape(1, seq_length)
|
98
|
+
input_len_arr = np.array([seq_length], dtype=np.int64).reshape(1)
|
99
|
+
|
100
|
+
inputs = {
|
101
|
+
"char_inputs": input_ids_arr,
|
102
|
+
"diac_inputs": diac_ids_arr,
|
103
|
+
"input_lengths": input_len_arr,
|
104
|
+
}
|
105
|
+
|
106
|
+
outputs = self.session.run(None, inputs)
|
107
|
+
|
108
|
+
# Output 0: target_ids (u8)
|
109
|
+
# Output 1: logits (f32)
|
110
|
+
target_ids = outputs[0].flatten().astype(np.uint8).tolist()
|
111
|
+
logits = outputs[1].flatten().astype(np.float32).tolist()
|
112
|
+
|
113
|
+
return target_ids, logits
|
114
|
+
|
115
|
+
def _annotate_text_with_diacritics(
|
116
|
+
self, input_text: str, diacritics: list[str], removed_chars: set[str]
|
117
|
+
) -> str:
|
118
|
+
output: list[str] = []
|
119
|
+
diac_iter = iter(diacritics)
|
120
|
+
for c in input_text:
|
121
|
+
if self._is_diacritic_char(c):
|
122
|
+
continue
|
123
|
+
|
124
|
+
if c in removed_chars:
|
125
|
+
output.append(c)
|
126
|
+
else:
|
127
|
+
output.append(c)
|
128
|
+
output.append(next(diac_iter, ""))
|
129
|
+
|
130
|
+
return "".join(output)
|
131
|
+
|
132
|
+
def _annotate_text_with_diacritics_taskeen(
|
133
|
+
self,
|
134
|
+
input_text: str,
|
135
|
+
diacritics: list[str],
|
136
|
+
removed_chars: set[str],
|
137
|
+
logits: list[float],
|
138
|
+
threshold: float,
|
139
|
+
) -> str:
|
140
|
+
output: list[str] = []
|
141
|
+
diac_iter = zip(diacritics, logits)
|
142
|
+
for c in input_text:
|
143
|
+
if self._is_diacritic_char(c):
|
144
|
+
continue
|
145
|
+
|
146
|
+
if c in removed_chars:
|
147
|
+
output.append(c)
|
148
|
+
else:
|
149
|
+
output.append(c)
|
150
|
+
diac, logit = next(diac_iter, ("", 0.0))
|
151
|
+
if logit > threshold:
|
152
|
+
output.append(SUKOON)
|
153
|
+
else:
|
154
|
+
output.append(diac)
|
155
|
+
return "".join(output)
|
156
|
+
|
157
|
+
def _is_diacritic_char(self, c) -> bool:
|
158
|
+
return c in ARABIC_DIACRITICS
|
159
|
+
|
160
|
+
def _extract_chars_and_diacritics(
|
161
|
+
self, text: str, normalize_diacritics: bool = True
|
162
|
+
) -> tuple[str, list[str]]:
|
163
|
+
text = text.lstrip("".join(ARABIC_DIACRITICS))
|
164
|
+
|
165
|
+
clean_chars = []
|
166
|
+
diacritics = []
|
167
|
+
pending_diac = ""
|
168
|
+
|
169
|
+
for c in list(text) + [" "]: # emulate .chain(iter::once(' '))
|
170
|
+
if self._is_diacritic_char(c):
|
171
|
+
pending_diac += c
|
172
|
+
else:
|
173
|
+
clean_chars.append(c)
|
174
|
+
diacritics.append(pending_diac)
|
175
|
+
pending_diac = ""
|
176
|
+
|
177
|
+
if clean_chars:
|
178
|
+
clean_chars.pop() # pop the trailing space equivalent
|
179
|
+
if diacritics:
|
180
|
+
diacritics.pop(0) # remove initial empty
|
181
|
+
|
182
|
+
if normalize_diacritics:
|
183
|
+
for i, d in enumerate(diacritics):
|
184
|
+
if d not in self.hint_id_map:
|
185
|
+
diacritics[i] = NORMALIZED_DIAC_MAP.get(d, "")
|
186
|
+
|
187
|
+
return "".join(clean_chars), diacritics
|
188
|
+
|
189
|
+
def _to_valid_chars(self, text: str) -> tuple[str, set[str]]:
|
190
|
+
valid: list[str] = []
|
191
|
+
invalid: set[str] = set()
|
192
|
+
for c in text:
|
193
|
+
if (c in self.input_id_map) or (c in ARABIC_DIACRITICS):
|
194
|
+
valid.append(c)
|
195
|
+
elif c in NUMERALS:
|
196
|
+
valid.append(NUMERAL_SYMBOL)
|
197
|
+
else:
|
198
|
+
invalid.add(c)
|
199
|
+
return "".join(valid), invalid
|
200
|
+
|
201
|
+
def _input_to_ids(self, text: str) -> list[int]:
|
202
|
+
return [self.input_id_map[c] for c in text]
|
203
|
+
|
204
|
+
def _hint_to_ids(self, diacritics: list[str]) -> list[int]:
|
205
|
+
return [self.hint_id_map[d] for d in diacritics]
|
206
|
+
|
207
|
+
def _target_to_diacritics(self, target_ids: list[int]) -> list[str]:
|
208
|
+
return [
|
209
|
+
self.id_target_map[i]
|
210
|
+
for i in target_ids
|
211
|
+
if i not in self.target_id_meta_chars
|
212
|
+
]
|
@@ -0,0 +1,56 @@
|
|
1
|
+
{
|
2
|
+
"_": 0,
|
3
|
+
" ": 1,
|
4
|
+
"#": 2,
|
5
|
+
"!": 3,
|
6
|
+
"\"": 4,
|
7
|
+
"(": 5,
|
8
|
+
")": 6,
|
9
|
+
"-": 7,
|
10
|
+
".": 8,
|
11
|
+
"/": 9,
|
12
|
+
":": 10,
|
13
|
+
"[": 11,
|
14
|
+
"]": 12,
|
15
|
+
"«": 13,
|
16
|
+
"»": 14,
|
17
|
+
"،": 15,
|
18
|
+
"؛": 16,
|
19
|
+
"؟": 17,
|
20
|
+
"ء": 18,
|
21
|
+
"آ": 19,
|
22
|
+
"أ": 20,
|
23
|
+
"ؤ": 21,
|
24
|
+
"إ": 22,
|
25
|
+
"ئ": 23,
|
26
|
+
"ا": 24,
|
27
|
+
"ب": 25,
|
28
|
+
"ة": 26,
|
29
|
+
"ت": 27,
|
30
|
+
"ث": 28,
|
31
|
+
"ج": 29,
|
32
|
+
"ح": 30,
|
33
|
+
"خ": 31,
|
34
|
+
"د": 32,
|
35
|
+
"ذ": 33,
|
36
|
+
"ر": 34,
|
37
|
+
"ز": 35,
|
38
|
+
"س": 36,
|
39
|
+
"ش": 37,
|
40
|
+
"ص": 38,
|
41
|
+
"ض": 39,
|
42
|
+
"ط": 40,
|
43
|
+
"ظ": 41,
|
44
|
+
"ع": 42,
|
45
|
+
"غ": 43,
|
46
|
+
"ف": 44,
|
47
|
+
"ق": 45,
|
48
|
+
"ك": 46,
|
49
|
+
"ل": 47,
|
50
|
+
"م": 48,
|
51
|
+
"ن": 49,
|
52
|
+
"ه": 50,
|
53
|
+
"و": 51,
|
54
|
+
"ى": 52,
|
55
|
+
"ي": 53
|
56
|
+
}
|
Binary file
|
@@ -0,0 +1,238 @@
|
|
1
|
+
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
"""
|
15
|
+
Rules to verbalize numbers into Chinese characters.
|
16
|
+
https://zh.wikipedia.org/wiki/中文数字#現代中文
|
17
|
+
"""
|
18
|
+
import re
|
19
|
+
from collections import OrderedDict
|
20
|
+
from typing import List
|
21
|
+
|
22
|
+
DIGITS = {str(i): tran for i, tran in enumerate('零一二三四五六七八九')}
|
23
|
+
UNITS = OrderedDict({
|
24
|
+
1: '十',
|
25
|
+
2: '百',
|
26
|
+
3: '千',
|
27
|
+
4: '万',
|
28
|
+
8: '亿',
|
29
|
+
})
|
30
|
+
|
31
|
+
COM_QUANTIFIERS = '(封|艘|把|目|套|段|人|所|朵|匹|张|座|回|场|尾|条|个|首|阙|阵|网|炮|顶|丘|棵|只|支|袭|辆|挑|担|颗|壳|窠|曲|墙|群|腔|砣|座|客|贯|扎|捆|刀|令|打|手|罗|坡|山|岭|江|溪|钟|队|单|双|对|出|口|头|脚|板|跳|枝|件|贴|针|线|管|名|位|身|堂|课|本|页|家|户|层|丝|毫|厘|分|钱|两|斤|担|铢|石|钧|锱|忽|(千|毫|微)克|毫|厘|(公)分|分|寸|尺|丈|里|寻|常|铺|程|(千|分|厘|毫|微)米|米|撮|勺|合|升|斗|石|盘|碗|碟|叠|桶|笼|盆|盒|杯|钟|斛|锅|簋|篮|盘|桶|罐|瓶|壶|卮|盏|箩|箱|煲|啖|袋|钵|年|月|日|季|刻|时|周|天|秒|分|小时|旬|纪|岁|世|更|夜|春|夏|秋|冬|代|伏|辈|丸|泡|粒|颗|幢|堆|条|根|支|道|面|片|张|颗|块|元|(亿|千万|百万|万|千|百)|(亿|千万|百万|万|千|百|美|)元|(亿|千万|百万|万|千|百|十|)吨|(亿|千万|百万|万|千|百|)块|角|毛|分|(公(里|引|丈|尺|寸|分|釐)))'
|
32
|
+
|
33
|
+
# 分数表达式
|
34
|
+
RE_FRAC = re.compile(r'(-?)(\d+)/(\d+)')
|
35
|
+
|
36
|
+
|
37
|
+
def replace_frac(match) -> str:
|
38
|
+
"""
|
39
|
+
Args:
|
40
|
+
match (re.Match)
|
41
|
+
Returns:
|
42
|
+
str
|
43
|
+
"""
|
44
|
+
sign = match.group(1)
|
45
|
+
nominator = match.group(2)
|
46
|
+
denominator = match.group(3)
|
47
|
+
sign: str = "负" if sign else ""
|
48
|
+
nominator: str = num2str(nominator)
|
49
|
+
denominator: str = num2str(denominator)
|
50
|
+
result = f"{sign}{denominator}分之{nominator}"
|
51
|
+
return result
|
52
|
+
|
53
|
+
|
54
|
+
# 百分数表达式
|
55
|
+
RE_PERCENTAGE = re.compile(r'(-?)(\d+(\.\d+)?)%')
|
56
|
+
|
57
|
+
|
58
|
+
def replace_percentage(match) -> str:
|
59
|
+
"""
|
60
|
+
Args:
|
61
|
+
match (re.Match)
|
62
|
+
Returns:
|
63
|
+
str
|
64
|
+
"""
|
65
|
+
sign = match.group(1)
|
66
|
+
percent = match.group(2)
|
67
|
+
sign: str = "负" if sign else ""
|
68
|
+
percent: str = num2str(percent)
|
69
|
+
result = f"{sign}百分之{percent}"
|
70
|
+
return result
|
71
|
+
|
72
|
+
|
73
|
+
# 整数表达式
|
74
|
+
# 带负号的整数 -10
|
75
|
+
RE_INTEGER = re.compile(r'(-)' r'(\d+)')
|
76
|
+
|
77
|
+
|
78
|
+
def replace_negative_num(match) -> str:
|
79
|
+
"""
|
80
|
+
Args:
|
81
|
+
match (re.Match)
|
82
|
+
Returns:
|
83
|
+
str
|
84
|
+
"""
|
85
|
+
sign = match.group(1)
|
86
|
+
number = match.group(2)
|
87
|
+
sign: str = "负" if sign else ""
|
88
|
+
number: str = num2str(number)
|
89
|
+
result = f"{sign}{number}"
|
90
|
+
return result
|
91
|
+
|
92
|
+
|
93
|
+
# 编号-无符号整形
|
94
|
+
# 00078
|
95
|
+
RE_DEFAULT_NUM = re.compile(r'\d{3}\d*')
|
96
|
+
|
97
|
+
|
98
|
+
def replace_default_num(match):
|
99
|
+
"""
|
100
|
+
Args:
|
101
|
+
match (re.Match)
|
102
|
+
Returns:
|
103
|
+
str
|
104
|
+
"""
|
105
|
+
number = match.group(0)
|
106
|
+
return verbalize_digit(number, alt_one=True)
|
107
|
+
|
108
|
+
|
109
|
+
# 数字表达式
|
110
|
+
# 纯小数
|
111
|
+
RE_DECIMAL_NUM = re.compile(r'(-?)((\d+)(\.\d+))' r'|(\.(\d+))')
|
112
|
+
# 正整数 + 量词
|
113
|
+
RE_POSITIVE_QUANTIFIERS = re.compile(r"(\d+)([多余几\+])?" + COM_QUANTIFIERS)
|
114
|
+
RE_NUMBER = re.compile(r'(-?)((\d+)(\.\d+)?)' r'|(\.(\d+))')
|
115
|
+
|
116
|
+
|
117
|
+
def replace_positive_quantifier(match) -> str:
|
118
|
+
"""
|
119
|
+
Args:
|
120
|
+
match (re.Match)
|
121
|
+
Returns:
|
122
|
+
str
|
123
|
+
"""
|
124
|
+
number = match.group(1)
|
125
|
+
match_2 = match.group(2)
|
126
|
+
if match_2 == "+":
|
127
|
+
match_2 = "多"
|
128
|
+
match_2: str = match_2 if match_2 else ""
|
129
|
+
quantifiers: str = match.group(3)
|
130
|
+
number: str = num2str(number)
|
131
|
+
result = f"{number}{match_2}{quantifiers}"
|
132
|
+
return result
|
133
|
+
|
134
|
+
|
135
|
+
def replace_number(match) -> str:
|
136
|
+
"""
|
137
|
+
Args:
|
138
|
+
match (re.Match)
|
139
|
+
Returns:
|
140
|
+
str
|
141
|
+
"""
|
142
|
+
sign = match.group(1)
|
143
|
+
number = match.group(2)
|
144
|
+
pure_decimal = match.group(5)
|
145
|
+
if pure_decimal:
|
146
|
+
result = num2str(pure_decimal)
|
147
|
+
else:
|
148
|
+
sign: str = "负" if sign else ""
|
149
|
+
number: str = num2str(number)
|
150
|
+
result = f"{sign}{number}"
|
151
|
+
return result
|
152
|
+
|
153
|
+
|
154
|
+
# 范围表达式
|
155
|
+
# match.group(1) and match.group(8) are copy from RE_NUMBER
|
156
|
+
|
157
|
+
RE_RANGE = re.compile(
|
158
|
+
r'((-?)((\d+)(\.\d+)?)|(\.(\d+)))[-~]((-?)((\d+)(\.\d+)?)|(\.(\d+)))')
|
159
|
+
|
160
|
+
|
161
|
+
def replace_range(match) -> str:
|
162
|
+
"""
|
163
|
+
Args:
|
164
|
+
match (re.Match)
|
165
|
+
Returns:
|
166
|
+
str
|
167
|
+
"""
|
168
|
+
first, second = match.group(1), match.group(8)
|
169
|
+
first = RE_NUMBER.sub(replace_number, first)
|
170
|
+
second = RE_NUMBER.sub(replace_number, second)
|
171
|
+
result = f"{first}到{second}"
|
172
|
+
return result
|
173
|
+
|
174
|
+
|
175
|
+
def _get_value(value_string: str, use_zero: bool=True) -> List[str]:
|
176
|
+
stripped = value_string.lstrip('0')
|
177
|
+
if len(stripped) == 0:
|
178
|
+
return []
|
179
|
+
elif len(stripped) == 1:
|
180
|
+
if use_zero and len(stripped) < len(value_string):
|
181
|
+
return [DIGITS['0'], DIGITS[stripped]]
|
182
|
+
else:
|
183
|
+
return [DIGITS[stripped]]
|
184
|
+
else:
|
185
|
+
largest_unit = next(
|
186
|
+
power for power in reversed(UNITS.keys()) if power < len(stripped))
|
187
|
+
first_part = value_string[:-largest_unit]
|
188
|
+
second_part = value_string[-largest_unit:]
|
189
|
+
return _get_value(first_part) + [UNITS[largest_unit]] + _get_value(
|
190
|
+
second_part)
|
191
|
+
|
192
|
+
|
193
|
+
def verbalize_cardinal(value_string: str) -> str:
|
194
|
+
if not value_string:
|
195
|
+
return ''
|
196
|
+
|
197
|
+
# 000 -> '零' , 0 -> '零'
|
198
|
+
value_string = value_string.lstrip('0')
|
199
|
+
if len(value_string) == 0:
|
200
|
+
return DIGITS['0']
|
201
|
+
|
202
|
+
result_symbols = _get_value(value_string)
|
203
|
+
# verbalized number starting with '一十*' is abbreviated as `十*`
|
204
|
+
if len(result_symbols) >= 2 and result_symbols[0] == DIGITS[
|
205
|
+
'1'] and result_symbols[1] == UNITS[1]:
|
206
|
+
result_symbols = result_symbols[1:]
|
207
|
+
return ''.join(result_symbols)
|
208
|
+
|
209
|
+
|
210
|
+
def verbalize_digit(value_string: str, alt_one=False) -> str:
|
211
|
+
result_symbols = [DIGITS[digit] for digit in value_string]
|
212
|
+
result = ''.join(result_symbols)
|
213
|
+
if alt_one:
|
214
|
+
result = result.replace("一", "幺")
|
215
|
+
return result
|
216
|
+
|
217
|
+
|
218
|
+
def num2str(value_string: str) -> str:
|
219
|
+
integer_decimal = value_string.split('.')
|
220
|
+
if len(integer_decimal) == 1:
|
221
|
+
integer = integer_decimal[0]
|
222
|
+
decimal = ''
|
223
|
+
elif len(integer_decimal) == 2:
|
224
|
+
integer, decimal = integer_decimal
|
225
|
+
else:
|
226
|
+
raise ValueError(
|
227
|
+
f"The value string: '${value_string}' has more than one point in it."
|
228
|
+
)
|
229
|
+
|
230
|
+
result = verbalize_cardinal(integer)
|
231
|
+
|
232
|
+
decimal = decimal.rstrip('0')
|
233
|
+
if decimal:
|
234
|
+
# '.22' is verbalized as '零点二二'
|
235
|
+
# '3.20' is verbalized as '三点二
|
236
|
+
result = result if result else "零"
|
237
|
+
result += '点' + verbalize_digit(decimal)
|
238
|
+
return result
|