test01.py 8.23 KB
# -*- coding: UTF-8 -*-
import json
import time
import traceback

from kafka import KafkaConsumer
import funasr_service
from mysql_service import funasr_db
from funasr import AutoModel
from datetime import datetime
import os

# 创建Kafka消费者
# consumer = KafkaConsumer(
#     "my-yang-topic",  # Kafka主题名称
#     bootstrap_servers="192.168.3.131:9092",  # Kafka集群的地址
#     group_id="my-yang-group",  # 消费者组ID
# )

# 循环消费消息
# for message in consumer:
#     # 从消息中获取键和值
#     key = message.key
#     value = message.value
#     print(f"Key: {key}, Value: {value}")

wav_root_url = "https://www.modelscope.cn/api/v1/models/dengcunqin/speech_seaco_paraformer_large_asr_nat-zh-cantonese-en-16k-common-vocab11666-pytorch/repo?Revision=master&FilePath="

desk_path = "C:\\Users\\chizw\\Desktop\\"

datas = ["C:\\Users\\chizw\\Desktop\\zhanggy202407100001.wav"]


def not_insert_run():
    for task_id in datas:
        out_put: str
        if task_id.find("/") != -1:
            output_res = funasr_service.FunasrService(task_id).transform()
        else:
            sql_res = funasr_db.select_ali_asr_model_res(task_id)
            url = sql_res[0]["file_url"]
            output_res = funasr_service.FunasrService(url).transform()
        print(f"output_res:{str(output_res)}")
        res = funasr_service.simple_transform_output(output_res[0]["sentence_info"])
        print(res)


def insert_run():
    for task_id in datas:
        funasr_service.deal_worker(task_id)


def run(url, name=None):
    now = datetime.now()
    if url is None:
        url = 'C:\\Users\\chizw\\Desktop\\zhanggy202407100001.wav'
    res = funasr_service.FunasrService(url).transform()
    # print(f"res:{str(res)}")
    print(f"url:{str(url)}")
    output = funasr_service.test_comparison_transform_output(res[0]["sentence_info"])
    # 格式化时间
    formatted_now = str(now.strftime('%Y-%m-%d_%H-%M-%S'))
    if name is None:
        basename, extension = os.path.splitext(os.path.basename(url))
        name = basename
    with open(f'../log/{name}_{formatted_now}.txt', 'w', encoding='utf-8') as file:
        for text in output:
            file.write("%s\n" % text)
    # print(f"sentence_info:{funasr_service.fine_grained_transform_output(res[0]['sentence_info'])}")


def test_paraformer():
    model = AutoModel(
        model="dengcunqin/speech_seaco_paraformer_large_asr_nat-zh-cantonese-en-16k-common-vocab11666-pytorch",
        model_revision="master"
    )

    res = model.generate(
        input="https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17161083134331716107368353.mp3",
        hotword=wav_root_url + "example/hotword.txt",
    )
    print(res)


def parse_file_to_dict(file_path):
    data_dict = {}
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                # 去除行尾的换行符
                line = line.strip()
                # 使用逗号分隔键和值
                parts = line.split(',', 1)
                if len(parts) == 2:
                    key, value = parts
                    data_dict[key.strip()] = value.strip()
                else:
                    print(f"警告: 行 '{line}' 未按逗号分隔,将跳过此行。")
    except FileNotFoundError:
        print(f"错误: 文件 '{file_path}' 未找到。")
    except Exception as e:
        print(f"错误: 读取文件时发生错误:{str(e)}")
    return data_dict


def read_files_in_directory(directory_path, dict):
    # 遍历目录及子目录中的所有文件
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                # 尝试打开文件并读取内容
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    file_name, extension = os.path.splitext(os.path.basename(file_path))
                    url = dict.get(file_name)
                    if url is None:
                        print(f"url不存在,file_name:{file_name}")
                        continue
                    funasr_db.insert_funasr_mock_data(file_name, url, content)
            except UnicodeDecodeError:
                print(f"警告: 文件 {file_path} 的编码不是 UTF-8,无法正确读取内容。")
            except Exception as e:
                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 > 160:
            speed = '过快'
        elif length > 140:
            speed = '适中'
        else:
            speed = '过慢'
        item["speed"] = speed
        item.pop("detail_json")
        # item.pop("recording_duration")
    time.sleep(3)
    with open("D:/software/python/project/funasr_web/audio.txt", 'w', encoding='utf-8') as file:
        for row in data:
            s = (
                # f"{row.get('id')};{row.get('recording_url')};{row.get('employee_name')};{row.get('car_model')};"
                # f"{row.get('bussiness_type')};{row.get('estimated_result')}"
                f"{row.get('id')}\t{row.get('recording_url')}\t{row.get('employee_name')}\t{row.get('car_model')}\t"
                f"{row.get('bussiness_type')}\t{row.get('estimated_result')}\t{row.get('speed')}\t{row.get('upgrade_goods_name')}\t"
                f"{row.get('score')}\t{row.get('sfjs')}\t{row.get('fwys')}\t{row.get('htjr')}\t{row.get('xqfx')}\t"
                f"{row.get('zyzs')}\t{row.get('cjsz')}\t{row.get('alzs')}\t{row.get('gfnl')}\t{row.get('bdnl')}"
                # f"{row.get('mon')}\t{row.get('id')}\t{row.get('recording_url')}\t{row.get('employee_name')}\t{row.get('car_model')}\t"
                # f"{row.get('bussiness_type')}\t{row.get('estimated_result')}"
                # f"\t{row.get('speed')}\t{row.get('recording_start_time')}\t"
            )
                # 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')}")
            print(s)
            # print(f"{row.get('merchant_name')}\t{row.get('employee_name')}\t{row.get('upgrade_goods_name')}\t{row.get('upgrade_goods_alias')}\t"
            #       f"{row.get('order_time')}\t{row.get('recording_url')}")
            # print(f"{row.get('speed')}")
            file.write(f"{s}\n")
            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"))

# run("https://smartcard-1253080096.cos.ap-guangzhou.myqcloud.com/audio/806599C6309C_1710219356_806599C6309C-1710219356.MP3",
#     "旧北京")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205808870541720579482995.mp3", "李丽")
# run("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/merged_17205827687271720580657722.mp3", "江门嘉钡")
# 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/车辆知识_保险基础知识培训-视频.mp3", "保险基础知识培训")

select_extract_data()