agc_video_method.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. import configparser
  2. import glob
  3. import os
  4. import random
  5. import re
  6. import subprocess
  7. import sys
  8. import time
  9. import urllib.parse
  10. import requests
  11. from datetime import datetime, timedelta
  12. sys.path.append(os.getcwd())
  13. from common.db import MysqlHelper
  14. from common.material import Material
  15. from common import Common, Oss, Feishu
  16. config = configparser.ConfigParser()
  17. config.read('./config.ini') # 替换为您的配置文件路径
  18. class AgcVidoe():
  19. # 获取未使用的视频链接
  20. @classmethod
  21. def get_url_gs_list(cls, user_list, mark, limit_count):
  22. for i in range(5):
  23. user = random.choice(user_list)
  24. Common.logger("gs_video").info(f"account_id 为{user}")
  25. current_time = datetime.now()
  26. three_days_ago = current_time - timedelta(days=3)
  27. formatted_current_time = current_time.strftime("%Y-%m-%d")
  28. formatted_three_days_ago = three_days_ago.strftime("%Y-%m-%d")
  29. if limit_count == 1:
  30. url_list = f"""SELECT a.video_id, a.account_id, a.oss_object_key
  31. FROM agc_video_url a
  32. LEFT JOIN agc_video_deposit b
  33. ON a.oss_object_key = b.oss_object_key
  34. AND b.time = '{formatted_current_time}'
  35. WHERE b.video_id IS NULL
  36. AND a.account_id = '{user}'
  37. AND a.status = 1
  38. AND a.mark = '{mark}'
  39. LIMIT {limit_count};"""
  40. url_list = MysqlHelper.get_values(url_list, "prod")
  41. if url_list:
  42. return url_list
  43. else:
  44. url_list = f"""SELECT a.video_id, a.account_id, a.oss_object_key
  45. FROM agc_video_url a
  46. LEFT JOIN agc_video_deposit b
  47. ON a.oss_object_key = b.oss_object_key
  48. AND b.time >= '{formatted_three_days_ago}'
  49. AND b.time <= '{formatted_current_time}'
  50. WHERE b.video_id IS NULL
  51. AND a.account_id = '{user}'
  52. AND a.status = 1
  53. AND a.mark = '{mark}'
  54. LIMIT {limit_count};"""
  55. Common.logger("gs_video").info(f"{mark}sql{url_list} ")
  56. url_list = MysqlHelper.get_values(url_list, "prod")
  57. Common.logger("gs_video").info(f"{mark}查询数据{url_list} ")
  58. if url_list:
  59. if len(url_list) >= 30:
  60. return url_list
  61. return None
  62. # 获取未使用的视频链接
  63. @classmethod
  64. def get_url_list(cls, user_list, mark, limit_count):
  65. for i in range(5):
  66. user = str(random.choice(user_list))
  67. user = user.replace('(', '').replace(')', '').replace(',', '')
  68. current_time = datetime.now()
  69. three_days_ago = current_time - timedelta(days=3)
  70. formatted_current_time = current_time.strftime("%Y-%m-%d")
  71. formatted_three_days_ago = three_days_ago.strftime("%Y-%m-%d")
  72. if limit_count == 1:
  73. url_list = f"""SELECT a.video_id, a.account_id, a.oss_object_key
  74. FROM agc_video_url a
  75. LEFT JOIN agc_video_deposit b
  76. ON a.oss_object_key = b.oss_object_key
  77. AND b.time = '{formatted_current_time}'
  78. WHERE b.video_id IS NULL
  79. AND a.account_id = {user}
  80. AND a.status = 1
  81. AND a.mark = '{mark}'
  82. LIMIT {limit_count};"""
  83. url_list = MysqlHelper.get_values(url_list, "prod")
  84. if url_list:
  85. return url_list
  86. else:
  87. url_list = f"""SELECT a.video_id, a.account_id, a.oss_object_key
  88. FROM agc_video_url a
  89. LEFT JOIN agc_video_deposit b
  90. ON a.oss_object_key = b.oss_object_key
  91. AND b.time >= '{formatted_three_days_ago}'
  92. AND b.time <= '{formatted_current_time}'
  93. WHERE b.video_id IS NULL
  94. AND a.account_id = {user}
  95. AND a.status = 1
  96. AND a.mark = '{mark}'
  97. LIMIT {limit_count};"""
  98. url_list = MysqlHelper.get_values(url_list, "prod")
  99. if url_list:
  100. if len(url_list) >= 30:
  101. return url_list
  102. return None
  103. # 随机生成id
  104. @classmethod
  105. def random_id(cls):
  106. now = datetime.now()
  107. rand_num = random.randint(10000, 99999)
  108. oss_id = "{}{}".format(now.strftime("%Y%m%d%H%M%S"), rand_num)
  109. return oss_id
  110. # 获取已入库的用户id
  111. @classmethod
  112. def get_user_id(cls, channel_type, mark):
  113. account_id = f"""select account_id from agc_video_url where mark = '{mark}' and oss_object_key LIKE '%{channel_type}%' group by account_id ;"""
  114. account_id = MysqlHelper.get_values(account_id, "prod")
  115. return account_id
  116. # 获取已入库数量
  117. @classmethod
  118. def get_link_count(cls, mark, platform):
  119. current_time = datetime.now()
  120. formatted_time = current_time.strftime("%Y-%m-%d")
  121. count = f"""SELECT COUNT(*) AS total_count FROM ( SELECT audio, account_id FROM agc_video_deposit WHERE time = '{formatted_time}' AND platform = '{platform}' and mark = '{mark}' GROUP BY audio, account_id) AS subquery;"""
  122. count = MysqlHelper.get_values(count, "prod")
  123. if count == None:
  124. count = 0
  125. count = str(count).replace('(', '').replace(')', '').replace(',', '')
  126. return int(count)
  127. # 获取跟随脚本已入库数量
  128. @classmethod
  129. def get_link_gs_count(cls, mark):
  130. current_time = datetime.now()
  131. formatted_time = current_time.strftime("%Y-%m-%d")
  132. count = f"""SELECT COUNT(*) AS total_count FROM ( SELECT audio, account_id FROM agc_video_deposit WHERE time = '{formatted_time}' and mark LIKE '%{mark}%' GROUP BY audio, account_id) AS subquery;"""
  133. count = MysqlHelper.get_values(count, "prod")
  134. if count == None:
  135. count = 0
  136. count = str(count).replace('(', '').replace(')', '').replace(',', '')
  137. return int(count)
  138. # 获取跟随脚本站外已入库数量
  139. @classmethod
  140. def get_link_zw_count(cls, mark, platform):
  141. current_time = datetime.now()
  142. formatted_time = current_time.strftime("%Y-%m-%d")
  143. count = f"""SELECT COUNT(*) AS total_count FROM ( SELECT audio, account_id FROM agc_video_deposit WHERE time = '{formatted_time}' and mark = '{mark}' GROUP BY audio, account_id) AS subquery;"""
  144. count = MysqlHelper.get_values(count, "prod")
  145. if count == None:
  146. count = 0
  147. count = str(count).replace('(', '').replace(')', '').replace(',', '')
  148. return int(count)
  149. # 获取跟随脚本站内已入库数量
  150. @classmethod
  151. def get_link_zn_count(cls, mark, platform):
  152. current_time = datetime.now()
  153. formatted_time = current_time.strftime("%Y-%m-%d")
  154. count = f"""SELECT COUNT(*) AS total_count FROM ( SELECT audio, account_id FROM agc_video_deposit WHERE time = '{formatted_time}' AND platform = '{platform}' and mark = '{mark}' GROUP BY audio, account_id) AS subquery;"""
  155. count = MysqlHelper.get_values(count, "prod")
  156. if count == None:
  157. count = 0
  158. count = str(count).replace('(', '').replace(')', '').replace(',', '')
  159. return int(count)
  160. @classmethod
  161. def create_subtitle_file(cls, srt, s_path):
  162. # 创建临时字幕文件
  163. with open(s_path, 'w') as f:
  164. f.write(srt)
  165. @classmethod
  166. def convert_srt_to_ass(cls, s_path, a_path):
  167. # 使用 FFmpeg 将 SRT 转换为 ASS
  168. subprocess.run(["ffmpeg", "-i", s_path, a_path])
  169. # 新生成视频上传到对应账号下
  170. @classmethod
  171. def insert_piaoquantv(cls, oss_object_key, audio_title, pq_ids_list):
  172. for i in range(2):
  173. url = "https://vlogapi.piaoquantv.com/longvideoapi/crawler/video/send"
  174. payload = dict(pageSource='vlog-pages/post/post-video-post', videoPath=oss_object_key, width='720',
  175. height='1280', fileExtensions='mp4', viewStatus='1', title=audio_title,
  176. careModelStatus='1',
  177. token='f04f58d6e664cbc9902660a1e8d20ce6cd7fdb0f', loginUid=pq_ids_list[i],
  178. versionCode='719',
  179. machineCode='weixin_openid_o0w175aZ4FJtqVsA1tcozJDJHdDU', appId='wx89e7eb06478361d7',
  180. clientTimestamp='1703337579331',
  181. machineInfo='{"sdkVersion":"3.2.5","brand":"iPhone","language":"zh_CN","model":"iPhone 12 Pro<iPhone13,3>","platform":"ios","system":"iOS 15.6.1","weChatVersion":"8.0.44","screenHeight":844,"screenWidth":390,"pixelRatio":3,"windowHeight":762,"windowWidth":390,"softVersion":"4.1.719"}',
  182. sessionId='1703337560040-27bfe208-a389-f476-db1d-840681e04b32',
  183. subSessionId='1703337569952-8f56d53c-b36d-760e-8abe-0b4a027cd5bd', senceType='1089',
  184. hotSenceType='1089', id='1050', channel='pq')
  185. payload['videoPath'] = oss_object_key
  186. payload['title'] = audio_title
  187. data = urllib.parse.urlencode(payload)
  188. headers = {
  189. 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.44(0x18002c2d) NetType/WIFI Language/zh_CN',
  190. 'Accept-Encoding': 'gzip,compress,br,deflate',
  191. 'Referer': 'https://servicewechat.com/wx89e7eb06478361d7/726/page-frame.html',
  192. 'Content-Type': 'application/x-www-form-urlencoded',
  193. 'Cookie': 'JSESSIONID=A60D96E7A300A25EA05425B069C8B459'
  194. }
  195. requests.post(url, data=data, headers=headers)
  196. return True
  197. # 获取视频链接
  198. @classmethod
  199. def get_audio_url(cls, uid, mark, mark_name):
  200. cookie = Material.get_houtai_cookie()
  201. url = f"https://admin.piaoquantv.com/manager/video/detail/{uid}"
  202. payload = {}
  203. headers = {
  204. 'authority': 'admin.piaoquantv.com',
  205. 'accept': 'application/json, text/plain, */*',
  206. 'accept-language': 'zh-CN,zh;q=0.9',
  207. 'cache-control': 'no-cache',
  208. 'cookie': cookie,
  209. 'pragma': 'no-cache',
  210. 'referer': f'https://admin.piaoquantv.com/cms/post-detail/{uid}/detail',
  211. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  212. 'sec-ch-ua-mobile': '?0',
  213. 'sec-ch-ua-platform': '"macOS"',
  214. 'sec-fetch-dest': 'empty',
  215. 'sec-fetch-mode': 'cors',
  216. 'sec-fetch-site': 'same-origin',
  217. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  218. }
  219. response = requests.request("GET", url, headers=headers, data=payload)
  220. data = response.json()
  221. try:
  222. code = data["code"]
  223. if code != 0:
  224. Common.logger("video").info(
  225. f"未登录,请更换cookie,{data}")
  226. Feishu.bot('recommend', '管理后台', '管理后台cookie失效,请及时更换~', mark, mark_name)
  227. return ""
  228. audio_url = data["content"]["transedVideoPath"]
  229. audio_title = data["content"]['title']
  230. return audio_url, audio_title
  231. except Exception as e:
  232. Common.logger("video").warning(f"获取音频视频链接失败:{e}\n")
  233. return ""
  234. # 获取视频时长
  235. @classmethod
  236. def get_audio_duration(cls, video_url):
  237. ffprobe_cmd = [
  238. "ffprobe",
  239. "-i", video_url,
  240. "-show_entries", "format=duration",
  241. "-v", "quiet",
  242. "-of", "csv=p=0"
  243. ]
  244. output = subprocess.check_output(ffprobe_cmd).decode("utf-8").strip()
  245. return float(output)
  246. # 获取视频文件的时长(秒)
  247. @classmethod
  248. def get_video_duration(cls, video_file):
  249. result = subprocess.run(
  250. ["ffprobe", "-v", "error", "-show_entries", "format=duration",
  251. "-of", "default=noprint_wrappers=1:nokey=1", video_file],
  252. capture_output=True, text=True)
  253. return float(result.stdout)
  254. @classmethod
  255. def clear_mp4_files(cls, folder_path):
  256. # 获取文件夹中所有扩展名为 '.mp4' 的文件路径列表
  257. mp4_files = glob.glob(os.path.join(folder_path, '*.mp4'))
  258. if not mp4_files:
  259. return
  260. # 遍历并删除所有 .mp4 文件
  261. for mp4_file in mp4_files:
  262. os.remove(mp4_file)
  263. print(f"文件夹 '{folder_path}' 中的所有 .mp4 文件已清空。")
  264. # 计算需要拼接的视频
  265. @classmethod
  266. def concat_videos_with_subtitles(cls, videos, audio_duration, platform, mark):
  267. # 计算视频文件列表总时长
  268. total_video_duration = sum(cls.get_video_duration(video_file[3]) for video_file in videos)
  269. if platform == "koubo" or platform == "zhannei":
  270. # 视频时长大于音频时长
  271. if total_video_duration > audio_duration:
  272. return videos
  273. # 计算音频秒数与视频秒数的比率,然后加一得到需要的视频数量
  274. video_audio_ratio = audio_duration / total_video_duration
  275. videos_needed = int(video_audio_ratio) + 2
  276. trimmed_video_list = videos * videos_needed
  277. return trimmed_video_list
  278. else:
  279. # 如果视频总时长小于音频时长,则不做拼接
  280. if total_video_duration < audio_duration:
  281. Common.logger("video").info(f"{mark}的{platform}渠道时长小于等于目标时长,不做视频拼接")
  282. return ""
  283. # 如果视频总时长大于音频时长,则截断视频
  284. trimmed_video_list = []
  285. remaining_duration = audio_duration
  286. for video_file in videos:
  287. video_duration = cls.get_video_duration(video_file[3])
  288. if video_duration <= remaining_duration:
  289. # 如果视频时长小于或等于剩余时长,则将整个视频添加到列表中
  290. trimmed_video_list.append(video_file)
  291. remaining_duration -= video_duration
  292. else:
  293. trimmed_video_list.append(video_file)
  294. break
  295. return trimmed_video_list
  296. # 已使用视频链接存表
  297. @classmethod
  298. def insert_videoAudio(cls, video_files, uid, platform, mark):
  299. current_time = datetime.now()
  300. formatted_time = current_time.strftime("%Y-%m-%d")
  301. for j in video_files:
  302. insert_sql = f"""INSERT INTO agc_video_deposit (audio, video_id, account_id, oss_object_key, time, platform, mark) values ('{uid}', '{j[0]}', '{j[1]}', '{j[2]}', '{formatted_time}', '{platform}', '{mark}')"""
  303. MysqlHelper.update_values(
  304. sql=insert_sql,
  305. env="prod",
  306. machine="",
  307. )
  308. #文件没有则创建目录
  309. @classmethod
  310. def create_folders(cls, mark):
  311. oss_id = cls.random_id()
  312. video_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/"
  313. # srt 目录
  314. s_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/srt/"
  315. # oss 目录
  316. v_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/oss/"
  317. if not os.path.exists(video_path_url):
  318. os.makedirs(video_path_url)
  319. if not os.path.exists(s_path_url):
  320. os.makedirs(s_path_url)
  321. if not os.path.exists(v_path_url):
  322. os.makedirs(v_path_url)
  323. # srt 文件地址
  324. s_path = s_path_url + mark + f"{str(oss_id)}.srt"
  325. # 最终生成视频地址
  326. v_path = v_path_url + mark + f"{str(oss_id)}.mp4"
  327. v_oss_path = v_path_url + mark + f"{str(oss_id)}oss.mp4"
  328. return s_path, v_path, video_path_url, v_oss_path
  329. # 视频拼接
  330. @classmethod
  331. def concatenate_videos(cls, videos, audio_duration, audio_video, platform, s_path, v_path, mark, v_oss_path ):
  332. video_files = cls.concat_videos_with_subtitles(videos, audio_duration, platform, mark)
  333. Common.logger("video").info(f"{mark}的{platform}视频文件:{video_files}")
  334. Common.logger("video").info(f"{mark}的{platform}渠道待生成视频为:{video_files}")
  335. if video_files == "":
  336. return ""
  337. print(f"{mark}的{platform}:开始拼接视频喽~~~")
  338. Common.logger("video").info(f"{mark}的{platform}:开始拼接视频喽~~~")
  339. if os.path.exists(s_path):
  340. # subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=11,Fontname=Hiragino Sans GB,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
  341. subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=12,Fontname=wqy-zenhei,Bold=1,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
  342. else:
  343. # subtitle_cmd = "drawtext=text='分享、转发给群友':fontsize=28:fontcolor=black:x=(w-text_w)/2:y=h-text_h-15"
  344. subtitle_cmd = "drawtext=text='分享、转发给群友':x=(w-text_w)/2:y=h-text_h-15:fontsize=28:fontcolor=black:fontfile=/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"
  345. # 背景色参数
  346. background_cmd = "drawbox=y=ih-65:color=yellow@1.0:width=iw:height=0:t=fill"
  347. VIDEO_COUNTER = 0
  348. FF_INPUT = ""
  349. FF_SCALE = ""
  350. FF_FILTER = ""
  351. ffmpeg_cmd = ["ffmpeg"]
  352. for videos in video_files:
  353. Common.logger("video").info(f"{mark}的{platform}视频:{videos[3]}")
  354. # 添加输入文件
  355. FF_INPUT += f" -i {videos[3]}"
  356. # 为每个视频文件统一长宽,并设置SAR(采样宽高比)
  357. FF_SCALE += f"[{VIDEO_COUNTER}:v]scale=320x480,setsar=1[v{VIDEO_COUNTER}];"
  358. # 为每个视频文件创建一个输入流,并添加到-filter_complex参数中
  359. FF_FILTER += f"[v{VIDEO_COUNTER}][{VIDEO_COUNTER}:a]"
  360. # 增加视频计数器
  361. VIDEO_COUNTER += 1
  362. # 构建最终的FFmpeg命令
  363. ffmpeg_cmd.extend(FF_INPUT.split())
  364. ffmpeg_cmd.extend(["-filter_complex", f"{FF_SCALE}{FF_FILTER}concat=n={VIDEO_COUNTER}:v=1:a=1[v][a]",
  365. "-map", "[v]", "-map", "[a]", v_path])
  366. # 多线程数
  367. num_threads = 4
  368. # 构建 FFmpeg 命令,生成视频
  369. ffmpeg_cmd_oss = [
  370. "ffmpeg",
  371. "-i", v_path, # 视频文件列表
  372. "-i", audio_video, # 音频文件
  373. "-c:v", "libx264", # 复制视频流
  374. "-c:a", "aac", # 编码音频流为AAC
  375. "-threads", str(num_threads),
  376. "-vf", f"{background_cmd},{subtitle_cmd}", # 添加背景色和字幕
  377. "-t", str(int(audio_duration)), # 保持与音频时长一致
  378. "-map", "0:v:0", # 映射第一个输入的视频流
  379. "-map", "1:a:0", # 映射第二个输入的音频流
  380. "-y", # 覆盖输出文件
  381. v_oss_path
  382. ]
  383. try:
  384. subprocess.run(ffmpeg_cmd)
  385. if os.path.isfile(v_path):
  386. subprocess.run(ffmpeg_cmd_oss)
  387. print("视频处理完成!")
  388. except subprocess.CalledProcessError as e:
  389. print(f"视频处理失败:{e}")
  390. print(f"{mark}的{platform}:视频拼接成功啦~~~")
  391. Common.logger("video").info(f"{mark}的{platform}:视频拼接成功啦~~~")
  392. return video_files
  393. # 常规任务
  394. @classmethod
  395. def video_stitching(cls, ex_list):
  396. pq_ids = ex_list["pq_id"]
  397. pq_ids_list = pq_ids.split(',')
  398. mark_name = ex_list['mark_name']
  399. mark = ex_list["mark"]
  400. feishu_id = ex_list["feishu_id"]
  401. video_call = ex_list["video_call"]
  402. parts = video_call.split(',')
  403. result = []
  404. for part in parts:
  405. sub_parts = part.split('--')
  406. result.append(sub_parts)
  407. link = result[0][0]
  408. yhmw_all_count = result[0][1]
  409. if int(yhmw_all_count) == 0:
  410. yhmw_count = 0
  411. else:
  412. yhmw_count = int(int(yhmw_all_count)/2)
  413. # 如果没有该文件目录则创建,有文件目录的话 则删除文件
  414. s_path, v_path, video_path_url, v_oss_path = cls.create_folders(mark)
  415. kb_count = int(result[1][1])
  416. channel = ['douyin', 'kuaishou', 'koubo']
  417. try:
  418. for platform in channel:
  419. limit_count = 35
  420. count = cls.get_link_count(mark, platform)
  421. if platform == "douyin" and count >= yhmw_count:
  422. continue
  423. elif platform == "kuaishou" and count >= yhmw_count:
  424. continue
  425. elif platform == "koubo":
  426. link = result[1][0]
  427. limit_count = 1
  428. if count >= kb_count or kb_count == 0:
  429. Feishu.bot('recommend', 'AGC完成通知', '今日常规自制视频拼接任务完成啦~', mark, mark_name)
  430. return mark
  431. # 获取音频类型+字幕+标题
  432. uid, srt, video_list = Material.get_all_data(feishu_id, link, mark)
  433. # 获取已入库的用户id
  434. user_id = cls.get_user_id(platform, mark)
  435. # 获取 未使用的视频链接
  436. url_list = cls.get_url_list(user_id, mark, limit_count)
  437. if url_list == None:
  438. Common.logger("video").info(f"未使用视频链接为空:{url_list}")
  439. return ''
  440. videos = [list(item) for item in url_list]
  441. # 下载视频
  442. videos = Oss.get_oss_url(videos, video_path_url)
  443. if srt:
  444. # 创建临时字幕文件
  445. cls.create_subtitle_file(srt, s_path)
  446. Common.logger("video").info(f"S{mark}的{platform}渠道RT 文件目录创建成功")
  447. # 获取音频
  448. audio_video, audio_title = cls.get_audio_url(uid, mark, mark_name)
  449. Common.logger("video").info(f"{mark}的{platform}渠道获取需要拼接的音频成功")
  450. # 获取音频秒数
  451. audio_duration = cls.get_audio_duration(audio_video)
  452. Common.logger("video").info(f"{mark}的{platform}渠道获取需要拼接的音频秒数为:{audio_duration}")
  453. video_files = cls.concatenate_videos(videos, audio_duration, audio_video, platform, s_path, v_path, mark, v_oss_path)
  454. if video_files == "":
  455. Common.logger("video").info(f"{mark}的{platform}渠道使用拼接视频为空")
  456. return ""
  457. if os.path.isfile(v_oss_path):
  458. Common.logger("video").info(f"{mark}的{platform}渠道新视频生成成功")
  459. else:
  460. Common.logger("video").info(f"{mark}的{platform}渠道新视频生成失败")
  461. return ""
  462. # 随机生成视频oss_id
  463. oss_id = cls.random_id()
  464. # 获取新生成视频时长
  465. v_path_duration = cls.get_audio_duration(v_oss_path)
  466. if v_path_duration > audio_duration+3 or v_path_duration < audio_duration-3:
  467. print(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒,实际秒数{audio_duration}")
  468. Common.logger("video").info(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒,实际秒数{audio_duration}")
  469. return ""
  470. # 上传 oss
  471. Common.logger("video").info(f"{mark}的{platform}渠道上传到 OSS 生成视频id为:{oss_id}")
  472. oss_object_key = Oss.stitching_sync_upload_oss(v_oss_path, oss_id)
  473. status = oss_object_key.get("status")
  474. if status == 200:
  475. # 获取 oss 视频地址
  476. oss_object_key = oss_object_key.get("oss_object_key")
  477. Common.logger("video").info(f"{mark}的{platform}渠道拼接视频发送成功,OSS 地址:{oss_object_key}")
  478. time.sleep(10)
  479. # 已使用视频存入数据库
  480. Common.logger("video").info(f"{mark}的{platform}渠道开始已使用视频存入数据库")
  481. cls.insert_videoAudio(video_files, uid, platform, mark)
  482. Common.logger("video").info(f"{mark}的{platform}渠道完成已使用视频存入数据库")
  483. Common.logger("video").info(f"{mark}的{platform}渠道开始视频添加到对应用户")
  484. piaoquantv = cls.insert_piaoquantv(oss_object_key, audio_title, pq_ids_list)
  485. if piaoquantv:
  486. Common.logger("video").info(f"{mark}的{platform}渠道视频添加到对应用户成功")
  487. if os.path.isfile(v_oss_path):
  488. os.remove(v_oss_path)
  489. if os.path.isfile(v_path):
  490. os.remove(v_path)
  491. if os.path.isfile(s_path):
  492. os.remove(s_path)
  493. # 清空所有mp4数据
  494. cls.clear_mp4_files(video_path_url)
  495. return ''
  496. except Exception as e:
  497. Common.logger("video").warning(f"{mark}的视频拼接失败:{e}\n")
  498. return ''
  499. # 脚本跟随任务
  500. @classmethod
  501. def video_gs_stitching(cls, ex_list):
  502. pq_ids = ex_list["pq_id"]
  503. pq_ids_list = pq_ids.split(',') # 账号ID
  504. mark_name = ex_list['mark_name'] # 负责人
  505. mark = ex_list["mark"] # 标示
  506. feishu_id = ex_list["feishu_id"] # 飞书文档ID
  507. video_call = ex_list["video_call"]
  508. parts = video_call.split(',')
  509. result = []
  510. for part in parts:
  511. sub_parts = part.split('--')
  512. result.append(sub_parts)
  513. link = result[0][0] # 脚本链接
  514. count = result[0][1] # 生成条数
  515. zd_count = ex_list["zd_count"] # 生成总条数
  516. # 总条数
  517. result = re.match(r'([^0-9]+)', mark).group()
  518. all_count = cls.get_link_gs_count(result)
  519. if all_count >= int(zd_count):
  520. Feishu.bot('recommend', 'AGC完成通知', '今日脚本跟随视频拼接任务完成啦~', mark.split("-")[0], mark_name)
  521. return mark
  522. # 获取音频类型+字幕+标题
  523. uid, srt, video_list = Material.get_all_data(feishu_id, link, mark)
  524. platform_list = ex_list["platform_list"] # 渠道
  525. # 如果没有该文件目录则创建,有文件目录的话 则删除文件
  526. s_path, v_path, video_path_url, v_oss_path = cls.create_folders(mark)
  527. platform = ''
  528. if platform_list:
  529. platform_name_list = random.choice(platform_list)
  530. platform_name = platform_name_list[1]
  531. platform_url = platform_name_list[0]
  532. if platform_name == "快手":
  533. platform = 'kuaishou'
  534. elif platform_name == "抖音":
  535. platform = 'douyin'
  536. zw_count = cls.get_link_zw_count(mark, "zhannei")
  537. if zw_count >= int(count):
  538. return video_call
  539. # 获取所有视频素材ID
  540. video_list = Material.get_user_id(feishu_id, platform_url)
  541. limit_count = 35
  542. else:
  543. platform = 'zhannei'
  544. zw_count = cls.get_link_zn_count(mark, platform)
  545. if zw_count >= int(count):
  546. return video_call
  547. limit_count = 1
  548. Common.logger("gs_video").info(f"{mark}的{platform} 开始查询")
  549. url_list = cls.get_url_gs_list(video_list, mark, limit_count)
  550. if url_list == None:
  551. Common.logger("gs_video").info(f"{mark}的{platform} 渠道 视频画面不足无法拼接")
  552. return
  553. videos = [list(item) for item in url_list]
  554. try:
  555. # 下载视频
  556. videos = Oss.get_oss_url(videos, video_path_url)
  557. if srt:
  558. # 创建临时字幕文件
  559. cls.create_subtitle_file(srt, s_path)
  560. Common.logger("gs_video").info(f"S{mark}的{platform}渠道RT 文件目录创建成功")
  561. # 获取音频
  562. audio_video, audio_title = cls.get_audio_url(uid, mark, mark_name)
  563. Common.logger("gs_video").info(f"{mark}的{platform}渠道获取需要拼接的音频成功")
  564. # 获取音频秒数
  565. audio_duration = cls.get_audio_duration(audio_video)
  566. Common.logger("gs_video").info(f"{mark}的{platform}渠道获取需要拼接的音频秒数为:{audio_duration}")
  567. video_files = cls.concatenate_videos(videos, audio_duration, audio_video, platform, s_path, v_path, mark, v_oss_path)
  568. if video_files == "":
  569. Common.logger("gs_video").info(f"{mark}的{platform}渠道使用拼接视频为空")
  570. return ""
  571. if os.path.isfile(v_oss_path):
  572. Common.logger("gs_video").info(f"{mark}的{platform}渠道新视频生成成功")
  573. else:
  574. Common.logger("gs_video").info(f"{mark}的{platform}渠道新视频生成失败")
  575. return ""
  576. # 随机生成视频oss_id
  577. oss_id = cls.random_id()
  578. # 获取新生成视频时长
  579. v_path_duration = cls.get_audio_duration(v_oss_path)
  580. if v_path_duration > audio_duration+3 or v_path_duration < audio_duration-3:
  581. print(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒,实际秒数{audio_duration}")
  582. Common.logger("gs_video").info(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒,实际秒数{audio_duration}")
  583. return ""
  584. # 上传 oss
  585. Common.logger("gs_video").info(f"{mark}的{platform}渠道上传到 OSS 生成视频id为:{oss_id}")
  586. oss_object_key = Oss.stitching_sync_upload_oss(v_oss_path, oss_id)
  587. status = oss_object_key.get("status")
  588. if status == 200:
  589. # 获取 oss 视频地址
  590. oss_object_key = oss_object_key.get("oss_object_key")
  591. Common.logger("gs_video").info(f"{mark}的{platform}渠道拼接视频发送成功,OSS 地址:{oss_object_key}")
  592. time.sleep(10)
  593. # 已使用视频存入数据库
  594. Common.logger("gs_video").info(f"{mark}的{platform}渠道开始已使用视频存入数据库")
  595. cls.insert_videoAudio(video_files, uid, platform, mark)
  596. Common.logger("gs_video").info(f"{mark}的{platform}渠道完成已使用视频存入数据库")
  597. Common.logger("gs_video").info(f"{mark}的{platform}渠道开始视频添加到对应用户")
  598. piaoquantv = cls.insert_piaoquantv(oss_object_key, audio_title, pq_ids_list)
  599. if piaoquantv:
  600. Common.logger("gs_video").info(f"{mark}的{platform}渠道视频添加到对应用户成功")
  601. if os.path.isfile(v_oss_path):
  602. os.remove(v_oss_path)
  603. if os.path.isfile(v_path):
  604. os.remove(v_path)
  605. if os.path.isfile(s_path):
  606. os.remove(s_path)
  607. # 清空所有mp4数据
  608. for file_path in videos:
  609. os.remove(file_path[3])
  610. print(f"已删除文件:{file_path[3]}")
  611. return ''
  612. except Exception as e:
  613. Common.logger("gs_video").warning(f"{mark}的视频拼接失败:{e}\n")
  614. return ''