import json from config.settings import settings from utils.logger import logger import datetime import os import asyncio from models.script import Script from config.database import SessionLocal from llm.generate_daily_article import generate_daily_article project_name = "故事任意门" # for daily article generation def job_generate_daily_article(): """定时任务:生成每日文章并保存至数据库。""" logger.info("Starting job: Generate Daily Article") # 1. 调用 LLM 生成每日文章 content = generate_daily_article() if not content: logger.warning("No daily article generated.") return # 2. 保存至数据库 # subject 以当前日期为准,格式 YYYY-MM-DD today_str = datetime.datetime.now().strftime("%Y-%m-%d") article_title= content["阶段4_今日文章"]["文章标题"] db = SessionLocal() try: # 查询是否已存在 project+subject 唯一记录 script = db.query(Script).filter_by(project=project_name, subject=today_str).first() if script: # 存在则更新内容 script.content = json.dumps(content, ensure_ascii=False, separators=(",", ":")) db.commit() logger.info(f"Updated script for {today_str} with {article_title}.") else: # 不存在则新建 script = Script( project=project_name, subject=today_str, content=json.dumps(content, ensure_ascii=False, separators=(",", ":")) ) db.add(script) db.commit() logger.info(f"Saved script for {today_str} with {article_title}.") except Exception as e: db.rollback() logger.error(f"Failed to save/update script for {today_str}: {e}") # 3. 生成音频 try: from tts.service import TTSService article_text = content["阶段4_今日文章"]["文章正文"] logger.debug(f"Synthesizing daily article audio for '{article_title}'") article_audio = asyncio.run(TTSService.synthesize( text=article_text, voice="yanglan", language="zh-CN" )) if not article_audio: logger.warning("No audio synthesized for daily article.") return # 保存音频文件 out_dir = os.path.join(settings.OUTPUT_PATH, project_name) os.makedirs(out_dir, exist_ok=True) safe_title = "_".join(article_title.split()) audio_filename = f"{safe_title}_{today_str}.wav" audio_path = os.path.join(out_dir, audio_filename) with open(audio_path, "wb") as fw: fw.write(article_audio.getvalue()) logger.info(f"Saved daily article audio to {audio_path}") except Exception as e: logger.error(f"Failed to synthesize/save daily article audio: {e}") logger.info("Completed job: Generate Daily Article") # For manual testing # if __name__ == "__main__": # 每日文章生成 # job_generate_daily_article()