Przeglądaj źródła

增加 分享引导

zhangyong 1 rok temu
rodzic
commit
ff8b1bab7c
6 zmienionych plików z 266 dodań i 208 usunięć
  1. 57 10
      common/feishu_form.py
  2. 105 118
      common/ffmpeg.py
  3. 8 5
      common/piaoquan_utils.py
  4. 5 8
      common/sql_help.py
  5. 14 12
      video_job.py
  6. 77 55
      video_rewriting/video_prep.py

+ 57 - 10
common/feishu_form.py

@@ -22,7 +22,9 @@ class Material():
             name = row[1]
             feishu_id = row[3]
             feishu_sheet = row[4]
-            number = {"mark": mark, "name": name, "feishu_id": feishu_id, "feishu_sheet": feishu_sheet}
+            pw_sheet = row[5]
+
+            number = {"mark": mark, "name": name, "feishu_id": feishu_id, "feishu_sheet": feishu_sheet, "pw_sheet": pw_sheet}
             if mark:
                 list.append(number)
             else:
@@ -35,21 +37,66 @@ class Material():
     @classmethod
     def get_task_data(cls, feishu_id, feishu_sheet):
         data = Feishu.get_values_batch(feishu_id, feishu_sheet)
-        list = []
+        processed_list = []
+
         for row in data[1:]:
-            task_mark = row[0]
             old_id = row[1]
             video_id = row[2]
             new_id = row[3]
             number = row[4]
-            title = row[5]
-            if new_id != 'None' and new_id != '' and new_id != None:
-                number = {"task_mark": task_mark, "old_id": old_id, "video_id": video_id, "new_id": new_id,
-                          "number": number, "title": title}
-                list.append(number)
+            video_share = row[5]
+            video_ending = row[6]
+            title = row[7]
+
+            def count_items(item, separator):
+                if item and item not in {'None', ''}:
+                    return len(item.split(separator))
+                return 0
+
+            old_id_total = count_items(str(old_id), ',')
+            video_id_total = count_items(str(video_id), ',')
+            new_id_total = count_items(str(new_id), ',')
+            title_total = count_items(str(title), '/')
+
+            values = [old_id_total, video_id_total, new_id_total, video_share, video_ending, title_total]
+            task_mark = "_".join(map(str, values))
+
+            if new_id and new_id not in {'None', ''}:
+                number_dict = {
+                    "task_mark": task_mark,
+                    "old_id": old_id,
+                    "video_id": video_id,
+                    "new_id": new_id,
+                    "number": number,
+                    "title": title,
+                    "video_share": video_share,
+                    "video_ending": video_ending
+                }
+                processed_list.append(number_dict)
             else:
-                return list
-        return list
+                return processed_list
+
+        return processed_list
+
+    """
+    获取对应负责人下的片尾+固定字幕
+    """
+    @classmethod
+    def get_pwsrt_data(cls, feishu_id, feishu_sheet):
+        data = Feishu.get_values_batch(feishu_id, feishu_sheet)
+        list = []
+        zm_list = []
+        for row in data[1:]:
+            pw_id = row[0]
+            pw_srt = row[1]
+            zm_video = row[2]
+            if pw_id != 'None' and pw_id != '' and pw_id != None:
+                number = {"pw_id": pw_id, "pw_srt": pw_srt}
+                list.append(number)
+            if zm_video != 'None' and zm_video != '' and zm_video != None:
+                zm_list.append(zm_video)
+        return list, zm_list
+
 
 
 

+ 105 - 118
common/ffmpeg.py

@@ -15,6 +15,17 @@ from urllib.parse import urlencode
 
 class FFmpeg():
 
