main.py 16.8 KB
# -*- coding: UTF-8 -*-
import argparse
import multiprocessing  # 多进程支持
import traceback  # 异常堆栈打印
import funasr_service
from kafka_service import funasr_producer
import os  # 文件/目录操作
import random  # 随机数生成
import shutil  # 目录/文件删除与复制
import threading
import time  # 计时与时间函数
import uuid  # 生成唯一任务 ID
import pydantic  # 数据模型校验
import uvicorn  # ASGI 服务器
import sys  # 解释器与路径控制
from utils import ap_scheduler_util  # APScheduler 定时任务工具
from fastapi import FastAPI, File, UploadFile
from contextlib import asynccontextmanager
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
from config.config import ConfigInfo
import json

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()  # 创建 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:  # pydantic 配置示例
        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"  # 返回 .wav 文件名


@app.get("/")  # 根接口(健康检查)
def hello_world():  # 返回 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),
    )


_startup_once_lock = threading.Lock()
_startup_once_called = False

def startup_once():
    global _startup_once_called
    if _startup_once_called:
        return
    with _startup_once_lock:
        if _startup_once_called:
            return
        log.info("重启后扫描一次处理中的任务,重新去处理")
        ap_scheduler_util.transform_file_for3()
        _startup_once_called = True

@asynccontextmanager
async def lifespan(app: FastAPI):
    threading.Timer(0.5, startup_once).start()
    yield
app.router.lifespan_context = lifespan


@app.post("/funasr/file/")  # 上传字节流音频并转写
async def create_file(file: bytes = File()):  # 接收原始字节流
    # 获取文件内容  # 已由 FastAPI 注入到参数
    # 打开文件以写入模式  # 保存到本地再处理
    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):  # 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:  # 二进制写入
            # 将接收到的文件内容写入文件中  # 以 1KB 分块读取写入
            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 请求体模型
    url: str  # 音频文件地址

@app.get("/funasr/start/scheduler")  # 通过 URL 创建转写任务
async def create_url():
    try:
        ap_scheduler_util.transform_file()
        return BaseResponse(
            code=200,
            msg="success",
            data={}
        )
    except Exception as e:  # 异常捕获
        log.error(f"error:{traceback.format_exc()}")  # 输出堆栈
        return BaseResponse(
            code=-1,
            msg="error",
            data=str(e)
        )
@app.post("/funasr/url/add")  # 通过 URL 创建转写任务
async def create_url(param: UrlParam):  # 接收 URL 参数
    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())  # 生成任务 ID
        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="数据库异常"
            )
        log.info(f"funasr create_url api task_id:{task_id}")  # 记录任务 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)
        )


@app.post("/funasr/url/")  # 通过 URL 创建转写任务
async def create_url(param: UrlParam):  # 接收 URL 参数
    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())  # 生成任务 ID
        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="数据库异常"
            )
        log.info(f"funasr create_url api task_id:{task_id}")  # 记录任务 ID
        data = {"task_id": task_id}
        message = json.dumps(data).encode('utf-8')
        funasr_service.handle_process(message)  # 处理任务
        # funasr_producer.send_message_analysis({"task_id": task_id})  # 发送 Kafka 分析消息
        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()  # 手动 GC


def consumer_process_error_callback(err):  # 进程池失败回调
    log.error(f"consumer_process_error_callback:{err}")  # 打印错误
    gc.collect()  # 手动 GC

def start_kafka():  # 启动 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()
    ap_scheduler_util.scheduler1_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,
        log_level="debug"
    )