利用 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
feat: Add Upload-Post integration for cross-posting to TikTok/Instagram
Juan Carlos Caverof2dfcfcd96c9
diff --git a/app/services/task.py b/app/services/task.pyindex 33c35ccc..e3aef25f 100644--- a/app/services/task.py+++ b/app/services/task.py@@ -8,7 +8,7 @@ from loguru import loggerfrom app.config import configfrom app.models import constfrom app.models.schema import VideoConcatMode, VideoParams-from app.services import llm, material, subtitle, video, voice+from app.services import llm, material, subtitle, video, voice, upload_postfrom app.services import state as smfrom app.utils import utils@@ -349,6 +349,21 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):f"task {task_id} finished, generated {len(final_video_paths)} videos.")+ # 7. Cross-post to TikTok/Instagram (if enabled)+ cross_post_results = []+ if upload_post.upload_post_service.is_configured() and upload_post.upload_post_service.auto_upload:+ logger.info("\n\n## cross-posting videos to TikTok/Instagram")+ for video_path in final_video_paths:+ result = upload_post.cross_post_video(+ video_path=video_path,+ title=params.video_subject or "Check out this video! #shorts #viral"+ )+ cross_post_results.append(result)+ if result.get('success'):+ logger.info(f"✅ Cross-posted: {video_path}")+ else:+ logger.warning(f"⚠️ Failed to cross-post: {video_path} - {result.get('error', 'Unknown error')}")+kwargs = {"videos": final_video_paths,"combined_videos": combined_video_paths,@@ -358,6 +373,7 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):"audio_duration": audio_duration,"subtitle_path": subtitle_path,"materials": downloaded_videos,+ "cross_post_results": cross_post_results if cross_post_results else None,}sm.state.update_task(task_id, state=const.TASK_STATE_COMPLETE, progress=100, **kwargsdiff --git a/app/services/upload_post.py b/app/services/upload_post.pynew file mode 100644index 00000000..2c0e7101--- /dev/null+++ b/app/services/upload_post.py@@ -0,0 +1,147 @@+"""+Upload-Post API integration for cross-posting videos to TikTok and Instagram.++Docs: https://docs.upload-post.com+"""+import os+import requests+from loguru import logger+from app.config import config+++class UploadPostService:+ """+ Service for cross-posting videos to TikTok/Instagram via Upload-Post API.+ """++ API_BASE = "https://api.upload-post.com"++ def __init__(self):+ self.api_key = config.app.get("upload_post_api_key", "")+ self.username = config.app.get("upload_post_username", "")+ self.enabled = config.app.get("upload_post_enabled", False)+ self.platforms = config.app.get("upload_post_platforms", ["tiktok", "instagram"])+ self.auto_upload = config.app.get("upload_post_auto_upload", False)++ def is_configured(self) -> bool:+ """Check if Upload-Post is properly configured."""+ return bool(self.api_key and self.username and self.enabled)++ def upload_video(+ self,+ video_path: str,+ title: str,+ platforms: list = None,+ privacy_level: str = "PUBLIC_TO_EVERYONE"+ ) -> dict:+ """+ Upload a video to TikTok and/or Instagram.++ Args:+ video_path (str): Path to the video file+ title (str): Video title/caption (max 2200 chars for Instagram)+ platforms (list): List of platforms ["tiktok", "instagram"]+ privacy_level (str): Privacy level for the video++ Returns:+ dict: API response with request_id and status+ """+ if not self.is_configured():+ logger.warning("Upload-Post is not configured. Skipping cross-post.")+ return {"success": False, "error": "Upload-Post not configured"}++ if platforms is None:+ platforms = self.platforms++ if not os.path.exists(video_path):+ logger.error(f"Video file not found: {video_path}")+ return {"success": False, "error": f"Video file not found: {video_path}"}++ logger.info(f"Cross-posting video to {', '.join(platforms)} via Upload-Post...")++ try:+ with open(video_path, 'rb') as video_file:+ files = {'video': video_file}++ data = {+ 'user': self.username,+ 'title': title[:2200],+ 'privacy_level': privacy_level+ }++ # Add each platform+ for i, platform in enumerate(platforms):+ data[f'platform[{i}]'] = platform++ headers = {+ 'Authorization': f'Apikey {self.api_key}'+ }++ response = requests.post(+ f"{self.API_BASE}/api/upload_video",+ headers=headers,+ data=data,+ files=files,+ timeout=300+ )++ response.raise_for_status()+ result = response.json()++ if result.get('success'):+ logger.info(f"✅ Video cross-posted successfully! Request ID: {result.get('request_id')}")+ else:+ logger.warning(f"Cross-post failed: {result.get('message', 'Unknown error')}")++ return result++ except requests.exceptions.RequestException as e:+ logger.error(f"Failed to cross-post video: {str(e)}")+ return {"success": False, "error": str(e)}++ def check_status(self, request_id: str) -> dict:+ """+ Check the status of an upload request.++ Args:+ request_id (str): The request ID from upload++ Returns:+ dict: Status information+ """+ try:+ headers = {+ 'Authorization': f'Apikey {self.api_key}'+ }++ response = requests.get(+ f"{self.API_BASE}/api/status/{request_id}",+ headers=headers,+ timeout=30+ )++ response.raise_for_status()+ return response.json()++ except requests.exceptions.RequestException as e:+ logger.error(f"Failed to check status: {str(e)}")+ return {"success": False, "error": str(e)}+++# Singleton instance+upload_post_service = UploadPostService()+++def cross_post_video(video_path: str, title: str, platforms: list = None) -> dict:+ """+ Convenience function to cross-post a video.++ Args:+ video_path (str): Path to the video file+ title (str): Video title/caption+ platforms (list): List of platforms (defaults to config)++ Returns:+ dict: API response+ """+ return upload_post_service.upload_video(video_path, title, platforms)diff --git a/config.example.toml b/config.example.tomlindex 5f77f42d..d808037f 100644--- a/config.example.toml+++ b/config.example.toml@@ -221,3 +221,23 @@ api_key = ""# 是否隐藏日志信息# Whether to hide logs in the UIhide_log = false++########## Upload-Post (Cross-post to TikTok/Instagram)+# Upload-Post allows you to automatically cross-post generated videos to TikTok and Instagram.+# Visit https://upload-post.com to create an account and get your API key.+# API Documentation: https://docs.upload-post.com++# Enable/disable Upload-Post integration+upload_post_enabled = false++# Your Upload-Post API key+upload_post_api_key = ""++# Your Upload-Post username+upload_post_username = ""++# Platforms to cross-post to (options: "tiktok", "instagram")+upload_post_platforms = ["tiktok", "instagram"]++# Automatically cross-post videos after generation (if false, you'll need to call the API manually)+upload_post_auto_upload = falsediff --git a/docs/upload-post.md b/docs/upload-post.mdnew file mode 100644index 00000000..a36bee92--- /dev/null+++ b/docs/upload-post.md@@ -0,0 +1,95 @@+# Upload-Post Integration / Upload-Post 集成++[English](#english) | [中文](#中文)++## English++### Overview++Upload-Post integration allows you to automatically cross-post generated videos to TikTok and Instagram.++### What is Upload-Post?++[Upload-Post](https://upload-post.com) is an API service that allows you to upload videos to multiple social media platforms with a single API call.++- **Website:** https://upload-post.com+- **API Docs:** https://docs.upload-post.com+- **Free tier available**++### Setup++1. Create an account at [upload-post.com](https://upload-post.com)+2. Connect your TikTok and/or Instagram accounts in the dashboard+3. Get your API key from the dashboard+4. Add the following to your `config.toml`:++```toml+upload_post_enabled = true+upload_post_api_key = "your-api-key"+upload_post_username = "your-username"+upload_post_platforms = ["tiktok", "instagram"]+upload_post_auto_upload = true+```++### Configuration Options++| Option | Type | Default | Description |+|--------|------|---------|-------------|+| `upload_post_enabled` | bool | `false` | Enable/disable Upload-Post integration |+| `upload_post_api_key` | string | `""` | Your Upload-Post API key |+| `upload_post_username` | string | `""` | Your Upload-Post username |+| `upload_post_platforms` | array | `["tiktok", "instagram"]` | Platforms to cross-post to |+| `upload_post_auto_upload` | bool | `false` | Automatically cross-post after video generation |++### Usage++When `upload_post_auto_upload` is set to `true`, videos will be automatically cross-posted to the configured platforms after generation.++The cross-posting results will be included in the task response under `cross_post_results`.++---++## 中文++### 概述++Upload-Post 集成允许您自动将生成的视频发布到 TikTok 和 Instagram。++### 什么是 Upload-Post?++[Upload-Post](https://upload-post.com) 是一个 API 服务,允许您通过单个 API 调用将视频上传到多个社交媒体平台。++- **网站:** https://upload-post.com+- **API 文档:** https://docs.upload-post.com+- **提供免费套餐**++### 设置++1. 在 [upload-post.com](https://upload-post.com) 创建账户+2. 在控制面板中连接您的 TikTok 和/或 Instagram 账户+3. 从控制面板获取您的 API 密钥+4. 将以下内容添加到您的 `config.toml`:++```toml+upload_post_enabled = true+upload_post_api_key = "your-api-key"+upload_post_username = "your-username"+upload_post_platforms = ["tiktok", "instagram"]+upload_post_auto_upload = true+```++### 配置选项++| 选项 | 类型 | 默认值 | 描述 |+|------|------|--------|------|+| `upload_post_enabled` | bool | `false` | 启用/禁用 Upload-Post 集成 |+| `upload_post_api_key` | string | `""` | 您的 Upload-Post API 密钥 |+| `upload_post_username` | string | `""` | 您的 Upload-Post 用户名 |+| `upload_post_platforms` | array | `["tiktok", "instagram"]` | 要发布的平台 |+| `upload_post_auto_upload` | bool | `false` | 视频生成后自动发布 |++### 使用方法++当 `upload_post_auto_upload` 设置为 `true` 时,视频在生成后将自动发布到配置的平台。++发布结果将包含在任务响应的 `cross_post_results` 字段中。