Commit d092d6e8 by ‘chizw’

[+]进程优化

1 parent 6b44354b
# 版本要求 modelscope version 升级至最新版本 funasr 升级至最新版本
from modelscope.pipelines import pipeline
# # 版本要求 modelscope version 升级至最新版本 funasr 升级至最新版本
# from modelscope.pipelines import pipeline
#
# sd_pipeline = pipeline(
# task="speaker-diarization",
# model="damo/speech_campplus_speaker-diarization_common",
# model_revision="v1.0.0",
# )
# input_wav = "https://modelscope.cn/api/v1/models/damo/speech_campplus_speaker-diarization_common/repo?Revision=master&FilePath=examples/2speakers_example.wav"
# result = sd_pipeline(input_wav)
# print(result)
# # 如果有先验信息,输入实际的说话人数,会得到更准确的预测结果
# result = sd_pipeline(input_wav, oracle_num=2)
# print(result)
sd_pipeline = pipeline(
task="speaker-diarization",
model="damo/speech_campplus_speaker-diarization_common",
model_revision="v1.0.0",
)
input_wav = "https://modelscope.cn/api/v1/models/damo/speech_campplus_speaker-diarization_common/repo?Revision=master&FilePath=examples/2speakers_example.wav"
result = sd_pipeline(input_wav)
print(result)
# 如果有先验信息,输入实际的说话人数,会得到更准确的预测结果
result = sd_pipeline(input_wav, oracle_num=2)
print(result)
from funasr import AutoModel
# paraformer-zh is a multi-functional asr model
# use vad, punc, spk or not as you need
model = AutoModel(model="paraformer-zh", vad_model="fsmn-vad", punc_model="ct-punc",disable_update=True
# spk_model="cam++"
)
res = model.generate(input=f"https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17342448514462266_1734241564204212.mp3",
batch_size_s=300,
hotword='魔搭')
print(res)
......@@ -10,9 +10,9 @@ from config.config import ConfigInfo
from concurrent.futures import ThreadPoolExecutor
from kafka.structs import TopicPartition
from tqdm import tqdm
from mysql_service import funasr_db
import numpy as np
import gc
from concurrent.futures import ProcessPoolExecutor, as_completed, wait, FIRST_COMPLETED
# 配置 Kafka 消费者
consumer_new = KafkaConsumer(
......@@ -83,7 +83,7 @@ def consume_kafka():
try:
# 先创建进程池,只复制当前资源
# multiprocessing.set_start_method('spawn')
process_pool = multiprocessing.Pool(processes=3, initializer=consumer_process_init)
process_pool = multiprocessing.Pool(processes=1, initializer=consumer_process_init)
# m = multiprocessing.Manager()
# q = m.JoinableQueue()
# # 加载大内存变量
......@@ -101,14 +101,61 @@ def consume_kafka():
process_pool.apply_async(func=funasr_service.handle_process, args=(arg,),
callback=consumer_process_callback,
error_callback=consumer_process_error_callback)
children = process_pool.active_children()
log.info(f"children:{children}")
# process = multiprocessing.Process(target=funasr_service.handle_process, args=((str(message.value.decode('utf-8'))),),)
# process.start()
print("task handle")
log.info("task handle")
# process_pool.close()
# process_pool.join()
except Exception as e:
log.error("funasr consumer Exception: " + str(traceback.format_exc()))
def handle_message(message, executor):
try:
arg = str(message.value.decode('utf-8'))
log.info(f"arg:{arg}, processing message in thread: {threading.current_thread().name}")
future = executor.submit(funasr_service.handle_process, arg)
return future
except Exception as e:
log.error("funasr consumer Exception: " + str(traceback.format_exc()))
raise
def consume_kafka_in_multiprocess():
log.info(f"启动consume_kafka Thread name:{threading.current_thread().name}")
# 消费消息并进行逻辑处理
try:
max_workers = 3
with ProcessPoolExecutor(max_workers=max_workers, initializer=consumer_process_init) as executor:
futures = []
for message in consumer_new:
if message is None:
continue
log.info(f"Received message: {message}")
future = handle_message(message, executor)
if future:
futures.append(future)
# 确保我们不会积压过多的任务
if len(futures) >= max_workers * 2:
# 等待最早的几个任务完成
done, futures = wait(futures, return_when=FIRST_COMPLETED)
for fut in done:
try:
result = fut.result()
consumer_process_callback(result)
except Exception as exc:
consumer_process_error_callback(exc)
# 等待所有任务完成
for future in as_completed(futures):
try:
result = future.result()
consumer_process_callback(result)
except Exception as exc:
consumer_process_error_callback(exc)
except Exception as e:
log.error("funasr consumer Exception: " + str(traceback.format_exc()))
# 循环消费消息
# for message in consumer:
......
# -*- coding: UTF-8 -*-
import json
import time
import traceback
from kafka import KafkaConsumer
......@@ -123,6 +124,46 @@ def read_files_in_directory(directory_path, dict):
print(f"错误: 无法读取文件 {file_path},原因:{str(e)}")
def select_extract_data():
data = funasr_db.select_extract_data()
for item in data:
length = 0
duration = 0
content = 0
detail_json = item.get("detail_json")
if detail_json is not None:
try:
detail = json.loads(detail_json)
role = detail[0].get("role")
for json_data in detail:
if json_data.get("role") == role:
content += len(json_data.get("content", ""))
duration += int(json_data.get('duration'))
except:
print(item.get("id"))
traceback.print_exc()
if duration != 0:
length = content / (duration / (60 * 1000))
if length > 210:
speed = '急速'
elif length > 180:
speed = '快速'
elif length > 150:
speed = '适中'
elif length > 120:
speed = '缓慢'
else:
speed = '极慢'
item["speed"] = speed
item.pop("detail_json")
item.pop("recording_duration")
time.sleep(3)
for row in data:
print(f"{row.get('id')}\t{row.get('employee_name')}\t{row.get('car_model')}\t"
f"{row.get('bussiness_type')}\t{row.get('estimated_result')}\t{row.get('product')}\t{row.get('speed')}")
pass
return data
# read_files_in_directory("D:/software/python/project/funasr_web/log/output/0910",
# parse_file_to_dict("D:/software/python/project/funasr_web/log/all.txt"))
......@@ -133,5 +174,4 @@ def read_files_in_directory(directory_path, dict):
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17212740566661721272782874.mp3", "曹俊")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_172075478615417207538825792.mp3", "东联")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_172119302897717211886442290.mp3", "李钰达")
run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205900068901720588971648.mp3", "张东华")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205900068901720588971648.mp3", "张东华")
......@@ -184,3 +184,34 @@ def update_tingwu_ask_res_asr_text(task_id: str, asr_text: str):
f"""UPDATE tingwu_ask_res SET asr_text = %s WHERE task_id = %s;"""
)
return pool.select_all(sql, (asr_text, task_id))
def select_extract_data():
sql = (
f"""
select ibr.id,t3.employee_name,rci.car_model,
case when rci.bussiness_type = 1 then '会员权益/升级' when ibr.check_type = 2 then '轻改' end bussiness_type,
if(t4.customer_phone is not null,'成交','未成交') as estimated_result,
case when rbmca.Is_mentioned = 1 then '安心包' else '大套餐' end product,
icde.detail_json,ibr.recording_duration
from inspection_badge_recordings ibr
left join reception_customer_info rci on rci.id =ibr.reception_id
left join inspection_employee_badge t3 on ibr.badge_id =t3.badge_id
LEFT JOIN inspection_conversation_batch icb ON icb.file_url = ibr.recording_url
left join recording_batch_model_call_axb rbmca on icb.id = rbmca.batch_id
left join inspection_conversation_detail_ext icde on icb.id = icde.batch_id
left join ( select
dclgoc.customer_phone,upgrade_goods_name,upgrade_goods_alias,dclgso.package_name
from dj_car_life_goods_order dclgo
left join dj_car_life_goods_sub_order dclgso
on dclgo.order_code = dclgso.order_code and dclgso.deleted_flag = 'N'
left join dj_car_life_goods_order_customer dclgoc
on dclgoc.order_code = dclgo.order_code and dclgoc.deleted_flag = 'N'
left join dj_car_life_pay_order dclpo on dclpo.order_code = dclgo.order_code and dclpo.deleted_flag = 'N'
where dclgo.deleted_flag = 'N' and dclgo.scene_type = 0
and dclgo.status in (4, 6) and upgrade_flag = 'Y'
group by dclgoc.customer_phone
order by order_time desc) t4 on rci.phone_number =t4.customer_phone
where recording_start_time BETWEEN %s AND %s;"""
)
return pool.select_all(sql, ('2024-12-16', '2024-12-23'))
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!