agc_video_method.py 31 KB

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