+    """
+    时间转换
+    """
+    @classmethod
+    def seconds_to_srt_time(cls, seconds):
+        hours = int(seconds // 3600)
+        minutes = int((seconds % 3600) // 60)
+        seconds = seconds % 60
+        milliseconds = int((seconds - int(seconds)) * 1000)
+        return f"{hours:02d}:{minutes:02d}:{int(seconds):02d},{milliseconds:03d}"
+
     """
     获取单个视频时长
     """
@@ -47,82 +58,99 @@ class FFmpeg():
     @classmethod
     def video_tailor(cls, video_url):
         output_video_path = ''
-        # 获取视频的原始宽高信息
-        ffprobe_cmd = f"ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 {video_url}"
-        ffprobe_process = subprocess.Popen(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
-        output, _ = ffprobe_process.communicate()
-        width, height = map(int, output.decode().strip().split(','))
-        # 计算裁剪后的高度
-        new_height = int(height * 0.7)
-
-        # 构建 FFmpeg 命令,裁剪视频高度为原始高度的70%,并将宽度缩放为320x480
-        ffmpeg_cmd = [
-            "ffmpeg",
-            "-i", video_url,
-            "-vf", f"crop={width}:{new_height},scale=320:480",
-            "-c:v", "libx264",
-            "-c:a", "aac",
-            "-y",
-            output_video_path
-        ]
-
-        # 执行 FFmpeg 命令
-        subprocess.run(ffmpeg_cmd)
-        return output_video_path
+        try:
+            # 获取视频的原始宽高信息
+            ffprobe_cmd = f"ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 {video_url}"
+            ffprobe_process = subprocess.Popen(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+            output, _ = ffprobe_process.communicate()
+            width, height = map(int, output.decode().strip().split(','))
+            # 计算裁剪后的高度
+            new_height = int(height * 0.7)
+            # 构建 FFmpeg 命令,裁剪视频高度为原始高度的70%,并将宽度缩放为320x480
+            ffmpeg_cmd = [
+                "ffmpeg",
+                "-i", video_url,
+                "-vf", f"crop={width}:{new_height},scale=320:480",
+                "-c:v", "libx264",
+                "-c:a", "aac",
+                "-y",
+                output_video_path
+            ]
+            # 执行 FFmpeg 命令
+            subprocess.run(ffmpeg_cmd, check=True)
+            return output_video_path
+        except Exception as e:
+            return None
 
     """
      截取原视频最后一帧
     """
     @classmethod
-    def video_png(cls,video_url):
+    def video_png(cls, new_video_path, video_path_url):
         """
-        png 生成图片位置
-        :param video_url: 视频地址
+        jpg_url 生成图片位置
+        :param new_video_path: 视频地址
         :return:
         """
-        png = ''
-        # 获取视频时长
-        total_duration = cls.get_video_duration(video_url)
-        time_offset = total_duration - 1  # 提取倒数第一秒的帧
-        # 获取视频最后一秒,生成.jpg
-        subprocess.run(
-            ['ffmpeg', '-ss', str(time_offset), '-i', video_url, '-t', str(total_duration), '-vf', 'fps=1', png])
-        return png
+        try:
+            jpg_url = video_path_url + 'png.jpg'
+            # 获取视频时长
+            total_duration = cls.get_video_duration(new_video_path)
+            time_offset = total_duration - 1  # 提取倒数第一秒的帧
+            # 获取视频最后一秒,生成.jpg
+            subprocess.run(
+                ['ffmpeg', '-ss', str(time_offset), '-i', new_video_path, '-t', str(total_duration), '-vf', 'fps=1', "-y", jpg_url])
+            return jpg_url
+
+        except Exception as e:
+            return None
 
     """
      生成片尾视频
     """
     @classmethod
-    def new_pw_video(cls):
+    def pw_video(cls, jpg_url, video_path_url, pw_url, pw_srt):
         # 添加音频到图片
         """
-        png_path 图片地址
+        jpg_url 图片地址
         pw_video 提供的片尾视频
         pw_duration  提供的片尾视频时长
-        background_cmd 视频位置
+        new_video_path 视频位置
         subtitle_cmd 字幕
-        pw_path 生成视频地址
+        pw_url 生成视频地址
         :return:
         """
-        ffmpeg_cmd = ['ffmpeg', '-loop', '1', '-i', png_path, '-i', pw_video, '-c:v', 'libx264', '-t',
+        pw_srt_path = video_path_url + 'pw_video.srt'
+        # 创建临时字幕文件
+        with open(pw_srt_path, 'w') as f:
+            f.write(pw_srt)
+        # 片尾位置
+        pw_url_path = video_path_url + 'pw_video.mp4'
+        # 获取视频时长
+        pw_duration = cls.get_video_duration(pw_url)
+        # 添加字幕 wqy-zenhei  Hiragino Sans GB
+        subtitle_cmd = f"subtitles={pw_srt_path}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV=155'"
+        background_cmd = "drawbox=y=366/2:color=yellow@1.0:width=iw:height=50:t=fill"
+        ffmpeg_cmd = ['ffmpeg', '-loop', '1', '-i', jpg_url, '-i', pw_url, '-c:v', 'libx264', '-t',
                       str(pw_duration), '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-strict', 'experimental', '-shortest',
-                      '-vf', f"scale=320x480,{background_cmd},{subtitle_cmd}", pw_path]
+                      '-vf', f"scale=320x480,{background_cmd},{subtitle_cmd}", pw_url_path]
         subprocess.run(ffmpeg_cmd)
-        return pw_path
+        return pw_url_path
 
 
     """
     设置统一格式拼接视频
     """
     @classmethod
-    def concatenate_videos(cls, video_files, concatenated_video_path):
+    def concatenate_videos(cls, video_list, video_path_url):
+        concatenate_videos_url = video_path_url + 'concatenate_videos.mp4'
         # 拼接视频
         VIDEO_COUNTER = 0
         FF_INPUT = ""
         FF_SCALE = ""
         FF_FILTER = ""
         ffmpeg_cmd = ["ffmpeg"]
-        for videos in video_files:
+        for videos in video_list:
             # 添加输入文件
             FF_INPUT += f" -i {videos}"
             # 为每个视频文件统一长宽,并设置SAR(采样宽高比)
@@ -134,95 +162,54 @@ class FFmpeg():
         # 构建最终的FFmpeg命令
         ffmpeg_cmd.extend(FF_INPUT.split())
         ffmpeg_cmd.extend(["-filter_complex", f"{FF_SCALE}{FF_FILTER}concat=n={VIDEO_COUNTER}:v=1:a=1[v][a]",
-                           "-map", "[v]", "-map", "[a]", concatenated_video_path])
+                           "-map", "[v]", "-map", "[a]", "-y", concatenate_videos_url])
         subprocess.run(ffmpeg_cmd)
-
-        return concatenated_video_path
+        return concatenate_videos_url
 
 
     """
     单个视频拼接
     """
     @classmethod
-    def single_video(cls):
-        text_ptah = cls.bk_text_folders(mark)
-        video_files = cls.concat_videos_with_subtitles(videos, audio_duration, platform, mark)
-        with open(text_ptah, 'w') as f:
-            for file in video_files:
-                f.write(f"file '{file}'\n")
-        if video_files == "":
-            return ""
-        if os.path.exists(s_path):
-            # subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=11,Fontname=Hiragino Sans GB,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
-            subtitle_cmd = f"subtitles={s_path}:force_style='Fontsize=12,Fontname=wqy-zenhei,Bold=1,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000'"
+    def single_video(cls, new_video_path, video_share, video_path_url, zm):
+        single_video_url = video_path_url + 'single_video.mp4'
+        single_video_srt = video_path_url + 'single_video.srt'
+        # 获取时长
+        duration = cls.get_video_duration(new_video_path)
+        start_time = cls.seconds_to_srt_time(0)
+        end_time = cls.seconds_to_srt_time(duration)
+        single_video_txt = video_path_url + 'single_video.txt'
+        with open(single_video_txt, 'w') as f:
+            f.write(f"file '{new_video_path}'\n")
+        with open(single_video_srt, 'w') as f:
+            f.write(f"1\n{start_time} --> {end_time}\n\u2764\uFE0F{zm}\n\n")
+        background_cmd = "drawbox=y=370/1:color=yellow@1.0:width=iw:height=70:t=fill"
+        if video_share == '有':
+            # 添加字幕 wqy-zenhei  Hiragino Sans GB
+            subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV=30'"
+            draw = f"{background_cmd},{subtitle_cmd}"
         else:
-            # subtitle_cmd = "drawtext=text='分享、转发给群友':fontsize=28:fontcolor=black:x=(w-text_w)/2:y=h-text_h-15"
-            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"
-        # 背景色参数
-        background_cmd = "drawbox=y=ih-65:color=yellow@1.0:width=iw:height=0:t=fill"
+            subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=30'"
+            draw = f"{subtitle_cmd}"
         # 多线程数
         num_threads = 4
         # 构建 FFmpeg 命令,生成视频
         ffmpeg_cmd_oss = [
-            "ffmpeg",
-            "-f", "concat",
-            "-safe", "0",
-            "-i", f"{text_ptah}",  # 视频文件列表
-            "-i", audio_video,  # 音频文件
-            "-c:v", "libx264",
-            "-c:a", "aac",
-            "-threads", str(num_threads),
-            "-vf", f"scale=320x480,{background_cmd},{subtitle_cmd}",  # 添加背景色和字幕
-            "-t", str(int(audio_duration)),  # 保持与音频时长一致
-            "-map", "0:v:0",  # 映射第一个输入的视频流
-            "-map", "1:a:0",  # 映射第二个输入的音频流
-            "-y",  # 覆盖输出文件
-            v_oss_path
+                "ffmpeg",
+                "-f", "concat",
+                "-safe", "0",
+                "-i",  f"{single_video_txt}",
+                "-c:v", "libx264",
+                "-c:a", "aac",
+                "-threads", str(num_threads),
+                "-vf", f"scale=320x480,{draw}",
+                 "-y",
+                 single_video_url
+
         ]
-        try:
-            subprocess.run(ffmpeg_cmd_oss)
-            print("视频处理完成!")
-            if os.path.isfile(text_ptah):
-                os.remove(text_ptah)
-        except subprocess.CalledProcessError as e:
-            print(f"视频处理失败:{e}")
-        print(f"{mark}:视频拼接成功啦~~~")
-        return video_files
-
-    # 计算需要拼接的视频
-    @classmethod
-    def concat_videos_with_subtitles(cls, videos, audio_duration, platform, mark):
-        # 计算视频文件列表总时长
-        if platform == "baokuai":
-            total_video_duration = sum(cls.get_video_duration(video_file) for video_file in videos)
-        else:
-            total_video_duration = sum(cls.get_video_duration(video_file[3]) for video_file in videos)
-        if platform == "koubo" or platform == "zhannei" or platform == "baokuai":
-            # 视频时长大于音频时长
-            if total_video_duration > audio_duration:
-                return videos
-            # 计算音频秒数与视频秒数的比率,然后加一得到需要的视频数量
-            video_audio_ratio = audio_duration / total_video_duration
-            videos_needed = int(video_audio_ratio) + 2
-            trimmed_video_list = videos * videos_needed
-            return trimmed_video_list
-        else:
-            # 如果视频总时长小于音频时长,则不做拼接
-            if total_video_duration < audio_duration:
-                return ""
-            # 如果视频总时长大于音频时长,则截断视频
-            trimmed_video_list = []
-            remaining_duration = audio_duration
-            for video_file in videos:
-                video_duration = cls.get_video_duration(video_file[3])
-                if video_duration <= remaining_duration:
-                    # 如果视频时长小于或等于剩余时长,则将整个视频添加到列表中
-                    trimmed_video_list.append(video_file)
-                    remaining_duration -= video_duration
-                else:
-                    trimmed_video_list.append(video_file)
-                    break
-            return trimmed_video_list
+        subprocess.run(ffmpeg_cmd_oss)
+        return single_video_url
+
 
 
 

+ 8 - 5
common/piaoquan_utils.py

@@ -14,7 +14,7 @@ class PQ:
      获取视频链接
     """
     @classmethod
-    def get_audio_url(cls, task_mark, user_id, title):
+    def get_audio_url(cls, task_mark, user_id, title, mark):
         url = f"https://admin.piaoquantv.com/manager/video/detail/{user_id}"
         payload = {}
         headers = {
@@ -39,7 +39,10 @@ class PQ:
         try:
             list = []
             video_id = data["content"]["id"]
-            status = sqlCollect.is_used(task_mark, video_id)
+            if mark:
+                status = sqlCollect.is_used(task_mark, video_id, mark)
+            else:
+                status = True
             if status:
                 if title == '' or title == None:
                     new_title = data["content"]["title"]
@@ -63,8 +66,8 @@ class PQ:
     获取用户下的所有视频
     """
     @classmethod
-    def get_user_url(cls, task_mark, user_id, number, title):
-        url = f"https://admin.piaoquantv.com/manager/video/page?uid={user_id}&pageNum=1&pageSize=50"
+    def get_user_url(cls, task_mark, user_id, number, title, mark):
+        url = f"https://admin.piaoquantv.com/manager/video/page?uid={user_id}&pageNum=1&pageSize=100"
 
         payload = {}
         headers = {
@@ -80,7 +83,7 @@ class PQ:
             list = []
             for url in content:
                 video_id = url["id"]
-                status = sqlCollect.is_used(task_mark, video_id)
+                status = sqlCollect.is_used(task_mark, video_id, mark)
                 if status:
                     if title == '' or title == None:
                         new_title = url["title"]

+ 5 - 8
common/sql_help.py

@@ -14,10 +14,10 @@ class sqlCollect():
     视频信息写入库中
     """
     @classmethod
-    def insert_task(cls, task_mark, video_id):
+    def insert_task(cls, task_mark, video_id, mark):
         current_time = datetime.now()
         formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
-        insert_sql = f"""INSERT INTO pj_video_data (task_name, used_video_id, data_time) values ('{task_mark}' ,'{video_id}', '{formatted_time}')"""
+        insert_sql = f"""INSERT INTO pj_video_data (task_name, used_video_id, mark_name, data_time) values ('{task_mark}' ,'{video_id}','{mark}', '{formatted_time}')"""
         MysqlHelper.update_values(
             sql=insert_sql
         )
@@ -26,18 +26,15 @@ class sqlCollect():
     判断该任务id是否用过
     """
     @classmethod
-    def is_used(cls, task_mark, video_id):
-        current_time = datetime.now()
-        three_days_ago = current_time - timedelta(days=3)
-        formatted_time = three_days_ago.strftime("%Y-%m-%d")
+    def is_used(cls, task_mark, video_id, mark_name):
         sql = """
             SELECT used_video_id
             FROM pj_video_data
-            WHERE used_video_id = %s AND task_name = %s AND data_time >= %s
+            WHERE used_video_id = %s AND task_name = %s AND mark_name = %s 
             ORDER BY data_time DESC
             LIMIT 1
         """
-        data = MysqlHelper.get_values(sql, (str(video_id), task_mark, formatted_time))
+        data = MysqlHelper.get_values(sql, (str(video_id), task_mark, mark_name))
         if len(data) == 0 or data == ():
             return True
         return False

+ 14 - 12
video_job.py

@@ -7,7 +7,7 @@ import time
 import threading
 from common import Material, Common, Feishu
 # 控制读写速度的参数
-from video_rewriting.video_data import getVideo
+from video_rewriting.video_prep import getVideo
 
 MAX_BPS = 120 * 1024 * 1024  # 120MB/s
 MAX_WORKERS = os.cpu_count() * 2  # 线程池最大工作线程数量
@@ -68,20 +68,22 @@ def video_start():
 
 def usernames_today():
     today.clear()
-    print("gs_usernames_today 已清空")
+    print("today 已清空")
 
 
-# video_start()
+video_start()
 
 
-# 定时任务设置
-schedule.every().day.at("01:00").do(usernames_today)
+# # 定时任务设置
+# schedule.every().day.at("01:00").do(usernames_today)
+#
+#
+# schedule.every(12).hours.do(video_start)
+#
+#
+#
+# while True:
+#     schedule.run_pending()
+#     time.sleep(1)
 
 
-schedule.every(12).hours.do(video_start)
-
-
-
-while True:
-    schedule.run_pending()
-    time.sleep(1)

+ 77 - 55
video_rewriting/video_data.py → video_rewriting/video_prep.py

@@ -1,18 +1,19 @@
 import configparser
 import os
 import random
-
 import time
-
-
 from datetime import datetime
+
 from common import Material, Feishu, Common, Oss
+from common.ffmpeg import FFmpeg
 from common.piaoquan_utils import PQ
 from common.sql_help import sqlCollect
 
 config = configparser.ConfigParser()
-config.read('./config.ini')  # 替换为您的配置文件路径
-class getVideo():
+config.read('./config.ini')
+
+
+class getVideo:
 
     """
     数据处理
@@ -22,11 +23,11 @@ class getVideo():
         pass
 
     """
-    创建目录
+    根据标示+任务标示创建目录
     """
     @classmethod
-    def create_folders(cls, task_mark):
-        video_path_url = config['PATHS']['VIDEO_PATH'] + task_mark + "/"
+    def create_folders(cls, mark, task_mark):
+        video_path_url = config['PATHS']['VIDEO_PATH'] + mark + "/" + task_mark + "/"
         if not os.path.exists(video_path_url):
             os.makedirs(video_path_url)
         return video_path_url
@@ -40,6 +41,10 @@ class getVideo():
         rand_num = random.randint(10000, 99999)
         oss_id = "{}{}".format(now.strftime("%Y%m%d%H%M%S"), rand_num)
         return oss_id
+
+
+
+
     """
     飞书数据处理
     """
@@ -49,96 +54,113 @@ class getVideo():
         name = data["name"]
         feishu_id = data["feishu_id"]
         feishu_sheet = data["feishu_sheet"]
+        pw_sheet = data["pw_sheet"]
+
         task_data = Material.get_task_data(feishu_id, feishu_sheet)
         if len(task_data) == 0:
             Feishu.bot(mark, '机器自动改造消息通知', f'今日任务为空,请关注', name)
             return mark
-        for task in task_data:
-            task_mark = task["task_mark"]
+
+        for task in task_data[0]:
+            task_mark = task["task_mark"]  # 任务标示
             old_id = str(task["old_id"])
             video_id = str(task["video_id"])
             new_id = str(task["new_id"])
 
-            number = task["number"] #指定条数
+            number = task["number"]  # 指定条数
             title = task["title"]
+            video_share = task["video_share"]
+            video_ending = task["video_ending"]
+
             try:
-                video_path_url = cls.create_folders(str(task_mark))
+                video_path_url = cls.create_folders(mark, str(task_mark))  # 创建目录
                 if ',' in new_id:
                     n_id = new_id.split(',')
                 else:
                     n_id = [new_id]
-                if old_id != 'None' and old_id != '' and old_id != None:
-                    if ',' in old_id:
-                        task_id = old_id.split(',')
-                    else:
-                        task_id = [old_id]
+                if old_id and old_id != 'None':
+                    task_id = old_id.split(',')
                 else:
-                    if ',' in video_id:
-                        task_id = video_id.split(',')
-                    else:
-                        task_id = [video_id]
+                    task_id = video_id.split(',')
+                count = 0  # 初始化计数器
                 for id in task_id:
                     time.sleep(1)
-                    if old_id != 'None' and old_id != '' and old_id != None:
-                        data_list = PQ.get_user_url(task_mark, id, number, title)
+                    if old_id and old_id != 'None':
+                        data_list = PQ.get_user_url(task_mark, id, number, title, mark)
                     else:
-                        data_list = PQ.get_audio_url(task_mark, id, title)
-                    if len(data_list) == 0 or data_list == "":
-                        Common.logger("log").info(f"{task_mark}下的视频ID{id} 近三天已经改造过了")
-                        Feishu.bot(mark, '机器自动改造消息通知', f'{task_mark}任务下的视频ID{id},近三天已经改造过,请关注', name)
+                        data_list = PQ.get_audio_url(task_mark, id, title, mark)
+
+                    if not data_list:
+                        Common.logger("log").info(f"{task_mark}下的视频ID{id} 已经改造过了")
+                        Feishu.bot(mark, '机器自动改造消息通知', f'{task_mark}任务下的视频ID{id},已经改造过,请关注', name)
                         continue
+
                     for video in data_list:
                         v_id = video["video_id"]
                         new_title = video["title"]
                         cover = video["cover"]
                         video_url = video["video_url"]
-                        new_video_path = PQ.download_video(video_url, video_path_url, v_id)
-                        if len(new_video_path) == 0 or new_video_path == "":
+                        new_video_path = PQ.download_video(video_url, video_path_url, v_id)  # 下载视频地址
+                        if not new_video_path:
                             Common.logger("log").info(f"{task_mark}下的视频ID{id},{new_video_path}视频下载失败")
                             continue
+                        pw_list, zm_list = Material.get_pwsrt_data(feishu_id, pw_sheet)  # 获取srt
+                        pws = random.choice(pw_list)  # 随机选择 片尾srt+音频
+                        zm = random.choice(zm_list)  # 随机选择 视频中字幕
+                        if video_share and video_share != 'None':
+                            new_video_path = FFmpeg.single_video(new_video_path, video_share, video_path_url, zm)
+                        if video_ending and video_ending != 'None':
+                            pw_id = pws["pw_id"]
+                            pw_srt = pws["pw_srt"]
+                            pw_url = PQ.get_audio_url(task_mark, pw_id, title, mark)
+                            jpg_path = FFmpeg.video_png(new_video_path, video_path_url)  # 生成视频最后一帧jpg
+                            pw_path = FFmpeg.pw_video(jpg_path, video_path_url, pw_url[0]["video_url"], pw_srt)  # 生成片尾视频
+                            video_list = [new_video_path, pw_path]
+                            video_path = FFmpeg.concatenate_videos(video_list, video_path_url)  # 视频与片尾拼接到一起
+                            if video_share and video_share != 'None':
+                                new_video_path = FFmpeg.single_video(video_path, video_share, video_path_url, zm)
+                            else:
+                                new_video_path = video_path
+                        else:
+                            if video_share and video_share != 'None':
+                                new_video_path = FFmpeg.single_video(new_video_path, video_share, video_path_url, zm)
                         oss_id = cls.random_id()
                         oss_object_key = Oss.stitching_sync_upload_oss(new_video_path, oss_id)  # 视频发送OSS
                         status = oss_object_key.get("status")
+
                         if status == 200:
-                            # 获取 oss 视频地址
                             oss_object_key = oss_object_key.get("oss_object_key")
                             time.sleep(1)
-                            code = PQ.insert_piaoquantv(oss_object_key, new_title, cover, n_id[0])
+                            code = PQ.insert_piaoquantv(oss_object_key, new_title, cover, n_id[count])
+
                             if code:
                                 Common.logger("log").info(f"{task_mark}下的视频ID{v_id}发送成功")
-                                sqlCollect.insert_task(task_mark, v_id)  # 插入数据库
+                                sqlCollect.insert_task(task_mark, v_id, mark)  # 插入数据库
                                 current_time = datetime.now()
                                 formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
-                                values = [[
-                                    name, task_mark, v_id, n_id[0], new_title, str(code), formatted_time
-                                ]]
+                                values = [[name, task_mark, v_id, n_id[count], new_title, str(code), formatted_time]]
                                 Feishu.insert_columns("ILb4sa0LahddRktnRipcu2vQnLb", "a74fc4", "ROWS", 1, 2)
                                 time.sleep(0.5)
                                 Feishu.update_values("ILb4sa0LahddRktnRipcu2vQnLb", "a74fc4", "A2:Z2", values)
-                            if os.path.isfile(new_video_path):
-                                os.remove(new_video_path)
+
+                            if os.path.exists(video_path_url) and os.path.isdir(video_path_url):
+                                for root, dirs, files in os.walk(video_path_url):
+                                    for file in files:
+                                        file_path = os.path.join(root, file)
+                                        os.remove(file_path)
+                                    for dir in dirs:
+                                        dir_path = os.path.join(root, dir)
+                                        os.rmdir(dir_path)
                         else:
                             Common.logger("log").info(f"{task_mark}下的视频ID{id} 视频发送OSS失败 ")
-                    if old_id != 'None' and old_id != '' and old_id != None:
+                    count += 1  # 每次迭代计数器加1
+                    if old_id and old_id != 'None':
                         Feishu.bot(mark, '机器自动改造消息通知', f'{task_mark}任务改造完成,请关注', name)
-                if video_id != 'None' and video_id != '' and video_id != None:
+
+                if video_id and video_id != 'None':
                     Feishu.bot(mark, '机器自动改造消息通知', f'{task_mark}任务改造完成,请关注', name)
+
             except Exception as e:
                 Common.logger("warning").warning(f"{name}的{task_mark}任务处理失败:{e}\n")
-        return mark
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 
+        return mark