agc_video_method.py 28 KB

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