agc_video_method.py 32 KB

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