agc_video_method.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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
  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, mark, limit_count):
  21. current_time = datetime.now()
  22. formatted_time = current_time.strftime("%Y-%m-%d")
  23. url_list = f"""SELECT a.video_id,a.account_id,a.oss_object_key FROM agc_video_url a WHERE NOT EXISTS (
  24. SELECT video_id
  25. FROM agc_video_deposit b
  26. WHERE a.oss_object_key = b.oss_object_key AND b.time = '{formatted_time}'
  27. ) AND a.account_id = {user} and a.`status` = 1 and a.mark = '{mark}' limit {limit_count};"""
  28. url_list = MysqlHelper.get_values(url_list, "prod")
  29. return url_list
  30. # 随机生成id
  31. @classmethod
  32. def random_id(cls):
  33. now = datetime.now()
  34. rand_num = random.randint(10000, 99999)
  35. oss_id = "{}{}".format(now.strftime("%Y%m%d%H%M%S"), rand_num)
  36. return oss_id
  37. # 获取已入库的用户id
  38. @classmethod
  39. def get_user_id(cls, channel_type, mark):
  40. account_id = f"""select account_id from agc_video_url where mark = '{mark}' and oss_object_key LIKE '%{channel_type}%' group by account_id ;"""
  41. account_id = MysqlHelper.get_values(account_id, "prod")
  42. return account_id
  43. # 获取已入库数量
  44. @classmethod
  45. def get_link_count(cls, mark, platform):
  46. current_time = datetime.now()
  47. formatted_time = current_time.strftime("%Y-%m-%d")
  48. 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;"""
  49. count = MysqlHelper.get_values(count, "prod")
  50. if count == None:
  51. count = 0
  52. count = str(count).replace('(', '').replace(')', '').replace(',', '')
  53. return int(count)
  54. @classmethod
  55. def create_subtitle_file(cls, srt, s_path):
  56. # 创建临时字幕文件
  57. with open(s_path, 'w') as f:
  58. f.write(srt)
  59. @classmethod
  60. def convert_srt_to_ass(cls, s_path, a_path):
  61. # 使用 FFmpeg 将 SRT 转换为 ASS
  62. subprocess.run(["ffmpeg", "-i", s_path, a_path])
  63. # 新生成视频上传到对应账号下
  64. @classmethod
  65. def insert_piaoquantv(cls, oss_object_key, title_list, pq_ids_list):
  66. for i in range(2):
  67. title_list = [item for item in title_list if item is not None]
  68. title = random.choice(title_list)
  69. url = "https://vlogapi.piaoquantv.com/longvideoapi/crawler/video/send"
  70. payload = dict(pageSource='vlog-pages/post/post-video-post', videoPath=oss_object_key, width='720',
  71. height='1280', fileExtensions='mp4', viewStatus='1', title=title,
  72. careModelStatus='1',
  73. token='f04f58d6e664cbc9902660a1e8d20ce6cd7fdb0f', loginUid=pq_ids_list[i],
  74. versionCode='719',
  75. machineCode='weixin_openid_o0w175aZ4FJtqVsA1tcozJDJHdDU', appId='wx89e7eb06478361d7',
  76. clientTimestamp='1703337579331',
  77. 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"}',
  78. sessionId='1703337560040-27bfe208-a389-f476-db1d-840681e04b32',
  79. subSessionId='1703337569952-8f56d53c-b36d-760e-8abe-0b4a027cd5bd', senceType='1089',
  80. hotSenceType='1089', id='1050', channel='pq')
  81. payload['videoPath'] = oss_object_key
  82. payload['title'] = title
  83. data = urllib.parse.urlencode(payload)
  84. headers = {
  85. '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',
  86. 'Accept-Encoding': 'gzip,compress,br,deflate',
  87. 'Referer': 'https://servicewechat.com/wx89e7eb06478361d7/726/page-frame.html',
  88. 'Content-Type': 'application/x-www-form-urlencoded',
  89. 'Cookie': 'JSESSIONID=A60D96E7A300A25EA05425B069C8B459'
  90. }
  91. response = requests.post(url, data=data, headers=headers)
  92. data = response.json()
  93. return True
  94. # 获取视频链接
  95. @classmethod
  96. def get_audio_url(cls, uid, mark, mark_name):
  97. cookie = Material.get_houtai_cookie()
  98. url = f"https://admin.piaoquantv.com/manager/video/detail/{uid}"
  99. payload = {}
  100. headers = {
  101. 'authority': 'admin.piaoquantv.com',
  102. 'accept': 'application/json, text/plain, */*',
  103. 'accept-language': 'zh-CN,zh;q=0.9',
  104. 'cache-control': 'no-cache',
  105. 'cookie': cookie,
  106. 'pragma': 'no-cache',
  107. 'referer': f'https://admin.piaoquantv.com/cms/post-detail/{uid}/detail',
  108. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  109. 'sec-ch-ua-mobile': '?0',
  110. 'sec-ch-ua-platform': '"macOS"',
  111. 'sec-fetch-dest': 'empty',
  112. 'sec-fetch-mode': 'cors',
  113. 'sec-fetch-site': 'same-origin',
  114. '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'
  115. }
  116. response = requests.request("GET", url, headers=headers, data=payload)
  117. data = response.json()
  118. try:
  119. code = data["code"]
  120. if code != 0:
  121. Common.logger("video").info(
  122. f"未登录,请更换cookie,{data}")
  123. Feishu.bot('recommend', '管理后台', '管理后台cookie失效,请及时更换~', mark, mark_name)
  124. return ""
  125. audio_url = data["content"]["transedVideoPath"]
  126. return audio_url
  127. except Exception as e:
  128. Common.logger("video").warning(f"获取音频视频链接失败:{e}\n")
  129. return ""
  130. # 获取视频时长
  131. @classmethod
  132. def get_audio_duration(cls, video_url):
  133. ffprobe_cmd = [
  134. "ffprobe",
  135. "-i", video_url,
  136. "-show_entries", "format=duration",
  137. "-v", "quiet",
  138. "-of", "csv=p=0"
  139. ]
  140. output = subprocess.check_output(ffprobe_cmd).decode("utf-8").strip()
  141. return float(output)
  142. # 获取视频文件的时长(秒)
  143. @classmethod
  144. def get_video_duration(cls, video_file):
  145. result = subprocess.run(
  146. ["ffprobe", "-v", "error", "-show_entries", "format=duration",
  147. "-of", "default=noprint_wrappers=1:nokey=1", video_file],
  148. capture_output=True, text=True)
  149. return float(result.stdout)
  150. @classmethod
  151. def clear_mp4_files(cls, folder_path):
  152. # 获取文件夹中所有扩展名为 '.mp4' 的文件路径列表
  153. mp4_files = glob.glob(os.path.join(folder_path, '*.mp4'))
  154. if not mp4_files:
  155. return
  156. # 遍历并删除所有 .mp4 文件
  157. for mp4_file in mp4_files:
  158. os.remove(mp4_file)
  159. print(f"已删除文件: {mp4_file}")
  160. print(f"文件夹 '{folder_path}' 中的所有 .mp4 文件已清空。")
  161. # 计算需要拼接的视频
  162. @classmethod
  163. def concat_videos_with_subtitles(cls, videos, audio_duration, platform, mark):
  164. # 计算视频文件列表总时长
  165. total_video_duration = sum(cls.get_video_duration(video_file[3]) for video_file in videos)
  166. if platform == "koubo":
  167. # 视频时长大于音频时长
  168. if total_video_duration > audio_duration:
  169. return videos
  170. # 计算音频秒数与视频秒数的比率,然后加一得到需要的视频数量
  171. video_audio_ratio = audio_duration / total_video_duration
  172. videos_needed = int(video_audio_ratio) + 2
  173. trimmed_video_list = videos * videos_needed
  174. return trimmed_video_list
  175. else:
  176. # 如果视频总时长小于音频时长,则不做拼接
  177. if total_video_duration < audio_duration:
  178. Common.logger("video").info(f"{mark}的{platform}渠道时长小于等于目标时长,不做视频拼接")
  179. return ""
  180. # 如果视频总时长大于音频时长,则截断视频
  181. trimmed_video_list = []
  182. remaining_duration = audio_duration
  183. for video_file in videos:
  184. video_duration = cls.get_video_duration(video_file[3])
  185. if video_duration <= remaining_duration:
  186. # 如果视频时长小于或等于剩余时长,则将整个视频添加到列表中
  187. trimmed_video_list.append(video_file)
  188. remaining_duration -= video_duration
  189. else:
  190. trimmed_video_list.append(video_file)
  191. break
  192. return trimmed_video_list
  193. # 已使用视频链接存表
  194. @classmethod
  195. def insert_videoAudio(cls, video_files, uid, platform, mark):
  196. current_time = datetime.now()
  197. formatted_time = current_time.strftime("%Y-%m-%d")
  198. for j in video_files:
  199. 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}')"""
  200. MysqlHelper.update_values(
  201. sql=insert_sql,
  202. env="prod",
  203. machine="",
  204. )
  205. #文件没有则创建目录
  206. @classmethod
  207. def create_folders(cls, mark):
  208. video_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/"
  209. # srt 目录
  210. s_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/srt/"
  211. # txt 目录
  212. t_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/txt/"
  213. # oss 目录
  214. v_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/oss/"
  215. if not os.path.exists(video_path_url):
  216. os.makedirs(video_path_url)
  217. if not os.path.exists(s_path_url):
  218. os.makedirs(s_path_url)
  219. if not os.path.exists(t_path_url):
  220. os.makedirs(t_path_url)
  221. if not os.path.exists(v_path_url):
  222. os.makedirs(v_path_url)
  223. # srt 文件地址
  224. s_path = s_path_url + mark + ".srt"
  225. # txt 文件地址
  226. t_path = t_path_url + mark + ".txt"
  227. # 最终生成视频地址
  228. v_path = v_path_url + mark + ".mp4"
  229. if os.path.isfile(v_path):
  230. os.remove(v_path)
  231. if os.path.isfile(t_path):
  232. os.remove(t_path)
  233. if os.path.isfile(s_path):
  234. os.remove(s_path)
  235. # 清空所有mp4数据
  236. cls.clear_mp4_files(video_path_url)
  237. return s_path, t_path, v_path, video_path_url
  238. # 视频拼接
  239. @classmethod
  240. def concatenate_videos(cls, videos, audio_duration, audio_video, platform, s_path, v_path, mark, t_path):
  241. video_files = cls.concat_videos_with_subtitles(videos, audio_duration, platform, mark)
  242. Common.logger("video").info(f"{mark}的{platform}渠道待生成视频为:{video_files}")
  243. if video_files == "":
  244. return ""
  245. print(f"{mark}的{platform}:开始拼接视频喽~~~")
  246. Common.logger("video").info(f"{mark}的{platform}:开始拼接视频喽~~~")
  247. # 将使用视频写入文件中
  248. with open(f'{t_path}', 'w') as f:
  249. for video_file in video_files:
  250. f.write(f"file '{video_file[3]}'\n")
  251. # 字幕参数
  252. if os.path.exists(s_path):
  253. # subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=11,Fontname=Hiragino Sans GB,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
  254. subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=12,Fontname=wqy-zenhei,Bold=1,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
  255. else:
  256. # subtitle_cmd = "drawtext=text='分享、转发给群友':fontsize=28:fontcolor=black:x=(w-text_w)/2:y=h-text_h-15"
  257. 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"
  258. # 背景色参数
  259. background_cmd = "drawbox=y=ih-65:color=yellow@1.0:width=iw:height=0:t=fill"
  260. # 分辨率参数
  261. resolution_cmd = "-s", "320x480"
  262. # 多线程数
  263. num_threads = 8
  264. # 构建 FFmpeg 命令,生成视频
  265. ffmpeg_cmd = [
  266. "ffmpeg",
  267. "-f", "concat",
  268. "-safe", "0",
  269. "-i", f"{t_path}", # 视频文件列表
  270. "-i", audio_video, # 音频文件
  271. "-pix_fmt", "yuv420p",
  272. "-movflags", "faststart",
  273. "-keyint_min", str(23.97),
  274. "-g", str(23.97),
  275. "-sc_threshold", "0",
  276. "-strict", "experimental",
  277. "-threads", str(num_threads),
  278. "-c:v", "libx264",
  279. "-c:a", "aac",
  280. "-vf", f"scale=320x480,{background_cmd},{subtitle_cmd}", # 添加背景色和字幕
  281. *resolution_cmd, # 添加分辨率参数
  282. "-b:v", "5M", # 设置可变比特率
  283. "-maxrate", "10M", # 设置最大比特率
  284. "-bufsize", "5M", # 设置缓冲大小
  285. "-crf", "23", # 设置CRF(恒定质量)
  286. "-r", "30", # 设置帧率为30帧每秒
  287. "-vsync", "cfr", # 设置视频同步策略为可变帧率
  288. "-t", str(int(audio_duration)), # 保持与音频时长一致
  289. "-map", "0:v:0", # 映射第一个输入的视频流
  290. "-map", "1:a:0", # 映射第二个输入的音频流
  291. "-y", # 覆盖输出文件
  292. v_path
  293. ]
  294. # 构建 FFmpeg 命令,添加字幕
  295. # 执行 FFmpeg 命令
  296. try:
  297. subprocess.run(ffmpeg_cmd, check=True)
  298. print("视频处理完成!")
  299. except subprocess.CalledProcessError as e:
  300. print(f"视频处理失败:{e}")
  301. print(f"{mark}的{platform}:视频拼接成功啦~~~")
  302. Common.logger("video").info(f"{mark}的{platform}:视频拼接成功啦~~~")
  303. return video_files
  304. @classmethod
  305. def video_stitching(cls, ex_list):
  306. pq_ids = ex_list["pq_id"]
  307. pq_ids_list = pq_ids.split(',')
  308. mark_name = ex_list['mark_name']
  309. mark = ex_list["mark"]
  310. feishu_id = ex_list["feishu_id"]
  311. video_call = ex_list["video_call"]
  312. parts = video_call.split(',')
  313. result = []
  314. for part in parts:
  315. sub_parts = part.split('--')
  316. result.append(sub_parts)
  317. link = result[0][0]
  318. yhmw_all_count = result[0][1]
  319. if int(yhmw_all_count) == 0:
  320. yhmw_count = 0
  321. else:
  322. yhmw_count = int(int(yhmw_all_count)/2)
  323. # 如果没有该文件目录则创建,有文件目录的话 则删除文件
  324. s_path, t_path, v_path, video_path_url= cls.create_folders(mark)
  325. kb_count = int(result[1][1])
  326. channel = ['douyin', 'kuaishou', 'koubo']
  327. try:
  328. for platform in channel:
  329. limit_count = 40
  330. count = cls.get_link_count(mark, platform)
  331. if platform == "douyin" and count >= yhmw_count:
  332. continue
  333. elif platform == "kuaishou" and count >= yhmw_count:
  334. continue
  335. elif platform == "koubo":
  336. link = result[1][0]
  337. limit_count = 1
  338. if count >= kb_count or kb_count == 0:
  339. Feishu.bot('recommend', 'AGC完成通知', '今日自制视频拼接任务完成啦~', mark, mark_name)
  340. return mark
  341. # 获取音频类型+字幕+标题
  342. uid, srt, title_list = Material.get_all_data(feishu_id, link, mark)
  343. # 获取已入库的用户id
  344. user_id = cls.get_user_id(platform, mark)
  345. if user_id:
  346. user = random.choice(user_id)
  347. else:
  348. Common.logger("video").info(f"{mark}的{platform} 渠道无抓取的数据")
  349. return ""
  350. user = str(user).replace('(', '').replace(')', '').replace(',', '')
  351. Common.logger("video").info(f"{mark}的{platform}渠道获取的用户ID:{user}")
  352. # 获取 未使用的视频链接
  353. url_list = cls.get_url_list(user, mark, limit_count)
  354. if url_list == None:
  355. Common.logger("video").info(f"未使用视频链接为空:{url_list}")
  356. return ''
  357. videos = [list(item) for item in url_list]
  358. # 下载视频
  359. videos = Oss.get_oss_url(videos, video_path_url)
  360. if srt:
  361. # 创建临时字幕文件
  362. cls.create_subtitle_file(srt, s_path)
  363. Common.logger("video").info(f"S{mark}的{platform}渠道RT 文件目录创建成功")
  364. # 获取音频
  365. audio_video = cls.get_audio_url(uid, mark, mark_name)
  366. Common.logger("video").info(f"{mark}的{platform}渠道获取需要拼接的音频成功")
  367. # 获取音频秒数
  368. audio_duration = cls.get_audio_duration(audio_video)
  369. Common.logger("video").info(f"{mark}的{platform}渠道获取需要拼接的音频秒数为:{audio_duration}")
  370. video_files = cls.concatenate_videos(videos, audio_duration, audio_video, platform, s_path, v_path, mark, t_path)
  371. if video_files == "":
  372. Common.logger("video").info(f"{mark}的{platform}渠道使用拼接视频为空")
  373. return ""
  374. if os.path.isfile(v_path):
  375. Common.logger("video").info(f"{mark}的{platform}渠道新视频生成成功")
  376. else:
  377. Common.logger("video").info(f"{mark}的{platform}渠道新视频生成失败")
  378. return ""
  379. # 随机生成视频oss_id
  380. oss_id = cls.random_id()
  381. # 获取新生成视频时长
  382. v_path_duration = cls.get_audio_duration(v_path)
  383. if v_path_duration > audio_duration+3 or v_path_duration < audio_duration-3:
  384. print(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒")
  385. Common.logger("video").info(f"{mark}的{platform}渠道最终生成视频秒数错误,生成了:{v_path_duration}秒")
  386. return ""
  387. # 上传 oss
  388. Common.logger("video").info(f"{mark}的{platform}渠道上传到 OSS 生成视频id为:{oss_id}")
  389. oss_object_key = Oss.stitching_sync_upload_oss(v_path, oss_id)
  390. status = oss_object_key.get("status")
  391. if status == 200:
  392. # 获取 oss 视频地址
  393. oss_object_key = oss_object_key.get("oss_object_key")
  394. Common.logger("video").info(f"{mark}的{platform}渠道拼接视频发送成功,OSS 地址:{oss_object_key}")
  395. time.sleep(10)
  396. # 已使用视频存入数据库
  397. Common.logger("video").info(f"{mark}的{platform}渠道开始已使用视频存入数据库")
  398. cls.insert_videoAudio(video_files, uid, platform, mark)
  399. Common.logger("video").info(f"{mark}的{platform}渠道完成已使用视频存入数据库")
  400. Common.logger("video").info(f"{mark}的{platform}渠道开始视频添加到对应用户")
  401. piaoquantv = cls.insert_piaoquantv(oss_object_key, title_list, pq_ids_list)
  402. if piaoquantv:
  403. Common.logger("video").info(f"{mark}的{platform}渠道视频添加到对应用户成功")
  404. return ''
  405. except Exception as e:
  406. Common.logger("video").warning(f"{mark}的视频拼接失败:{e}\n")
  407. return ''