利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
refactor: optimize codebase for better performance and reliability
Claude44096d608651
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.pyindex e80d7626..1c802b30 100644--- a/app/controllers/v1/video.py+++ b/app/controllers/v1/video.py@@ -131,7 +131,7 @@ def get_task(def file_to_uri(file):if not file.startswith(endpoint):- _uri_path = v.replace(task_dir, "tasks").replace("\\", "/")+ _uri_path = file.replace(task_dir, "tasks").replace("\\", "/")_uri_path = f"{endpoint}/{_uri_path}"else:_uri_path = filediff --git a/app/services/material.py b/app/services/material.pyindex ae631fd2..70ef4764 100644--- a/app/services/material.py+++ b/app/services/material.py@@ -1,5 +1,6 @@import osimport random+import threadingfrom typing import Listfrom urllib.parse import urlencode@@ -11,7 +12,9 @@ from app.config import configfrom app.models.schema import MaterialInfo, VideoAspect, VideoConcatModefrom app.utils import utils-requested_count = 0+# Thread-safe counter for API key rotation+_api_key_counter = 0+_api_key_lock = threading.Lock()def get_api_key(cfg_key: str):@@ -26,9 +29,10 @@ def get_api_key(cfg_key: str):if isinstance(api_keys, str):return api_keys- global requested_count- requested_count += 1- return api_keys[requested_count % len(api_keys)]+ global _api_key_counter+ with _api_key_lock:+ _api_key_counter += 1+ return api_keys[_api_key_counter % len(api_keys)]def search_videos_pexels(@@ -178,19 +182,25 @@ def save_video(video_url: str, save_dir: str = "") -> str:)if os.path.exists(video_path) and os.path.getsize(video_path) > 0:+ clip = Nonetry:clip = VideoFileClip(video_path)duration = clip.durationfps = clip.fps- clip.close()if duration > 0 and fps > 0:return video_pathexcept Exception as e:+ logger.warning(f"invalid video file: {video_path} => {str(e)}")try:os.remove(video_path)except Exception:pass- logger.warning(f"invalid video file: {video_path} => {str(e)}")+ finally:+ if clip is not None:+ try:+ clip.close()+ except Exception:+ passreturn ""diff --git a/app/services/video.py b/app/services/video.pyindex 1a79e301..7153aaf7 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -91,12 +91,12 @@ def close_clip(clip):def delete_files(files: List[str] | str):if isinstance(files, str):files = [files]-+for file in files:try:os.remove(file)- except:- pass+ except Exception as e:+ logger.debug(f"failed to delete file {file}: {str(e)}")def get_bgm_file(bgm_type: str = "random", bgm_file: str = ""):if not bgm_type:@@ -127,10 +127,7 @@ def combine_videos(audio_clip = AudioFileClip(audio_file)audio_duration = audio_clip.durationlogger.info(f"audio duration: {audio_duration} seconds")- # Required duration of each clip- req_dur = audio_duration / len(video_paths)- req_dur = max_clip_duration- logger.info(f"maximum clip duration: {req_dur} seconds")+ logger.info(f"maximum clip duration: {max_clip_duration} seconds")output_dir = os.path.dirname(combined_video_path)aspect = VideoAspect(video_aspect)@@ -220,11 +217,13 @@ def combine_videos(# wirte clip to temp fileclip_file = f"{output_dir}/temp-clip-{i+1}.mp4"clip.write_videofile(clip_file, logger=None, fps=fps, codec=video_codec)-++ # Store clip duration before closing+ clip_duration_saved = clip.durationclose_clip(clip)-- processed_clips.append(SubClippedVideoClip(file_path=clip_file, duration=clip.duration, width=clip_w, height=clip_h))- video_duration += clip.duration++ processed_clips.append(SubClippedVideoClip(file_path=clip_file, duration=clip_duration_saved, width=clip_w, height=clip_h))+ video_duration += clip_duration_savedexcept Exception as e:logger.error(f"failed to process clip: {str(e)}")diff --git a/app/utils/utils.py b/app/utils/utils.pyindex 7efb521a..dc5ff3ee 100644--- a/app/utils/utils.py+++ b/app/utils/utils.py@@ -53,7 +53,8 @@ def to_json(obj):# Serialize the processed object into a JSON stringreturn json.dumps(serialized_obj, ensure_ascii=False, indent=4)- except Exception:+ except Exception as e:+ logger.error(f"failed to serialize object to json: {str(e)}")return None@@ -126,9 +127,9 @@ def run_in_background(func, *args, **kwargs):try:func(*args, **kwargs)except Exception as e:- logger.error(f"run_in_background error: {e}")+ logger.error(f"run_in_background error: {e}", exc_info=True)- thread = threading.Thread(target=run)+ thread = threading.Thread(target=run, daemon=False)thread.start()return thread