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 ebb9e00f
authored
Dec 19, 2024
by
‘chizw’
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
[+]进程优化
1 parent
87664ef3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
149 additions
and
36 deletions
kafka_service/simple_consumer.py
main.py
utils/ap_scheduler_util.py
kafka_service/simple_consumer.py
0 → 100644
View file @
ebb9e00
import
json
import
multiprocessing
import
threading
import
time
import
traceback
from
kafka
import
KafkaConsumer
from
log.logger
import
log
from
config.config
import
ConfigInfo
import
gc
# 配置 Kafka 消费者
consumer_new
=
KafkaConsumer
(
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
,
# 从最早的消息开始消费
connections_max_idle_ms
=
5000000
,
request_timeout_ms
=
4000000
,
fetch_max_wait_ms
=
300000
,
)
log
.
info
(
"启动2"
)
# 循环消费消息
def
consume_kafka
():
log
.
info
(
f
"启动consume_kafka Thread name:{threading.current_thread().name}"
)
# 消费消息并进行逻辑处理
try
:
# 先创建进程池,只复制当前资源
# multiprocessing.set_start_method('spawn')
process_pool
=
multiprocessing
.
Pool
(
processes
=
2
,
initializer
=
consumer_process_init
)
# m = multiprocessing.Manager()
# q = m.JoinableQueue()
# # 加载大内存变量
# larg_mem = np.random.normal(1.0, 0.1, 10000000)
# 使用`psutil`库或内置的`sys.getsizeof()`函数实时监控内存使用情况,及时发现异常。
for
message
in
consumer_new
:
if
message
is
None
:
continue
log
.
info
(
f
"Received message: {message}"
)
# 处理逻辑
# funasr_service.handle_process(str(message.value.decode('utf-8')))
arg
=
str
(
message
.
value
.
decode
(
'utf-8'
))
log
.
info
(
f
"arg:{arg},process_pool1:{process_pool}"
)
# print(list((tqdm(p.imap(f, range(10)), total=10, desc='监视进度'))))
process_pool
.
apply_async
(
func
=
handle_process
,
args
=
(
arg
,),
callback
=
consumer_process_callback
,
error_callback
=
consumer_process_error_callback
)
# process = multiprocessing.Process(target=funasr_service.handle_process, args=((str(message.value.decode('utf-8'))),),)
# process.start()
print
(
"task handle"
)
# process_pool.close()
# process_pool.join()
except
Exception
as
e
:
log
.
error
(
"funasr consumer Exception: "
+
str
(
traceback
.
format_exc
()))
def
handle_process
(
message
:
str
):
import
funasr_service
try
:
process
=
multiprocessing
.
current_process
()
log
.
info
(
f
"handle_process_start process:{process},thread name:{threading.current_thread().name},"
f
"Received task_id: {message}"
)
# 处理逻辑
start_time
=
time
.
time
()
task_id
=
json
.
loads
(
message
)[
"task_id"
]
funasr_service
.
deal_worker
(
task_id
)
log
.
info
(
f
"handle_process_end process:{process} task_id:{task_id} 耗时:"
+
str
(
time
.
time
()
-
start_time
))
except
Exception
as
e
:
log
.
error
(
"funasr handle_process Exception: "
+
str
(
traceback
.
format_exc
()))
# 循环消费消息
# for message in consumer:
# log.info(f"Received message: {message.value}")
# if message is None:
# continue
# funasr_service.handle_process(str(message.value.decode('utf-8')))
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
()
main.py
View file @
ebb9e00
...
@@ -14,10 +14,10 @@ import uvicorn
...
@@ -14,10 +14,10 @@ import uvicorn
import
sys
import
sys
from
utils
import
ap_scheduler_util
from
utils
import
ap_scheduler_util
from
fastapi
import
FastAPI
,
File
,
UploadFile
from
fastapi
import
FastAPI
,
File
,
UploadFile
from
funasr_service
import
FunasrService
from
pydantic
import
BaseModel
from
pydantic
import
BaseModel
from
mysql_service
import
funasr_db
from
mysql_service
import
funasr_db
from
kafka_service
import
funasr_consumer
from
kafka_service
import
funasr_consumer
from
kafka_service
import
simple_consumer
import
gc
import
gc
current_dir
=
os
.
path
.
dirname
(
os
.
path
.
abspath
(
__file__
))
current_dir
=
os
.
path
.
dirname
(
os
.
path
.
abspath
(
__file__
))
...
@@ -29,6 +29,44 @@ from log.logger import log
...
@@ -29,6 +29,44 @@ from log.logger import log
app
=
FastAPI
()
app
=
FastAPI
()
def
start_kafka
():
try
:
kafka_thread
=
threading
.
Thread
(
target
=
simple_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
)
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
,
)
from
funasr_service
import
FunasrService
class
BaseResponse
(
BaseModel
):
class
BaseResponse
(
BaseModel
):
code
:
int
=
pydantic
.
Field
(
200
,
description
=
"HTTP status code"
)
code
:
int
=
pydantic
.
Field
(
200
,
description
=
"HTTP status code"
)
msg
:
str
=
pydantic
.
Field
(
"success"
,
description
=
"HTTP status message"
)
msg
:
str
=
pydantic
.
Field
(
"success"
,
description
=
"HTTP status message"
)
...
@@ -224,15 +262,6 @@ async def create_url(param: UrlParam):
...
@@ -224,15 +262,6 @@ async def create_url(param: UrlParam):
)
)
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
()))
def
start_process
():
def
start_process
():
process
=
multiprocessing
.
Process
(
target
=
funasr_consumer
.
consume_kafka
,
)
process
=
multiprocessing
.
Process
(
target
=
funasr_consumer
.
consume_kafka
,
)
log
.
info
(
f
"process:{process}"
)
log
.
info
(
f
"process:{process}"
)
...
@@ -279,27 +308,3 @@ def consumer_process_error_callback(err):
...
@@ -279,27 +308,3 @@ def consumer_process_error_callback(err):
log
.
error
(
f
"consumer_process_error_callback:{err}"
)
log
.
error
(
f
"consumer_process_error_callback:{err}"
)
gc
.
collect
()
gc
.
collect
()
if
__name__
==
"__main__"
:
log
.
info
(
"funasr main starting..."
)
funasr_producer
.
send_wait_task
()
ap_scheduler_util
.
scheduler_start
()
start_process_kafka
()
save_path
=
"audios/"
if
os
.
path
.
exists
(
save_path
):
shutil
.
rmtree
(
save_path
)
parser
=
argparse
.
ArgumentParser
()
parser
.
add_argument
(
"--env"
,
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
,
)
utils/ap_scheduler_util.py
View file @
ebb9e00
import
datetime
import
datetime
import
time
import
time
import
traceback
import
traceback
import
funasr_service
from
apscheduler.schedulers.blocking
import
BlockingScheduler
from
apscheduler.schedulers.blocking
import
BlockingScheduler
from
apscheduler.schedulers.background
import
BackgroundScheduler
from
apscheduler.schedulers.background
import
BackgroundScheduler
from
apscheduler.jobstores.memory
import
MemoryJobStore
from
apscheduler.jobstores.memory
import
MemoryJobStore
...
@@ -28,6 +26,7 @@ def job_func():
...
@@ -28,6 +26,7 @@ def job_func():
print
(
datetime
.
datetime
.
utcnow
()
.
strftime
(
"
%
Y-
%
m-
%
d
%
H:
%
M:
%
S.
%
f"
)[:
-
3
])
print
(
datetime
.
datetime
.
utcnow
()
.
strftime
(
"
%
Y-
%
m-
%
d
%
H:
%
M:
%
S.
%
f"
)[:
-
3
])
def
scheduler_start
():
def
scheduler_start
():
import
funasr_service
log
.
info
(
"scheduler_starting..."
)
log
.
info
(
"scheduler_starting..."
)
try
:
try
:
scheduler
=
BackgroundScheduler
(
executors
=
executors
,
job_defaults
=
job_defaults
)
scheduler
=
BackgroundScheduler
(
executors
=
executors
,
job_defaults
=
job_defaults
)
...
...
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