agc_video_method.py 32 KB

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