Yi Jin commited on
Commit
a7c4935
·
unverified ·
1 Parent(s): a7573db

Added IAT and TTS SDK for app

Browse files
Files changed (5) hide show
  1. .gitignore +179 -0
  2. .vscode/settings.json +4 -0
  3. iat.py +106 -0
  4. requirements.txt +7 -0
  5. tts.py +98 -0
.gitignore ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ # End of https://www.toptal.com/developers/gitignore/api/python
177
+
178
+ config.yaml
179
+
.vscode/settings.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "python.analysis.autoImportCompletions": true,
3
+ "python.analysis.typeCheckingMode": "basic"
4
+ }
iat.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib.parse import urlparse, urlencode
2
+ from wsgiref.handlers import format_date_time
3
+ from datetime import datetime
4
+ import hmac
5
+ import hashlib
6
+ import base64
7
+ import numpy as np
8
+ import json
9
+ import websockets.client
10
+ from websockets.exceptions import ConnectionClosedError
11
+ import time
12
+
13
+ STATUS_FIRST_FRAME = 0
14
+ STATUS_CONTINUE_FRAME = 1
15
+ STATUS_LAST_FRAME = 2
16
+
17
+ '''
18
+ XFYun's IAT Client, which is used to convert speech to text.
19
+ '''
20
+ class IATClient:
21
+ def __init__(
22
+ self,
23
+ app_id: str,
24
+ api_key: str,
25
+ api_secret: str,
26
+ endpoint="wss://ws-api.xfyun.cn/v2/iat",
27
+ ) -> None:
28
+ self.app_id = app_id
29
+ self.api_key = api_key
30
+ self.api_secret = api_secret
31
+ self.endpoint = endpoint
32
+ self.common_args = {"app_id": self.app_id}
33
+ self.business_args = {
34
+ "domain": "iat",
35
+ "language": "zh_cn",
36
+ "accent": "mandarin",
37
+ "vinfo": 1,
38
+ "vad_eos": 10000,
39
+ }
40
+
41
+ # To convert ndarray audio data to PCM-style bytes
42
+ # Gradio Audio Module returns a tuple of (sampling_rate, np.ndarray)
43
+ # And the np.ndarray is the audio data, which is range from -32768 to 32767 matching PCM range.
44
+ def encode_pcm(self, source: np.ndarray):
45
+ return source.astype(np.int16).tobytes()
46
+
47
+ def create_url(self):
48
+ parse_result = urlparse(self.endpoint)
49
+ host = parse_result.hostname
50
+ # RFC1123 Timestamp
51
+ date = format_date_time(time.mktime(datetime.now().timetuple()))
52
+ path = parse_result.path
53
+
54
+ sign_raw_str = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
55
+ sign_sha = hmac.new(
56
+ self.api_secret.encode("utf-8"),
57
+ sign_raw_str.encode("utf-8"),
58
+ digestmod=hashlib.sha256,
59
+ ).digest()
60
+ auth_origin = 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (
61
+ self.api_key,
62
+ "hmac-sha256",
63
+ "host date request-line",
64
+ sign_sha,
65
+ )
66
+ auth = base64.b64encode(auth_origin.encode("utf-8")).decode("utf-8")
67
+ params = {
68
+ "authorization": auth,
69
+ "date": date,
70
+ "host": host,
71
+ }
72
+ url = f"{self.endpoint}?{urlencode(params)}"
73
+ return url
74
+
75
+ def prepare_data(self, audio: bytes, chunk_size=1280, sampling_rate=16000):
76
+ status = STATUS_FIRST_FRAME
77
+ for i in range(0, len(audio), chunk_size):
78
+ chunk = audio[i : i + chunk_size]
79
+ if i + chunk_size >= len(audio):
80
+ status = STATUS_LAST_FRAME
81
+ data = {
82
+ "status": status,
83
+ "format": f"audio/L16;rate={sampling_rate}",
84
+ "audio": base64.b64encode(chunk).decode("utf-8"),
85
+ "encoding": "raw",
86
+ }
87
+ payload = {"data": data}
88
+ if status == STATUS_FIRST_FRAME:
89
+ payload["common"] = self.common_args
90
+ payload["business"] = self.business_args
91
+ yield payload
92
+ status = STATUS_CONTINUE_FRAME
93
+
94
+ async def dictate(self, audio: tuple[int, np.ndarray], interval=0.4):
95
+ url = self.create_url()
96
+ sampling_rate, source = audio
97
+ pcm = self.encode_pcm(source)
98
+ async with websockets.client.connect(url) as ws:
99
+ for payload in self.prepare_data(pcm, sampling_rate=sampling_rate):
100
+ await ws.send(json.dumps(payload))
101
+ time.sleep(interval)
102
+ try:
103
+ async for message in ws:
104
+ yield message
105
+ except ConnectionClosedError as e:
106
+ print(f"Connection closed: {e.code} {e.reason}")
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ jupyter
3
+ requests
4
+ websocket-client
5
+ zhipuai
6
+ loguru
7
+ numpy
tts.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib.parse import urlparse, urlencode
2
+ from wsgiref.handlers import format_date_time
3
+ from datetime import datetime
4
+ import hmac
5
+ import hashlib
6
+ import base64
7
+ import numpy as np
8
+ import json
9
+ import websockets.client
10
+ from websockets.exceptions import ConnectionClosedError
11
+ import time
12
+
13
+ STATUS_FIRST_FRAME = 0
14
+ STATUS_CONTINUE_FRAME = 1
15
+ STATUS_LAST_FRAME = 2
16
+
17
+
18
+ class TTSClient:
19
+
20
+ def __init__(
21
+ self,
22
+ app_id: str,
23
+ api_key: str,
24
+ api_secret: str,
25
+ endpoint="wss://ws-api.xfyun.cn/v2/tts",
26
+ ) -> None:
27
+ self.app_id = app_id
28
+ self.api_key = api_key
29
+ self.api_secret = api_secret
30
+ self.endpoint = endpoint
31
+ self.common_args = {"app_id": self.app_id}
32
+ self.business_args = {
33
+ "aue": "raw",
34
+ "auf": "audio/L16;rate=16000",
35
+ "vcn": "xiaoyan",
36
+ "tte": "utf8",
37
+ }
38
+
39
+ def prepare_data(self, text: str):
40
+ return {
41
+ "common": self.common_args,
42
+ "business": self.business_args,
43
+ "data": {
44
+ "status": 2,
45
+ "text": str(base64.b64encode(text.encode("utf-8")), "UTF8"),
46
+ },
47
+ }
48
+
49
+ def create_url(self):
50
+ parse_result = urlparse(self.endpoint)
51
+ host = parse_result.hostname
52
+ # RFC1123 Timestamp
53
+ date = format_date_time(time.mktime(datetime.now().timetuple()))
54
+ path = parse_result.path
55
+
56
+ sign_raw_str = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
57
+ sign_sha = hmac.new(
58
+ self.api_secret.encode("utf-8"),
59
+ sign_raw_str.encode("utf-8"),
60
+ digestmod=hashlib.sha256,
61
+ ).digest()
62
+ auth_origin = 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (
63
+ self.api_key,
64
+ "hmac-sha256",
65
+ "host date request-line",
66
+ sign_sha,
67
+ )
68
+ auth = base64.b64encode(auth_origin.encode("utf-8")).decode("utf-8")
69
+ params = {
70
+ "authorization": auth,
71
+ "date": date,
72
+ "host": host,
73
+ }
74
+ url = f"{self.endpoint}?{urlencode(params)}"
75
+ return url
76
+
77
+ def parse_result(self, result: bytes) -> np.ndarray:
78
+ return np.frombuffer(result, dtype=np.int16)
79
+
80
+ async def generate(self, text: str):
81
+ url = self.create_url()
82
+ data = self.prepare_data(text)
83
+ result = bytearray()
84
+ async with websockets.client.connect(url) as ws:
85
+ await ws.send(json.dumps(data))
86
+ while True:
87
+ try:
88
+ message = await ws.recv()
89
+ message = json.loads(message)
90
+ audio = message["data"]["audio"]
91
+ audio = base64.b64decode(audio)
92
+ status = message["data"]["status"]
93
+ result += audio
94
+ if status == STATUS_LAST_FRAME:
95
+ break
96
+ except ConnectionClosedError:
97
+ break
98
+ return self.parse_result(bytes(result))