Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
eshiled-new
/
funasr_web
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 1d261528
authored
Jun 21, 2024
by
‘chizw’
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
[+]内存优化
1 parent
5cdb84b8
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
293 additions
and
27 deletions
funasr_service.py
test03.py
test04.py
funasr_service.py
View file @
1d26152
...
@@ -7,6 +7,7 @@ from log.logger import log
...
@@ -7,6 +7,7 @@ from log.logger import log
import
json
import
json
import
traceback
import
traceback
from
mysql_service
import
funasr_db
from
mysql_service
import
funasr_db
import
gc
# paraformer-zh is a multi-functional asr model
# paraformer-zh is a multi-functional asr model
# use vad, punc, spk or not as you need
# use vad, punc, spk or not as you need
...
@@ -32,7 +33,8 @@ model = AutoModel(
...
@@ -32,7 +33,8 @@ model = AutoModel(
punc_model_revision
=
"master"
,
punc_model_revision
=
"master"
,
spk_model_revision
=
"master"
,
spk_model_revision
=
"master"
,
# spk_model_revision="v2.0.2",
# spk_model_revision="v2.0.2",
ncpu
=
2
,
ncpu
=
4
,
ngpu
=
0
,
device
=
"cpu"
,
device
=
"cpu"
,
batch_size
=
1
,
batch_size
=
1
,
# model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
# model="iic/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
...
@@ -143,6 +145,8 @@ def deal_worker(task_id: str):
...
@@ -143,6 +145,8 @@ def deal_worker(task_id: str):
f
"Function create_upload_file executed in {execute_time} s"
f
"Function create_upload_file executed in {execute_time} s"
)
)
log
.
info
(
f
"Worker {task_id} finished."
)
log
.
info
(
f
"Worker {task_id} finished."
)
# 强制进行垃圾回收
gc
.
collect
()
except
Exception
as
e
:
except
Exception
as
e
:
log
.
error
(
f
"Worker error:{traceback.format_exc()}"
)
log
.
error
(
f
"Worker error:{traceback.format_exc()}"
)
funasr_db
.
update_ali_asr_model_res_fail
(
task_id
,
str
(
e
),
traceback
.
format_exc
())
funasr_db
.
update_ali_asr_model_res_fail
(
task_id
,
str
(
e
),
traceback
.
format_exc
())
...
...
test03.py
View file @
1d26152
# 版本要求 modelscope 升级至最新版本 funasr升级至最新版本
import
argparse
from
modelscope.pipelines
import
pipeline
import
logging
import
os
sd_pipeline
=
pipeline
(
import
uuid
task
=
"speaker-diarization"
,
import
gc
model
=
"damo/speech_eres2net-large_speaker-diarization_common"
,
model_revision
=
"v1.0.0"
,
import
aiofiles
)
import
ffmpeg
input_wav
=
"https://modelscope.cn/api/v1/models/damo/speech_campplus_speaker-diarization_common/repo?Revision=master&FilePath=examples/2speakers_example.wav"
import
uvicorn
result
=
sd_pipeline
(
input_wav
)
from
fastapi
import
FastAPI
,
File
,
UploadFile
print
(
result
)
from
modelscope.utils.logger
import
get_logger
# 如果有先验信息,输入实际的说话人数,会得到更准确的预测结果
result
=
sd_pipeline
(
input_wav
,
oracle_num
=
2
)
from
funasr
import
AutoModel
print
(
result
)
# from itn.chinese.inverse_normalizer import InverseNormalizer
logger
=
get_logger
(
log_level
=
logging
.
INFO
)
logger
.
setLevel
(
logging
.
INFO
)
parser
=
argparse
.
ArgumentParser
()
parser
.
add_argument
(
"--host"
,
type
=
str
,
default
=
"0.0.0.0"
,
required
=
False
,
help
=
"host ip, localhost, 0.0.0.0"
)
parser
.
add_argument
(
"--port"
,
type
=
int
,
default
=
8000
,
required
=
False
,
help
=
"server port"
)
parser
.
add_argument
(
"--asr_model"
,
type
=
str
,
# default="paraformer-zh",
default
=
"/soft/FunASR/model/speech_paraformer-large-vad-punc-spk_asr_nat-zh-cn"
,
help
=
"asr model from https://github.com/alibaba-damo-academy/FunASR?tab=readme-ov-file#model-zoo"
,
)
parser
.
add_argument
(
"--asr_model_revision"
,
type
=
str
,
default
=
"v2.0.4"
,
help
=
""
)
parser
.
add_argument
(
"--vad_model"
,
type
=
str
,
# default="fsmn-vad",
default
=
"/soft/FunASR/model/speech_fsmn_vad_zh-cn-16k-common-pytorch/"
,
help
=
"vad model from https://github.com/alibaba-damo-academy/FunASR?tab=readme-ov-file#model-zoo"
,
)
parser
.
add_argument
(
"--vad_model_revision"
,
type
=
str
,
default
=
"v2.0.4"
,
help
=
""
)
parser
.
add_argument
(
"--punc_model"
,
type
=
str
,
# default="ct-punc-c",
default
=
"/soft/FunASR/model/punc_ct-transformer_cn-en-common-vocab471067-large/"
,
help
=
"model from https://github.com/alibaba-damo-academy/FunASR?tab=readme-ov-file#model-zoo"
,
)
parser
.
add_argument
(
"--punc_model_revision"
,
type
=
str
,
default
=
"v2.0.4"
,
help
=
""
)
# 说话人识别/分割
parser
.
add_argument
(
"--spk_model_revision"
,
type
=
str
,
default
=
"v2.0.4"
,
help
=
""
)
parser
.
add_argument
(
"--spk_model"
,
type
=
str
,
# default="cam++",
default
=
"/soft/FunASR/model/speech_campplus_sv_zh-cn_16k-common/"
,
help
=
"model from https://github.com/alibaba-damo-academy/FunASR?tab=readme-ov-file#model-zoo"
,
)
parser
.
add_argument
(
"--ngpu"
,
type
=
int
,
default
=
0
,
help
=
"0 for cpu, 1 for gpu"
)
parser
.
add_argument
(
"--device"
,
type
=
str
,
default
=
"cpu"
,
help
=
"cuda, cpu"
)
parser
.
add_argument
(
"--ncpu"
,
type
=
int
,
default
=
4
,
help
=
"cpu cores"
)
parser
.
add_argument
(
"--hotword_path"
,
type
=
str
,
default
=
"hotwords.txt"
,
help
=
"hot word txt path, only the hot word model works"
,
)
parser
.
add_argument
(
"--certfile"
,
type
=
str
,
default
=
None
,
required
=
False
,
help
=
"certfile for ssl"
)
parser
.
add_argument
(
"--keyfile"
,
type
=
str
,
default
=
None
,
required
=
False
,
help
=
"keyfile for ssl"
)
parser
.
add_argument
(
"--temp_dir"
,
type
=
str
,
default
=
"temp_dir/"
,
required
=
False
,
help
=
"temp dir"
)
args
=
parser
.
parse_args
()
logger
.
info
(
"----------- Configuration Arguments -----------"
)
for
arg
,
value
in
vars
(
args
)
.
items
():
logger
.
info
(
"
%
s:
%
s"
%
(
arg
,
value
))
logger
.
info
(
"------------------------------------------------"
)
os
.
makedirs
(
args
.
temp_dir
,
exist_ok
=
True
)
logger
.
info
(
"model loading"
)
# load funasr model
model
=
AutoModel
(
model
=
args
.
asr_model
,
model_revision
=
args
.
asr_model_revision
,
vad_model
=
args
.
vad_model
,
vad_model_revision
=
args
.
vad_model_revision
,
punc_model
=
args
.
punc_model
,
punc_model_revision
=
args
.
punc_model_revision
,
spk_model
=
args
.
spk_model
,
spk_model_revision
=
args
.
spk_model_revision
,
ngpu
=
args
.
ngpu
,
ncpu
=
args
.
ncpu
,
device
=
args
.
device
,
disable_pbar
=
True
,
disable_log
=
True
,
)
logger
.
info
(
"loaded models!"
)
app
=
FastAPI
(
title
=
"FunASR"
)
param_dict
=
{
"sentence_timestamp"
:
False
,
"batch_size_s"
:
50
}
if
args
.
hotword_path
is
not
None
and
os
.
path
.
exists
(
args
.
hotword_path
):
with
open
(
args
.
hotword_path
,
"r"
,
encoding
=
"utf-8"
)
as
f
:
lines
=
f
.
readlines
()
lines
=
[
line
.
strip
()
for
line
in
lines
]
hotword
=
" "
.
join
(
lines
)
logger
.
info
(
f
"热词:{hotword}"
)
param_dict
[
"hotword"
]
=
hotword
@app.post
(
"/recognition"
)
async
def
api_recognition
(
audio
:
UploadFile
=
File
(
...
,
description
=
"audio file"
)):
suffix
=
audio
.
filename
.
split
(
"."
)[
-
1
]
audio_path
=
f
"{args.temp_dir}/{str(uuid.uuid1())}.{suffix}"
async
with
aiofiles
.
open
(
audio_path
,
"wb"
)
as
out_file
:
content
=
await
audio
.
read
()
await
out_file
.
write
(
content
)
try
:
audio_bytes
,
_
=
(
ffmpeg
.
input
(
audio_path
,
threads
=
0
)
.
output
(
"-"
,
format
=
"s16le"
,
acodec
=
"pcm_s16le"
,
ac
=
1
,
ar
=
16000
)
.
run
(
cmd
=
[
"ffmpeg"
,
"-nostdin"
],
capture_stdout
=
True
,
capture_stderr
=
True
)
)
except
Exception
as
e
:
logger
.
error
(
f
"读取音频文件发生错误,错误信息:{e}"
)
return
{
"msg"
:
"读取音频文件发生错误"
,
"code"
:
1
}
rec_results
=
model
.
generate
(
input
=
audio_bytes
,
is_final
=
True
,
**
param_dict
)
logger
.
error
(
f
"识别结果rec_results:{rec_results}"
)
# 结果为空
if
len
(
rec_results
)
==
0
:
return
{
"text"
:
""
,
"sentences"
:
[],
"code"
:
0
}
elif
len
(
rec_results
)
==
1
:
# 解析识别结果
rec_result
=
rec_results
[
0
]
# text = rec_result["text"]
# 文本逆正则化
# invnormalizer = InverseNormalizer(cache_dir="/soft/FunASR/model/fst_itn_zh/")
# text = invnormalizer.normalize(rec_result["text"])
text
=
rec_result
[
"text"
]
sentences
=
[]
for
sentence
in
rec_result
[
"sentence_info"
]:
# 每句话的时间戳
sentences
.
append
(
{
"spk"
:
sentence
[
"spk"
],
# "text": invnormalizer.normalize(sentence["text"]),
"text"
:
sentence
[
"text"
],
"start"
:
sentence
[
"start"
],
"end"
:
sentence
[
"end"
]}
)
ret
=
{
"text"
:
text
,
"sentences"
:
sentences
,
"code"
:
0
}
logger
.
info
(
f
"识别结果:{ret}"
)
# 强制进行垃圾回收
gc
.
collect
()
return
ret
else
:
logger
.
info
(
f
"识别结果:{rec_results}"
)
return
{
"msg"
:
"未知错误"
,
"code"
:
-
1
}
if
__name__
==
"__main__"
:
uvicorn
.
run
(
app
,
host
=
args
.
host
,
port
=
args
.
port
,
ssl_keyfile
=
args
.
keyfile
,
ssl_certfile
=
args
.
certfile
)
test04.py
View file @
1d26152
# 版本要求 modelscope version 升级至最新版本 funasr 升级至最新版本
import
argparse
from
modelscope.pipelines
import
pipeline
from
funasr
import
AutoModel
import
traceback
import
os
import
shutil
import
uuid
import
pydantic
import
uvicorn
import
json
from
fastapi
import
FastAPI
,
File
,
UploadFile
from
pydantic
import
BaseModel
from
log.logger
import
log
from
kafka
import
KafkaConsumer
sd_pipeline
=
pipeline
(
app
=
FastAPI
()
task
=
"speaker-diarization"
,
model
=
"damo/speech_campplus_speaker-diarization_common"
,
consumer_new
=
KafkaConsumer
(
model_revision
=
"v1.0.0"
,
# ConfigInfo.kafka_consumer_analysis_topic,
# bootstrap_servers=ConfigInfo.kafka_consumer_bootstrap_servers, # Kafka broker 的地址
# group_id=ConfigInfo.kafka_consumer_group_id, # 消费者组 ID
# auto_offset_reset=ConfigInfo.kafka_consumer_auto_offset_reset, # 从最早的消息开始消费
)
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
UrlParam
(
BaseModel
):
url
:
str
model
=
AutoModel
(
model
=
"iic/speech_seaco_paraformer_large_asr_nat-zh-cn-16k-common-vocab8404-pytorch"
,
vad_model
=
"fsmn-vad"
,
punc_model
=
"ct-punc-c"
,
spk_model
=
"cam++"
,
ncpu
=
2
,
ngpu
=
0
,
device
=
"cpu"
,
batch_size
=
1
,
)
)
input_wav
=
"https://modelscope.cn/api/v1/models/damo/speech_campplus_speaker-diarization_common/repo?Revision=master&FilePath=examples/2speakers_example.wav"
def
handle_process
(
message
:
str
):
result
=
sd_pipeline
(
input_wav
)
try
:
print
(
result
)
# 如果有先验信息,输入实际的说话人数,会得到更准确的预测结果
task_id
=
json
.
loads
(
message
)[
"task_id"
]
result
=
sd_pipeline
(
input_wav
,
oracle_num
=
2
)
# url = select_db(task_id) 查询数据库url todo
print
(
result
)
url
=
"https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17177345226501717730109711.mp3"
# 解析音频
output_res
=
model
.
generate
(
input
=
url
,
batch_size_s
=
1
,
batch_size_threshold_s
=
60
*
60
,
hotword
=
""
)
# update_db(task_id,output_res) 更新数据库 todo
except
Exception
as
e
:
log
.
error
(
"funasr handle_process Exception: "
+
str
(
traceback
.
format_exc
()))
@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"
)
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
())
# insert_db(task_id,url) 插入数据库 todo
# task_id推送kafka todo
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
)
)
if
__name__
==
"__main__"
:
log
.
info
(
"funasr main starting..."
)
save_path
=
"./audio/"
if
os
.
path
.
exists
(
save_path
):
shutil
.
rmtree
(
save_path
)
parser
=
argparse
.
ArgumentParser
()
parser
.
add_argument
(
"--env"
,
type
=
str
,
default
=
"dev"
)
parser
.
add_argument
(
"--host"
,
type
=
str
,
default
=
"0.0.0.0"
)
parser
.
add_argument
(
"--port"
,
type
=
int
,
default
=
7888
)
args
=
parser
.
parse_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
,
)
def
consume_kafka
():
# kafka消费消息并进行逻辑处理
try
:
for
message
in
consumer_new
:
if
message
is
None
:
continue
log
.
info
(
f
"Received message: {message}"
)
# 处理逻辑
handle_process
(
str
(
message
.
value
.
decode
(
'utf-8'
)))
print
(
"task handle"
)
except
Exception
as
e
:
log
.
error
(
"funasr consumer Exception: "
+
str
(
traceback
.
format_exc
()))
\ No newline at end of file
\ No newline at end of file
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment