CheckVideoGenerationTasksCommand.php 14 KB

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