main.py
10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# -*- coding: UTF-8 -*-
import argparse
import multiprocessing
import traceback
from kafka_service import funasr_producer
import os
import random
import shutil
import threading
import time
import uuid
import pydantic
import uvicorn
import sys
from utils import ap_scheduler_util
from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel
from mysql_service import funasr_db
from kafka_service import funasr_consumer
from kafka_service import simple_consumer
import gc
from funasr_service import FunasrService
current_dir = os.path.dirname(os.path.abspath(__file__))
# 将根目录添加到 Python 解释器的搜索路径中
root_dir = os.path.join(current_dir, '..') # 假设根目录是当前目录的父目录
sys.path.append(root_dir)
from log.logger import log
app = FastAPI()
class BaseResponse(BaseModel):
code: int = pydantic.Field(200, description="HTTP status code")
msg: str = pydantic.Field("success", description="HTTP status message")
data: object = pydantic.Field([], description="HTTP return data")
time_consuming: int = pydantic.Field(
11, description="HTTP return data time consuming"
)
class Config:
schema_extra = {
"example": {
"code": 200,
"msg": "success",
"data": [],
"time_consuming": 11,
}
}
def generate_random_filename():
timestamp = int(time.time()) # 获取当前时间戳
random_number = random.randint(1000, 9999) # 生成一个随机数
filename = f"file_{timestamp}_{random_number}" # 创建文件名
return filename + ".wav"
@app.get("/")
def hello_world():
print("Hello World!")
return "Hello World!"
@app.get("/funasr/exit")
def exit():
log.info(f"funasr exit !")
sys.exit(0)
@app.get("/funasr/")
async def transform_file():
consuming_start_time = time.perf_counter()
res = FunasrService("audios/asr_example.wav").transform()
# res = FunasrService("123456.wav").transform()
answer = []
print(str(res[0]["sentence_info"]))
for one in res[0]["sentence_info"]:
start_time = one['start']
end_time = one['end']
answer.append(
f'{"角色1" if one["spk"] == 0 else "角色2"} : {one["text"]} -- 时长:{end_time - start_time}ms'
)
consuming_end_time = time.perf_counter()
print(f"Function transform_file executed in {(consuming_end_time - consuming_start_time)} 秒")
log.info(f"Function transform_file executed in {(consuming_end_time - consuming_start_time)} 秒")
return BaseResponse(
code=200,
msg=res[0]["text"],
data=answer,
time_consuming=int(consuming_end_time - consuming_start_time),
)
@app.post("/funasr/file/")
async def create_file(file: bytes = File()):
# 获取文件内容
# 打开文件以写入模式
try:
consuming_start_time = time.perf_counter()
save_path = f"audios/"
if not os.path.exists(save_path):
os.mkdir(save_path)
save_path = f"audios/{str(threading.current_thread().ident)}/"
if not os.path.exists(save_path):
os.mkdir(save_path)
save_file = os.path.join(save_path, generate_random_filename())
with open(save_file, "wb") as f:
# 将接收到的文件内容写入文件中
# while content := await file.read(1024):
# f.write(content)
f.write(file)
print({"file_size": len(file)})
# 解析音频
res = FunasrService(save_file).transform()
answer = []
print(str(res[0]["sentence_info"]))
for one in res[0]["sentence_info"]:
start_time = one['start']
end_time = one['end']
answer.append(
f'{"角色1" if one["spk"] == 0 else "角色2"} : {one["text"]} -- 时长:{end_time - start_time}ms'
)
consuming_end_time = time.perf_counter()
print(f"Function create_file executed in {(consuming_end_time - consuming_start_time)} 秒")
log.info(f"Function create_file executed in {(consuming_end_time - consuming_start_time)} 秒")
os.remove(save_file)
response = BaseResponse(
code=200,
msg=res[0]["text"],
data=answer,
time_consuming=int(consuming_end_time - consuming_start_time),
)
print(f"response:{response}")
return response
except Exception as e:
os.remove(save_file)
return {"error": str(e)}
@app.post("/funasr/uploadfile/")
async def create_upload_file(file: UploadFile):
try:
consuming_start_time = time.perf_counter()
fn = file.filename
save_path = f"audios/"
if not os.path.exists(save_path):
os.mkdir(save_path)
save_path = f"audios/{str(threading.current_thread().ident)}/"
if not os.path.exists(save_path):
os.mkdir(save_path)
save_file = os.path.join(save_path, fn)
with open(save_file, "wb") as f:
# 将接收到的文件内容写入文件中
while content := await file.read(1024):
f.write(content)
print({"filename": file.filename})
# 解析音频
res = FunasrService(save_file).transform()
answer = []
print(str(res[0]["sentence_info"]))
for one in res[0]["sentence_info"]:
start_time = one['start']
end_time = one['end']
answer.append(
f'{"角色1" if one["spk"] == 0 else "角色2"} : {one["text"]} -- 时长:{end_time - start_time}ms'
)
consuming_end_time = time.perf_counter()
print(f"Function create_upload_file executed in {(consuming_end_time - consuming_start_time)} 秒")
log.info(
f"Function create_upload_file executed in {(consuming_end_time - consuming_start_time)} 秒"
)
os.remove(save_file)
return BaseResponse(
code=200,
msg=res[0]["text"],
data=answer,
time_consuming=int(consuming_end_time - consuming_start_time),
)
except Exception as e:
os.remove(save_file)
return {"error": str(e)}
class UrlParam(BaseModel):
url: str
@app.post("/funasr/url/")
async def create_url(param: UrlParam):
try:
log.info(f"funasr create_url api param:{param}")
url = param.url
if url is None:
return BaseResponse(
code=-1,
msg="error",
data="url is empty"
)
url.replace(" ", "")
if url == "" or len(url) < 1 or not url.startswith("http"):
return BaseResponse(
code=-1,
msg="error",
data="url format error"
)
task_id = str(uuid.uuid1())
res = funasr_db.insert_ali_asr_model_res(task_id, url)
if res is None or (isinstance(res, bool) and res is False):
return BaseResponse(
code=-1,
msg="error",
data="数据库异常"
)
funasr_producer.send_message_analysis({"task_id": task_id})
response = BaseResponse(
code=200,
msg="success",
data={"task_id": str(task_id)}
)
log.info(f"response:{response}")
return response
except Exception as e:
log.error(f"error:{traceback.format_exc()}")
return BaseResponse(
code=-1,
msg="error",
data=str(e)
)
def start_process():
process = multiprocessing.Process(target=funasr_consumer.consume_kafka, )
log.info(f"process:{process}")
process.start()
def start_process_kafka():
processes_num = 2
process_pool = multiprocessing.Pool(processes=processes_num, initializer=consumer_process_init)
log.info(f"main process_pool1:{process_pool}")
for i in range(processes_num):
process_pool.apply_async(func=funasr_consumer.consume_kafka,
# args=(),
callback=consumer_process_callback,
error_callback=consumer_process_error_callback)
def consumer_process_init():
process_name = str(multiprocessing.current_process().name)
log.info(f"consumer_process_init process_name:{process_name}")
# try:
# res = funasr_db.select_process_fail_task(process_name)
# if res is not None:
# data = {"task_id": res[0]["task_id"]}
# message = json.dumps(data).encode('utf-8')
# funasr_service.handle_process(str(message))
# except Exception as e:
# log.error(f"consumer_process_init_error process_name:{process_name}", e)
def consumer_process_callback(res):
log.info(f"consumer_process_callback:{multiprocessing.current_process().name}, res:{res}")
# count = funasr_db.select_process_all_end()
# if count is not None and int(count) == 0:
# res = funasr_db.select_ali_asr_model_wait()
# if res is not None and len(res) > 0:
# data = {"task_id": res[0]["task_id"]}
# message = json.dumps(data).encode('utf-8')
# funasr_service.handle_process(str(message))
gc.collect()
def consumer_process_error_callback(err):
log.error(f"consumer_process_error_callback:{err}")
gc.collect()
def start_kafka():
try:
kafka_thread = threading.Thread(target=funasr_consumer.consume_kafka)
kafka_thread.daemon = True # 将线程设置为守护线程,当主线程结束时,该线程也会自动结束
kafka_thread.start()
except Exception as e:
log.error("funasr start_kafka Exception: " + str(traceback.format_exc()))
if __name__ == "__main__":
log.info("funasr main starting...")
start_kafka()
funasr_producer.send_wait_task()
ap_scheduler_util.scheduler_start()
save_path = "audios/"
if os.path.exists(save_path):
shutil.rmtree(save_path)
parser = argparse.ArgumentParser()
parser.add_argument("--env", type=str, default="dev")
parser.add_argument("--test", type=str)
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=7888)
args = parser.parse_args()
# args = parser.parse_known_args()
uvicorn.run(
app="main:app",
host=args.host,
port=args.port,
workers=1,
ws_ping_interval=600,
ws_ping_timeout=600,
timeout_keep_alive=600,
)