CheckVideoGenerationTasksCommand.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\AIGeneration\AIVideoGenerationService;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. class CheckVideoGenerationTasksCommand extends Command
  7. {
  8. /** @var AIVideoGenerationService */
  9. private $videoGenerationService;
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'AIGeneration:checkVideoTasks';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = '检查视频生成任务状态并更新结果';
  22. /**
  23. * Execute the console command.
  24. *
  25. * @param AIVideoGenerationService $videoGenerationService
  26. * @return int
  27. */
  28. public function handle(AIVideoGenerationService $videoGenerationService)
  29. {
  30. $this->videoGenerationService = $videoGenerationService;
  31. dLog('command')->info('开始检查视频生成任务状态...');
  32. // 执行50s
  33. $time_start = time();
  34. try {
  35. $count = DB::table('mp_generate_video_tasks')->where('status', 'processing')->count('id');
  36. while ($count > 0) {
  37. $time_diff = time() - $time_start;
  38. sleep(3);
  39. if ($time_diff > 50) break;
  40. $videoGenerationService->updatePendingTasks();
  41. $count = DB::table('mp_generate_video_tasks')->where('status', 'processing')->count('id');
  42. }
  43. // 更新分镜表中的视频任务状态
  44. $this->updateSegmentVideoStatus();
  45. dLog('command')->info('视频任务状态检查完成');
  46. } catch (\Exception $e) {
  47. dLog('command')->error('视频任务状态检查失败: ' . $e->getMessage());
  48. logDB('command', 'error', '定时任务:视频生成任务状态检查失败', ['error' => $e->getMessage()]);
  49. return 1;
  50. }
  51. return 0;
  52. }
  53. /**
  54. * 更新分镜表中的视频任务状态
  55. *
  56. * @return void
  57. */
  58. private function updateSegmentVideoStatus()
  59. {
  60. try {
  61. // 获取所有状态为"生成中"的分镜(兼容分镜模式和全能模式)
  62. $segments = DB::table('mp_episode_segments')
  63. ->where('video_task_status', '生成中')
  64. ->whereNotNull('video_task_id')
  65. ->where('video_task_id', '<>', '')
  66. ->where('created_at', '<', date('Y-m-d H:i:s', strtotime('-20 hours')))
  67. ->select('id', 'segment_id', 'video_task_id', 'audio_duration')
  68. ->get();
  69. if ($segments->isEmpty()) {
  70. return;
  71. }
  72. dLog('command')->info('开始更新分镜视频任务状态', ['count' => $segments->count()]);
  73. $successCount = 0;
  74. $failedCount = 0;
  75. $processingCount = 0;
  76. foreach ($segments as $segment) {
  77. $videoTaskId = $segment->video_task_id;
  78. // 兼容两种模式:优先使用segment_id(分镜模式),如果为空则使用id(全能模式的act_id)
  79. $recordId = $segment->id;
  80. $segmentId = $segment->segment_id ?: $segment->id;
  81. // 查询视频生成任务状态
  82. $videoTask = DB::table('mp_generate_video_tasks')
  83. ->where('id', $videoTaskId)
  84. ->select('id', 'status', 'result_url', 'compressed_url', 'last_frame_url', 'error_message', 'result_json', 'extra_params', 'alias_segment_id', 'alias_act_id')
  85. ->first();
  86. if (!$videoTask) {
  87. dLog('command')->warning('分镜关联的视频任务不存在', [
  88. 'record_id' => $recordId,
  89. 'segment_id' => $segmentId,
  90. 'video_task_id' => $videoTaskId
  91. ]);
  92. continue;
  93. }
  94. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  95. // 根据任务状态更新分镜表
  96. if ($videoTask->status === 'success') {
  97. $updateData['video_task_status'] = '已完成';
  98. $updateData['origin_video_url'] = $videoTask->result_url;
  99. $updateData['video_url'] = $videoTask->compressed_url ?: $videoTask->result_url;
  100. $updateData['current_type'] = 2;
  101. // 如果有尾帧图片,也更新
  102. if (!empty($videoTask->last_frame_url)) {
  103. $updateData['last_frame_url'] = $videoTask->last_frame_url;
  104. }
  105. // 计算视频时长
  106. $video_duration = 0;
  107. if (!empty($videoTask->result_json)) {
  108. $resultJson = is_array($videoTask->result_json) ? $videoTask->result_json : json_decode($videoTask->result_json, true);
  109. if (isset($resultJson['duration'])) {
  110. // 如果直接返回duration,使用该值
  111. $video_duration = (int)$resultJson['duration'];
  112. } elseif (isset($resultJson['frames']) && isset($resultJson['framespersecond'])) {
  113. // 如果返回frames和framespersecond,计算时长
  114. $frames = (int)$resultJson['frames'];
  115. $fps = (int)$resultJson['framespersecond'];
  116. if ($fps > 0) {
  117. $video_duration = (int)floor($frames / $fps);
  118. }
  119. }
  120. }
  121. // 如果没有计算出时长,使用任务表中的设定值
  122. if ($video_duration <= 0 && !empty($videoTask->extra_params)) {
  123. $extraParams = is_array($videoTask->extra_params) ? $videoTask->extra_params : json_decode($videoTask->extra_params, true);
  124. if (isset($extraParams['duration'])) {
  125. $video_duration = (int)$extraParams['duration'];
  126. }
  127. }
  128. // 只有当video_duration > 0时才添加到更新数据中
  129. if ($video_duration > 0) {
  130. $updateData['video_duration'] = $video_duration;
  131. $updateData['video_time_point_start'] = 0;
  132. $segment_id = getProp($videoTask, 'alias_segment_id');
  133. $act_id = getProp($videoTask, 'alias_act_id');
  134. if ($segment_id) {
  135. // 分镜模式:使用segment_id查询
  136. $audio_duration = DB::table('mp_episode_segments')->where('segment_id', $segmentId)->value('audio_duration');
  137. } elseif ($act_id) {
  138. // 全能模式(全能模式):如果传入了video_duration直接返回,否则查询audio_duration
  139. if ($video_duration !== null && $video_duration > 0) {
  140. $audio_duration = $video_duration;
  141. }
  142. $audio_duration = DB::table('mp_episode_segments')->where('id', $segmentId)->value('audio_duration');
  143. }
  144. $updateData['video_time_point_end'] = $audio_duration ?? 0;
  145. }
  146. $successCount++;
  147. // 更新分镜视频成功后新增对话记录(addVideoGenerationRecords 内部按 video_task_id 幂等)
  148. $this->addVideoGenerationRecords($videoTask, $segmentId, $videoTask->result_url);
  149. dLog('command')->info('分镜视频生成成功', [
  150. 'record_id' => $recordId,
  151. 'segment_id' => $segmentId,
  152. 'video_task_id' => $videoTaskId,
  153. 'video_url' => $videoTask->result_url,
  154. 'video_duration' => $video_duration
  155. ]);
  156. } elseif ($videoTask->status === 'failed') {
  157. $updateData['video_task_status'] = '失败';
  158. $failedCount++;
  159. dLog('command')->error('分镜视频生成失败', [
  160. 'record_id' => $recordId,
  161. 'segment_id' => $segmentId,
  162. 'video_task_id' => $videoTaskId,
  163. 'error' => $videoTask->error_message
  164. ]);
  165. logDB('command', 'error', '分镜视频生成失败', [
  166. 'record_id' => $recordId,
  167. 'segment_id' => $segmentId,
  168. 'video_task_id' => $videoTaskId,
  169. 'error' => $videoTask->error_message
  170. ]);
  171. $this->videoGenerationService->addVideoGenerationFailedRecord($videoTask, $videoTask->error_message);
  172. } else {
  173. // 仍在处理中,不更新
  174. $processingCount++;
  175. continue;
  176. }
  177. // 更新分镜表(使用主键id更新,兼容两种模式)
  178. DB::table('mp_episode_segments')
  179. ->where('id', $recordId)
  180. ->update($updateData);
  181. }
  182. dLog('command')->info('分镜视频任务状态更新完成', [
  183. 'total' => $segments->count(),
  184. 'success' => $successCount,
  185. 'failed' => $failedCount,
  186. 'processing' => $processingCount
  187. ]);
  188. } catch (\Exception $e) {
  189. dLog('command')->error('更新分镜视频任务状态异常: ' . $e->getMessage());
  190. logDB('command', 'error', '更新分镜视频任务状态异常', [
  191. 'error' => $e->getMessage(),
  192. 'trace' => $e->getTraceAsString()
  193. ]);
  194. }
  195. }
  196. /**
  197. * 添加视频生成对话记录
  198. * @param array $task 任务数据
  199. * @param string|int $segmentIdOrActId segment_id(分镜模式)或 act_id(全能模式)
  200. * @param string $videoUrl 视频URL
  201. * @return void
  202. */
  203. private function addVideoGenerationRecords($task, $segmentIdOrActId, $videoUrl)
  204. {
  205. try {
  206. $segment_id = getProp($task, 'alias_segment_id');
  207. $act_id = getProp($task, 'alias_act_id');
  208. $reference_images = getProp($task, 'ref_image_url');
  209. if (!$reference_images) $reference_images = json_encode([], 256);
  210. if (!empty($segment_id)) {
  211. // 分镜模式:使用segment_id查询
  212. $segment = DB::table('mp_episode_segments as a')->leftJoin('mp_animes as b', 'a.anime_id', 'b.id')
  213. ->where('a.segment_id', $segmentIdOrActId)
  214. ->select('b.user_id as uid', 'a.anime_id', 'a.episode_number', 'a.tail_frame', 'a.segment_id')
  215. ->first();
  216. } elseif (!empty($act_id)) {
  217. // 全能模式:使用id查询
  218. $segment = DB::table('mp_episode_segments as a')->leftJoin('mp_animes as b', 'a.anime_id', 'b.id')
  219. ->where('a.id', $segmentIdOrActId)
  220. ->select('b.user_id as uid', 'a.anime_id', 'a.episode_number', 'a.act_content', 'a.act_show_content', 'a.id as act_id')
  221. ->first();
  222. } else {
  223. dLog('generate')->warning('无法确定查询模式,任务缺少segment_id和act_id', ['segment_id_or_act_id' => $segmentIdOrActId]);
  224. return;
  225. }
  226. if (!$segment) {
  227. dLog('generate')->warning('分镜信息不存在,无法添加对话记录', ['segment_id_or_act_id' => $segmentIdOrActId]);
  228. return;
  229. }
  230. $now = date('Y-m-d H:i:s');
  231. // 根据模式确定保存的字段和值
  232. if (!empty($segment_id)) {
  233. // 分镜模式:保存segment_id字段
  234. $recordField = 'segment_id';
  235. $recordValue = $segmentIdOrActId;
  236. $userContent = '图片转视频';
  237. $assistantContent = $segment->tail_frame ?: '';
  238. } else {
  239. // 全能模式:保存act_id字段
  240. $recordField = 'act_id';
  241. $recordValue = $segmentIdOrActId;
  242. $userContent = '片段转视频';
  243. $assistantContent = $segment->act_show_content ? $segment->act_show_content : $segment->act_content;
  244. if (!$assistantContent) $assistantContent = '';
  245. }
  246. // 同一视频任务只写一次对话记录(仅在有任务ID时按任务幂等,允许多个任务对应同一 act)
  247. $videoTaskId = getProp($task, 'id');
  248. if (!empty($videoTaskId)) {
  249. $exists = DB::table('mp_anime_records')
  250. ->where('video_task_id', $videoTaskId)
  251. ->where('role', 'assistant')
  252. ->exists();
  253. if ($exists) {
  254. dLog('generate')->info('该视频任务的对话记录已存在,跳过重复写入', [
  255. 'video_task_id' => $videoTaskId,
  256. 'segment_id_or_act_id' => $segmentIdOrActId,
  257. 'video_url' => $videoUrl
  258. ]);
  259. return;
  260. }
  261. }
  262. // 保存对话记录
  263. $records = [
  264. [
  265. 'uid' => $segment->uid,
  266. 'anime_id' => $segment->anime_id,
  267. 'sequence' => $segment->episode_number,
  268. 'role' => 'user',
  269. 'content' => $userContent,
  270. 'video_task_id' => $videoTaskId,
  271. $recordField => $recordValue,
  272. 'video_url' => '',
  273. 'reference_images' => json_encode([], 256),
  274. 'created_at' => $now,
  275. 'updated_at' => $now
  276. ],
  277. [
  278. 'uid' => $segment->uid,
  279. 'anime_id' => $segment->anime_id,
  280. 'sequence' => $segment->episode_number,
  281. 'role' => 'assistant',
  282. 'content' => $assistantContent,
  283. 'video_task_id' => $videoTaskId,
  284. $recordField => $recordValue,
  285. 'video_url' => $videoUrl,
  286. 'reference_images' => $reference_images,
  287. 'created_at' => $now,
  288. 'updated_at' => $now
  289. ]
  290. ];
  291. DB::table('mp_anime_records')->insert($records);
  292. dLog('generate')->info('视频生成对话记录添加成功', [
  293. 'segment_id_or_act_id' => $segmentIdOrActId,
  294. 'video_url' => $videoUrl,
  295. 'uid' => $segment->uid,
  296. 'anime_id' => $segment->anime_id
  297. ]);
  298. } catch (\Exception $e) {
  299. dLog('generate')->error('添加视频生成对话记录失败: ' . $e->getMessage(), [
  300. 'segment_id' => $segmentIdOrActId,
  301. 'video_url' => $videoUrl,
  302. 'error' => $e->getMessage()
  303. ]);
  304. }
  305. }
  306. }