优化人工接管功能

main
fanpt 7 days ago
parent b223e9f03c
commit d798fbbcc7

@ -1,54 +1,24 @@
from datetime import datetime
from fastapi import FastAPI from fastapi import FastAPI
from pydantic import BaseModel from pydantic import BaseModel
from loguru import logger
app = FastAPI(title="直播状态控制接口") app = FastAPI(title="直播接管控制接口")
app.shared_config = None
class SpeakingStatus(BaseModel):
is_speaking: bool
@app.post("/speaking-status", summary="更新说话状态")
def update_speaking_status(status: SpeakingStatus):
if app.shared_config is None:
return {"error": "服务未初始化"}
prev = app.shared_config.get("is_speaking", False) # 由 main.py 在启动前注入app.state.shared_config = <Manager().dict(...)>
app.shared_config["is_speaking"] = status.is_speaking app.shared_config = None
# 当状态从 True 变为 False 的瞬间,取出预测队列并计算差值
if (not status.is_speaking) and prev:
now_dt = datetime.now()
now_str = now_dt.strftime("%Y-%m-%d %H:%M:%S")
app.shared_config["speaking_false_time"] = now_str
predicted_time_str = None
try:
q = app.shared_config.get("prediction_queue")
if q is not None and len(q) > 0:
predicted_time_str = q.pop(0)
except Exception:
predicted_time_str = None
app.shared_config["predicted_time"] = predicted_time_str class ControlMode(BaseModel):
control_mode: int # 0=手动接管, 1=AI接管
# 打印日志
if predicted_time_str:
try:
predicted_dt = datetime.strptime(predicted_time_str, "%Y-%m-%d %H:%M:%S")
delta_seconds = (now_dt - predicted_dt).total_seconds()
app.shared_config["time_diff_seconds"] = float(delta_seconds)
logger.info(
f"[计算差值] 队列剩余: {list(app.shared_config.get('prediction_queue', []))} | "
f"真实时间: {now_str} | 使用预测: {predicted_time_str} | 差值(秒): {delta_seconds}"
)
except Exception:
app.shared_config["time_diff_seconds"] = None
else:
app.shared_config["time_diff_seconds"] = None
logger.warning(
f"[计算差值] 队列为空或解析失败 | 真实时间: {now_str}"
)
return {"message": "状态更新成功"} @app.post("/control-mode", summary="更新直播间接管模式")
def update_control_mode(mode: ControlMode):
if app.shared_config is None:
return {"error": "服务未初始化"}
app.shared_config["control_mode"] = mode.control_mode
return {
"message": "模式更新成功",
"current_status": {
"control_mode": app.shared_config["control_mode"], # 0=手动, 1=AI
},
}

@ -422,7 +422,7 @@ class DouyinLiveWebReply:
:param text: 文本 :param text: 文本
:return: 耗时 单位秒 :return: 耗时 单位秒
""" """
return len(text)/4.5 return len(text)/4.6
def __call__(self): def __call__(self):
""" """
@ -440,7 +440,8 @@ class DouyinLiveWebReply:
try: try:
# next_to_human_call_time大于当前时间立即调用 # next_to_human_call_time大于当前时间立即调用
call_immediate = next_to_human_call_time is None or time.time() >= next_to_human_call_time call_immediate = next_to_human_call_time is None or time.time() >= next_to_human_call_time
if not call_immediate:
if not call_immediate or self.config['control_mode'] == 0:
prompt_data = self.queue.get(False) prompt_data = self.queue.get(False)
if prompt_data is not None: if prompt_data is not None:
product_name, product_specification, product_description = self.live_chat_config.product_info product_name, product_specification, product_description = self.live_chat_config.product_info
@ -531,11 +532,13 @@ class DouyinLiveWebReply:
self.live_chat_config.flush_precedence_reply_message() self.live_chat_config.flush_precedence_reply_message()
logger.info(f"开始播放系统文案:{reply_message}") logger.info(f"开始播放系统文案:{reply_message}")
cost = self.text_to_adio_cost_predict(reply_message) cost = self.text_to_adio_cost_predict(reply_message)
# logger.info(f'文本:{reply_message}预计算出的语音时长:{cost}秒')
next_to_human_call_time = time.time() + cost next_to_human_call_time = time.time() + cost
formatted_time = datetime.fromtimestamp(next_to_human_call_time).strftime("%Y-%m-%d %H:%M:%S") formatted_time = datetime.fromtimestamp(next_to_human_call_time).strftime("%Y-%m-%d %H:%M:%S")
self.config["prediction_queue"].append(formatted_time)
logger.info(f'预计在{formatted_time}发送下一段语音') logger.info(f'预计在{formatted_time}发送下一段语音')
self.post_to_human_sync(reply_message) self.post_to_human_sync(reply_message)
# 睡眠一秒
time.sleep(5)
except Exception: except Exception:
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())

@ -28,11 +28,7 @@ if __name__ == "__main__":
prediction_queue = manager.list() # 共享队列,用来存放预测时间(字符串) prediction_queue = manager.list() # 共享队列,用来存放预测时间(字符串)
shared_config = manager.dict({ shared_config = manager.dict({
"is_speaking": False, "control_mode": 1
"predicted_time": None, # 最近一次用于对时差计算的预测时间
"speaking_false_time": None, # is_speaking 变为 False 的真实时间
"time_diff_seconds": None, # 真实时间 - 预测时间(秒)
"prediction_queue": prediction_queue # FIFO 队列,避免覆盖
}) })
queue = PromptQueue(10) queue = PromptQueue(10)

Loading…
Cancel
Save