### Example .env File for Development Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md An example of a complete .env file for local development, including settings for environment, API keys, and platform integrations. Adapt values as needed for your specific setup. ```bash # Environment ENV=development # API Keys OPEN_AI_KEY=sk-proj-... API_HOST=https://ai-video-api.jackhui.com.au API_KEY=your-api-key # YouTube YOUTUBE_DEFAULT_PRIVACY=private # Instagram IG_USER_ID=12345678 IG_ACCESS_TOKEN=EAAabc... # Email EMAIL_USER=notifications@example.com EMAIL_PASSWORD=app-password SMTP_SERVER=smtp.gmail.com # Xiaohongshu XHS_MCP_ENABLED=true XHS_MCP_SERVER_URL=http://192.168.1.9:18060/mcp XHS_MCP_VIDEO_DIR=/mnt/shared/videos # Compliance COMPLIANCE_STRICT_MODE=false HEADLESS=false ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/README.md Installs all required Python packages for the project. Run this after cloning the repository. ```bash pip install -r requirements.txt ``` -------------------------------- ### Start MCP Server Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Start the MCP server, either with the browser visible for manual login or in the background. ```bash # Start server with browser visible (for login) python -m xiaohongshu_mcp.server --host 0.0.0.0 --port 18060 --headless false # Or in background nohup python -m xiaohongshu_mcp.server --host 0.0.0.0 --port 18060 & ``` -------------------------------- ### Command Line Usage with Presets Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md Examples of how to run the main script using predefined campaign presets like 'winningcv' and 'selectprep'. ```bash # Uses winningcv preset automatically python main.py --backlog winning-cv-video-backlog.json --day 1 --campaign winningcv # Uses selectprep preset automatically python main.py --backlog selectprep-video-backlog.json --day 1 --campaign selectprep ``` -------------------------------- ### Load Script from Markdown File Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Example command to generate a video by loading a script from a specified Markdown file. ```bash python main.py --language en --script-file scripts/episode_42.md ``` -------------------------------- ### Use Custom Topic for Video Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Example command to generate an English video with a custom topic overriding the default. ```bash python main.py --language en --topic "Is AI replacing software engineers?" ``` -------------------------------- ### Clone and Install MCP Server Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Clone the MCP server repository and install its dependencies using pip. ```bash # Clone the MCP server repository git clone https://github.com/xpzouying/xiaohongshu-mcp.git cd xiaohongshu-mcp # Install dependencies pip install -r requirements.txt ``` -------------------------------- ### Example: Call MCP Tool Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Illustrates calling an MCP tool, specifically 'check_login_status', using the `_call_tool_with_timeout` method. This example sets a timeout of 180.0 seconds for the operation. ```python result = await uploader._call_tool_with_timeout( tool_name="check_login_status", arguments={}, timeout=180.0 ) ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/README.md Installs necessary browser binaries for Playwright, used for non-MCP browser automation. This is optional. ```bash python -m playwright install chromium ``` -------------------------------- ### Example: Publish Video using XhsMcpUploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Demonstrates how to use the XhsMcpUploader within an async context to publish a video. Specify the video path, title, and description for the upload. ```python async def upload_example(): async with XhsMcpUploader() as uploader: result = await uploader.publish_video( video_path="/path/to/video.mp4", title="视频标题", description="视频描述" ) print(result) ``` -------------------------------- ### Development Environment Configuration (.env.development) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/09-configuration-and-env-vars.md Example .env file for local development testing. Includes settings for environment, API keys, YouTube, Instagram, Email, Xiaohongshu, and compliance. ```bash # Environment ENV=development HEADLESS=false # API Keys OPEN_AI_KEY=sk-proj-local-test-key API_HOST=https://ai-video-api.jackhui.com.au API_KEY=dev-api-key-12345 # YouTube YOUTUBE_DEFAULT_PRIVACY=unlisted # Instagram (optional for testing) IG_USER_ID= IG_ACCESS_TOKEN= # Email (optional for testing) EMAIL_USER= EMAIL_PASSWORD= SMTP_SERVER= # Xiaohongshu (optional) XHS_MCP_ENABLED=false XHS_MCP_SERVER_URL=http://localhost:18060/mcp XHS_MCP_VIDEO_DIR=/tmp/pending_upload # Compliance COMPLIANCE_STRICT_MODE=false ``` -------------------------------- ### Auto-generate English Video Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Example command to automatically generate an English video, specifying the language and campaign. ```bash python main.py --language en --campaign Q2_2024 ``` -------------------------------- ### Load Script from Backlog File Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Example command to generate a Chinese video by loading a script from a backlog JSON file for a specific day. ```bash python main.py --language zh --backlog campaigns/2024_plan.json --day 5 ``` -------------------------------- ### Production Environment Configuration (.env.production) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/09-configuration-and-env-vars.md Example .env file for production deployment. Includes settings for environment, API keys, YouTube, Instagram, Email, Xiaohongshu, and compliance. Emphasizes secure API key management. ```bash # Environment ENV=production HEADLESS=true # API Keys (use secrets management) OPEN_AI_KEY=sk-proj-production-key-secure API_HOST=https://ai-video-api.jackhui.com.au API_KEY=prod-api-key-secure # YouTube YOUTUBE_DEFAULT_PRIVACY=private # Instagram IG_USER_ID=12345678 IG_ACCESS_TOKEN=EAAxxxxx... # Email EMAIL_USER=notifications@example.com EMAIL_PASSWORD=app-password-secure SMTP_SERVER=smtp.gmail.com # Xiaohongshu (MCP) XHS_MCP_ENABLED=true XHS_MCP_SERVER_URL=http://192.168.1.9:18060/mcp XHS_MCP_VIDEO_DIR=/mnt/shared/pending_upload XHS_MCP_VISIBILITY=仅自己可见 # Compliance COMPLIANCE_STRICT_MODE=true ``` -------------------------------- ### Topic History Database Record Example Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/08-types-and-data-structures.md An example JSON record illustrating the structure and data types for the topic_history table. ```json { "id": "uuid-1234", "topic": "Why quantum computing will transform AI", "category": "quantum", "source_url": "https://arxiv.org/paper/2406.12345", "keywords": "quantum,computing,ai,future", "cross_feed_count": 5, "generated_at": "2024-06-18T10:30:00Z", "last_modified": "2024-06-18T10:30:00Z" } ``` -------------------------------- ### Toutiao Video Upload Usage Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Example of how to use the ToutiaoUploader to upload a video. Requires video path, title, description, and tags. ```python from platforms.toutiao.uploader import ToutiaoUploader uploader = ToutiaoUploader() result = uploader.upload_video( video_path="video.mp4", title="今日头条视频标题", description="视频描述", tags=["头条", "科技新闻"] ) ``` -------------------------------- ### Example: Check Login Status Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Shows how to check the login status using the XhsMcpUploader. It prints the username if logged in, or a message indicating that authentication is required. ```python async with XhsMcpUploader() as uploader: status = await uploader.check_login_status() if status.get('is_logged_in'): print(f"Logged in as: {status.get('username')}") else: print("Not logged in. Need to authenticate first.") ``` -------------------------------- ### Bilibili Video Upload Usage Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Example of how to use the BilibiliUploader to upload a video. Requires video path, title, description, tags, and an optional category. ```python from platforms.bili.uploader import BilibiliUploader uploader = BilibiliUploader() result = uploader.upload_video( video_path="video.mp4", title="视频标题", description="视频描述", tags=["技术", "科普"], category="知识" # Bilibili-specific category ) ``` -------------------------------- ### Example: Passing Compliance Check Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/08-types-and-data-structures.md Illustrates how to instantiate a ComplianceResult object for a successful compliance check. This includes setting passed to True and providing relevant metadata. ```python # Passing compliance check ComplianceResult( passed=True, issues=[], warnings=[], metadata={ "sources_analyzed": 1, "safe_source_detected": "pexels.com", "risk_score": 0.05 }, timestamp="2024-06-18T10:30:45.123456" ) ``` -------------------------------- ### Implement Custom Uploader Subclass Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md Example of creating a concrete uploader by subclassing `Upload` and implementing the `upload_video` method. Ensure to call `super().__init__()`. ```python from core.upload import Upload class MyPlatformUploader(Upload): def __init__(self): super().__init__() self.platform = "my_platform" def upload_video(self, video_path, title, description): self.logger.info(f"Uploading {title}") # Implementation here self.logger.info("Upload complete") ``` -------------------------------- ### Start MCP Server in Headless Mode Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Run the MCP server with `--headless false` to enable manual login via a browser, which is necessary if the 'Not logged in' error occurs. ```bash server --headless false ``` -------------------------------- ### XhsSessionManager Usage Example Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md Demonstrates how to initialize and use the XhsSessionManager to check and renew Xiaohongshu sessions. Requires a configuration dictionary with the cookie path. ```python from core.session_manager import XhsSessionManager import asyncio config = { "cookie_path": "cookies/xhs_cookies.json" } async def main(): manager = XhsSessionManager(config) # Check if session is healthy is_healthy = await manager.check_session_health() if not is_healthy: # Renew session with manual login await manager.renew_session() asyncio.run(main()) ``` -------------------------------- ### Load Environment Variables in Python Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/09-configuration-and-env-vars.md Load environment variables from a specific file based on the ENV setting. Ensure the 'dotenv' library is installed. ```python import os from dotenv import load_dotenv # Load from specific file env = os.getenv("ENV", "development") dotenv_path = f".env.{env}" load_dotenv(dotenv_path=dotenv_path) # Access variables api_key = os.getenv("OPEN_AI_KEY") api_host = os.getenv("API_HOST") ``` -------------------------------- ### Generate Video and Get Download URLs Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Generates a video file from a script and terms, then returns URLs for the original and potentially format-optimized versions. Requires a TTS voice name and supports multiple languages. Use this to create the final video asset. ```python original_url, converted_url = generate_video_and_get_urls( video_subject="Quantum Computing Breakthrough", video_script=script_text, video_terms=["Quantum", "Science"], voice_name="en-US-AnaNeural", language="en" ) if original_url: print(f"Download from: {original_url}") if converted_url: print(f"Optimized format: {converted_url}") else: print("Video generation failed") ``` -------------------------------- ### Integration Tests for Platform Uploaders Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md These examples show integration tests for connecting to different platform APIs, including MCP, YouTube authentication, and parsing Instagram API errors. They are executed using Python's `-c` flag. ```python # Test MCP connection python -c "from platforms.xhs.uploader_mcp_final import XhsMcpUploader; import asyncio; asyncio.run(XhsMcpUploader().check_login_status())" ``` ```python # Test YouTube auth python -c "from youtube_manager import authenticate_youtube; youtube = authenticate_youtube(); print('✅ YouTube authenticated')" ``` ```python # Test Instagram API python -c "from instagram_publisher import parse_api_error; print(parse_api_error('{\"error\": {\"code\": 190}}'))" ``` -------------------------------- ### Example: Failing Compliance Check Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/08-types-and-data-structures.md Demonstrates how to create a ComplianceResult object for a failed compliance check. This involves setting passed to False and detailing the specific issues and warnings encountered. ```python # Failing compliance check ComplianceResult( passed=False, issues=[ "Source URL detected in blocklist: youtube.com", "Script contains keyword: 'official music video'" ], warnings=[ "Video title contains common copyright keyword: 'official'" ], metadata={ "sources_analyzed": 2, "blocklisted_sources": ["youtube.com"], "risky_keywords": ["official video"], "risk_score": 0.85 }, timestamp="2024-06-18T10:30:45.123456" ) ``` -------------------------------- ### Initialize and Use XHS MCP Uploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Demonstrates how to initialize the XhsMcpUploader using an async context manager, check login status, and publish a video. Ensure the required environment variables are set. ```python from platforms.xhs.uploader_mcp_final import XhsMcpUploader async def upload(): async with XhsMcpUploader() as uploader: # Verify login status = await uploader.check_login_status() if not status.get('is_logged_in'): print("Must login first") return # Publish video result = await uploader.publish_video( video_path="/mnt/shared/video.mp4", title="视频标题", description="视频描述" ) return result ``` -------------------------------- ### Initialize and Upload Video with Douyin Uploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Initializes the DouyinUploader and uploads a video. This method requires the video path, title, description, and tags. Ensure the video meets Douyin's specified requirements. ```python from platforms.douyin.uploader import DouyinUploader uploader = DouyinUploader() result = uploader.upload_video( video_path="video.mp4", title="视频标题", description="视频描述", tags=["抖音", "科技"] ) ``` -------------------------------- ### Populate and Print VideoInfo Object Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md Demonstrates how to instantiate and populate a `VideoInfo` object with video metadata. The `__str__` method provides a formatted output. ```python from core.video_info import VideoInfo video = VideoInfo() video.video_name = "output_001.mp4" video.video_url = "https://api.example.com/videos/001" video.video_path = "/tmp/output_001.mp4" video.describe = "Generated AI video on quantum computing" print(video) # Output: # video_name="output_001.mp4" # download_date=None # video_url="https://api.example.com/videos/001" # video_path="/tmp/output_001.mp4" # remark1=None # describe="Generated AI video on quantum computing" ``` -------------------------------- ### Last Used Voice History Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/06-utilities-and-helpers.md Example JSON structure for storing the last used voice names for different languages. ```json { "last_voice_name_en": "en-US-AnaNeural", "last_voice_name_zh": "zh-CN-XiaoxiaoNeural" } ``` -------------------------------- ### English Video Pipeline Entry Point Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md Use this command to publish videos in English. It requires YouTube as a target and can optionally publish to Instagram if configured. ```bash python main.py --language en [--topic "..."] [--campaign campaign_name] ``` -------------------------------- ### Video Generation API Response Format for Script Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Example JSON structure for the response containing the generated video script. ```json { "data": { "video_script": "Full script text here..." } } ``` -------------------------------- ### Session Data JSON Structure Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md Example structure for storing session metadata, including the last renewal timestamp and estimated expiry. ```json { "last_renewal": "2024-06-18T10:30:00", "estimated_expiry": "2024-07-02T10:30:00" } ``` -------------------------------- ### main() - Chinese Video Upload Entry Point Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md The `main()` function is the asynchronous entry point for uploading videos to Chinese platforms. It handles video generation, uploading, and error recovery. ```APIDOC ## async def main(video_subject=None, video_script=None, video_terms=None, voice_name=None) ### Description Async entry point for Chinese platform video uploads (Xiaohongshu/XHS, Douyin, Toutiao). This function orchestrates the entire video upload process, from generation to final upload. ### Function Signature ```python async def main(video_subject=None, video_script=None, video_terms=None, voice_name=None) ``` ### Parameters #### Arguments - **video_subject** (str) - Optional - Video title/subject; generated if omitted. - **video_script** (str) - Optional - Video script; generated from subject if omitted. - **video_terms** (list) - Optional - List of search terms/tags for video. - **voice_name** (str) - Optional - TTS voice name; random selection if omitted. ### Returns dict - A dictionary containing upload results for each platform. ### Raises - `RuntimeError` - If video generation fails. - `ConnectionError` - If the MCP server is unreachable. ### Usage Example ```python import asyncio from main_cn import main # Generate video for Chinese platforms result = asyncio.run(main( video_subject="为什么AI正在改变世界?", voice_name="zh-CN-XiaoxiaoNeural" )) print(result) # {'xhs': {'success': True, 'video_id': '...'}, ...} ``` ``` -------------------------------- ### Run Test Suite Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md Execute the built-in test suite for the YouTube uploader. Ensure you are in the project directory and have activated the virtual environment. ```bash cd /home/ubuntu/youtube-uploader source venv/bin/activate python cta_overlay.py ``` -------------------------------- ### Video Generation API Response Format for Terms Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Example JSON structure for the response containing the generated video terms or tags. ```json { "data": { "video_terms": ["AI", "Machine Learning", "Software Development", "Automation", "Technology"] } } ``` -------------------------------- ### Chinese Video Pipeline Entry Point Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md Use this command to publish videos in Chinese. It supports various options and can be run asynchronously. ```bash python main.py --language zh [options...] ``` -------------------------------- ### MCP publish_with_video Arguments Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/08-types-and-data-structures.md Arguments for publishing a video, including path, title, description, and visibility. ```json { "video_path": "/mnt/shared/video.mp4", "title": "视频标题", "description": "视频描述", "visibility": "仅自己可见" # or "公开可见" } ``` -------------------------------- ### Main Entry Point for Chinese Video Uploads Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md This is the asynchronous entry point for uploading videos to Chinese platforms. It handles video generation, downloading, and uploading using either MCP or browser automation. Use this function to initiate the video creation and distribution process. ```python async def main(video_subject=None, video_script=None, video_terms=None, voice_name=None): # ... function body ... pass ``` ```python import asyncio from main_cn import main # Generate video for Chinese platforms result = asyncio.run(main( video_subject="为什么AI正在改变世界?", voice_name="zh-CN-XiaoxiaoNeural" )) print(result) # {'xhs': {'success': True, 'video_id': '...'}, ...} ``` -------------------------------- ### Get YouTube Video Status Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/03-youtube-publishing.md Retrieves the processing and publishing status of a YouTube video. Useful for checking if a video has finished processing or if there were any errors. ```python from youtube_manager import get_video_status # Assuming 'youtube' is an authenticated YouTube service object # and 'video_id' is the ID of the video to query. status = get_video_status(youtube, "dQw4w9WgXcQ") print(f"Upload Status: {status['upload_status']}") print(f"Processing: {status['processing_status']}") print(f"Privacy: {status['privacy_status']}") if status['processing_status'] == 'succeeded': print("Video is ready to view!") elif status['processing_status'] == 'failed': print(f"Error: {status['failure_reason']}") ``` -------------------------------- ### Initialize XHS Uploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Initializes the XhsUploader and uploads a video. Ensure the video path, title, description, and tags are correctly provided. This implementation uses DrissionPage/Playwright. ```python from platforms.xhs.uploader import XhsUploader uploader = XhsUploader() result = uploader.upload_video( video_path="video.mp4", title="视频标题", description="视频描述", tags=["#AI", "#Technology"] ) ``` -------------------------------- ### Instagram Publish API - Failure Case Result Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/04-instagram-publishing.md Example of a failure result returned by the publish_video_to_instagram function. Details the error, type, code, and context. ```python False, { "error": "Error message", "error_type": "ERROR_TYPE", "error_code": 100, "is_token_error": False, "context": { "video_url": "https://...", "ig_user_id": "123456789", "container_id": "987654321" } } ``` -------------------------------- ### Generate and Publish to All Platforms (English + Chinese) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md Execute the English pipeline first, followed by the Chinese pipeline using separate commands. This allows for multi-language content distribution. ```python # Run English pipeline first python main.py --language en # Then run Chinese pipeline python main.py --language zh ``` -------------------------------- ### Instagram Publish API - Success Case Result Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/04-instagram-publishing.md Example of a successful result returned by the publish_video_to_instagram function. Includes the media ID of the published content. ```python True, { "media_id": "17896954321234567" } ``` -------------------------------- ### Video Generation API Request Body for Script Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Example JSON payload for requesting a video script. Includes subject, language, and paragraph count. ```json { "video_subject": "Is AI about to replace developers?", "video_language": "en", "paragraph_number": 1 } ``` -------------------------------- ### Get Instagram Business Account ID Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/04-instagram-publishing.md Use the Facebook Graph API Explorer to retrieve your Instagram Business Account ID and name. This is a prerequisite for publishing. ```bash # Using Facebook Graph API Explorer # https://developers.facebook.com/tools/explorer/ # Query: GET /me/instagram_business_account?fields=id,name # Returns: { "instagram_business_account": { "id": "12345678", "name": "your_ig_handle" } } ``` -------------------------------- ### VideoInfo String Representation Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/08-types-and-data-structures.md Shows how to create and print a VideoInfo object, demonstrating its string representation. ```python video = VideoInfo() video.video_name = "test.mp4" video.describe = "Test video" print(video) # Output: # video_name="test.mp4" # download_date=None # video_url=None # video_path=None # remark1=None # describe="Test video" ``` -------------------------------- ### Video Generation API Request Body for Terms Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Example JSON payload for requesting video search terms. Includes subject, language, and the number of terms desired. ```json { "video_subject": "Is AI about to replace developers?", "video_language": "en", "amount": 5, "video_language": "en" } ``` -------------------------------- ### Chinese Video Pipeline Async Entry Point Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md This asynchronous function provides an alternative entry point for the Chinese video pipeline, allowing for programmatic control over video generation and publishing. ```python asyncio.run(main_cn.main(video_subject, video_script, video_terms, voice_name)) ``` -------------------------------- ### Instagram Publish API - Create Media Container Response Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/04-instagram-publishing.md Example JSON response after successfully creating a media container. Contains the unique ID for the created media. ```json { "id": "17896954321234567" } ``` -------------------------------- ### Get and Store Random Voice Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/02-video-generation-api.md Retrieves a random voice, ensuring it's different from the last used one for a specified language, and then stores the newly selected voice. ```python from voice_manager import get_last_used_voice, get_random_voice, store_last_used_voice last_voice = get_last_used_voice(language="en") voice_name = get_random_voice(last_voice=last_voice, language="en") store_last_used_voice(voice_name, language="en") ``` -------------------------------- ### Test Local Platform Upload Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Use this snippet to test the upload functionality with a small video and metadata locally. Ensure the uploader is properly initialized. ```python # Test with small video test_video = "test_output.mp4" test_metadata = { "title": "Test Video", "description": "Testing upload functionality" } # Test XHS MCP async with XhsMcpUploader() as uploader: result = await uploader.publish_video( video_path=test_video, title=test_metadata['title'], description=test_metadata['description'] ) print(f"XHS Result: {result}") ``` -------------------------------- ### Initialize XhsMcpUploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Instantiates the XhsMcpUploader class. Ensure XHS_MCP_ENABLED is set to 'true' in environment variables to enable MCP mode. Other environment variables like XHS_MCP_SERVER_URL, XHS_MCP_VIDEO_DIR, and XHS_MCP_VISIBILITY can be configured. ```python class XhsMcpUploader(Upload): platform = "xhs_mcp" def __init__(self): ``` -------------------------------- ### Get Recent Topic Titles Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/06-utilities-and-helpers.md Fetches a list of recent topic titles from the history database, defaulting to the last 14 days. Useful for checking previously published content. ```python from topic_history import get_recent_topic_titles recent = get_recent_topic_titles(days=14) print(f"Recent topics ({len(recent)}):") for topic in recent[:5]: print(f" - {topic}") ``` -------------------------------- ### Run English Video Upload Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/README.md Execute the main script to upload an English video. This process may also upload to Instagram depending on environment flags. ```bash python main.py --language en ``` -------------------------------- ### Get Last Used Text-to-Speech Voice Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/06-utilities-and-helpers.md Retrieves the name of the last text-to-speech voice used for a specific language from the 'last_voice.json' file. Returns None if the history file is missing. ```python from voice_manager import get_last_used_voice last_voice = get_last_used_voice(language="en") if last_voice: print(f"Last voice: {last_voice}") else: print("No voice history yet") ``` -------------------------------- ### Batch Upload Videos from Campaign Backlog Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md Upload videos in batches from a specified campaign backlog file. This is useful for uploading content for specific days within a campaign. ```bash # Upload Day 1 python main.py --language en --backlog campaigns/Q2_2024.json --day 1 # Upload Day 2 python main.py --language en --backlog campaigns/Q2_2024.json --day 2 ``` -------------------------------- ### Get Random Text-to-Speech Voice Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/06-utilities-and-helpers.md Selects a random text-to-speech voice for a given language, optionally excluding the last used voice to prevent repetition. If all voices are exhausted, it resets and allows repetition. ```python from voice_manager import get_random_voice, get_last_used_voice last = get_last_used_voice(language="en") voice = get_random_voice(last_voice=last, language="en") # Returns e.g., "en-US-JennyNeural" ``` -------------------------------- ### SelectPrep Preset Configuration Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md Default configuration for the SelectPrep campaign. Enables the overlay with specific text, URL, and timing. ```json { "enabled": true, "text": "Ace selective entry exams", "url": "selectprep.com.au", "position": "lower_third", "style": "box", "start_seconds_from_end": 8, "end_card_seconds": 2, "publish_public": true } ``` -------------------------------- ### Python Main Function for English Video Pipeline Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md This snippet demonstrates how to parse command-line arguments and initiate the main video generation and upload pipeline. It's used to configure the language, topic, and campaign for video processing. ```python import argparse # Parse args from command line parser = argparse.ArgumentParser() parser.add_argument('--language', choices=['en', 'zh'], default='en') parser.add_argument('--topic', type=str) parser.add_argument('--campaign', type=str, default='default') args = parser.parse_args() # Run pipeline exit_code = main(args) ``` -------------------------------- ### Instagram Publish API - Create Media Container Request Body Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/04-instagram-publishing.md Example JSON payload for creating a media container via the Facebook Graph API. Specifies media type, video URL, and caption. ```json { "media_type": "REELS", "video_url": "https://example.com/video.mp4", "caption": "Video caption", "access_token": "token..." } ``` -------------------------------- ### Select Environment File Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/09-configuration-and-env-vars.md Set the ENV environment variable to specify which .env file to load for configuration. This allows for different settings for development and production. ```bash # Load .env.development (default) export ENV=development python main.py --language en # Load .env.production export ENV=production python main.py --language en ``` -------------------------------- ### CLI Invocation (English) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Basic command to invoke the CLI for English video generation. Options for topic, campaign, and script file can be included. ```bash python main.py --language en [--topic "video topic"] [--campaign campaign_name] \ [--script-file path/to/script.json] [--backlog path/to/backlog.json --day N] ``` -------------------------------- ### Configure Douyin Uploader Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Defines the configuration dictionary for the Douyin uploader, including paths for cookies and various upload/check site URLs. This configuration is used to set up the uploader instance. ```python douyin_config = { "cookie_path": "cookies/douyin_cookies.json", "up_site": "https://creator.douyin.com/creator-micro/content/upload", "up_site2": "https://creator.douyin.com/creator-micro/content/publish", "check_site": "https://creator.douyin.com/creator-micro/content/manage" } ``` -------------------------------- ### Async Upload Pattern with Session Check Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md Demonstrates how to perform an asynchronous video upload, including an optional check for session health before initiating the upload. This pattern is suitable for non-MCP platforms with asynchronous operations. ```python import asyncio from platforms.platform import PlatformUploader async def async_upload(video_path, title): uploader = PlatformUploader() # Optional: check login status is_logged_in = await uploader.check_session_health() if not is_logged_in: print("Session expired") return None # Upload video result = await uploader.upload_video_async( video_path=video_path, title=title ) return result # Usage result = asyncio.run(async_upload("video.mp4", "Title")) ``` -------------------------------- ### Required Environment Variables for Services Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/07-core-classes-and-config.md Lists essential variables for API keys, service credentials, and platform publishing settings. Ensure these are set in your .env file for proper operation. ```bash # OpenAI API OPEN_AI_KEY=sk-... # Video Generation API API_HOST=https://ai-video-api.example.com API_KEY=api-key-... # YouTube OAuth YOUTUBE_CLIENT_ID=... YOUTUBE_CLIENT_SECRET=... # Instagram Publishing: IG_USER_ID=12345678 IG_ACCESS_TOKEN=EAAabc123... # Email Notifications: EMAIL_USER=your-email@gmail.com EMAIL_PASSWORD=app-specific-password SMTP_SERVER=smtp.gmail.com # Xiaohongshu MCP: XHS_MCP_ENABLED=true XHS_MCP_SERVER_URL=http://192.168.1.9:18060/mcp XHS_MCP_VIDEO_DIR=/mnt/shared/pending_upload # YouTube Publishing: YOUTUBE_DEFAULT_PRIVACY=private # private, unlisted, public COMPLIANCE_STRICT_MODE=false # Enable stricter pre-upload checks # General: ENV=production # development or production HEADLESS=false # Show browser windows during automation ``` -------------------------------- ### Chinese Workflow: Async Upload to Multiple Platforms Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/10-platform-uploaders.md This snippet demonstrates how to initiate an asynchronous upload to multiple Chinese platforms using the `main_cn` module. It takes video subject, script, terms, and voice name as input. ```python from main_cn import main as chinese_uploader_main # Async upload to Chinese platforms results = asyncio.run(chinese_uploader_main( video_subject=subject, video_script=script, video_terms=terms, voice_name=voice )) # results = { # 'xhs': {'success': True, 'video_id': '...'}, # 'douyin': {'success': True, 'video_id': '...'}, # 'toutiao': {'success': False, 'error': '...'}, # 'bili': {'success': True, 'video_id': '...'} # } ``` -------------------------------- ### Configure CTA Overlay for All Videos Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md Apply overlay settings to all videos within a campaign by adding the 'cta_overlay' configuration to the campaign backlog JSON. This is the recommended approach for consistent branding. ```json { "campaign": "WinningCV Launch", "platforms": ["youtube", "instagram"], "start_date": "2026-05-06", "cta_overlay": { "enabled": true, "text": "Try WinningCV free", "url": "winning-cv.jackhui.com.au", "position": "lower_third", "style": "box", "start_seconds_from_end": 8, "end_card_seconds": 2, "publish_public": true }, "videos": [...] } ``` -------------------------------- ### Set Environment to Production (macOS/Linux) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/README.md Exports the ENV variable to 'production' on macOS or Linux systems. This selects the .env.production configuration file. ```bash # macOS/Linux export ENV=production ``` -------------------------------- ### Video Generation API Credentials Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/09-configuration-and-env-vars.md Set the API_HOST and API_KEY for accessing the video generation service. These credentials are required for generating scripts, synthesizing content, and rendering videos. ```bash API_HOST=https://ai-video-api.jackhui.com.au API_KEY=your-api-key-here ``` -------------------------------- ### Video Generation Pipeline API Functions Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md This Python code demonstrates the sequence of API calls for generating a video, from creating a subject and script to selecting a voice and finally generating the video URLs. It also shows how to save the selected voice. ```python from video_manager import generate_video_subject, process_video_subject, generate_video_and_get_urls from voice_manager import get_random_voice, store_last_used_voice # 1. Generate topic subject = generate_video_subject(api_key, language="en") # 2. Generate script and terms script, terms, tags = process_video_subject(subject, language="en") # 3. Select voice voice = get_random_voice(language="en") # 4. Generate video original_url, converted_url = generate_video_and_get_urls( subject, script, terms, voice, language="en" ) # 5. Save voice selection store_last_used_voice(voice, language="en") ``` -------------------------------- ### Run Chinese Video Upload Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/README.md Execute the main script to upload a Chinese video. This process may upload to Chinese platforms like XHS via MCP if enabled. ```bash python main.py --language zh ``` -------------------------------- ### Publish Video using MCP Tool Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/05-xiaohongshu-mcp.md Use the 'publish_with_video' tool to upload a video to Xiaohongshu, specifying its path, title, description, and visibility. ```python await session.call_tool("publish_with_video", arguments={ "video_path": "/path/to/video.mp4", "title": "视频标题", "description": "视频描述", "visibility": "仅自己可见" # or 公开可见 }) ``` -------------------------------- ### Minimal Preset Configuration Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md A minimal configuration for the CTA overlay, suitable for simple call-to-actions with no specific text or URL. ```json { "enabled": true, "text": "", "url": "", "position": "lower_third", "style": "minimal", "start_seconds_from_end": 5, "end_card_seconds": 0 } ``` -------------------------------- ### Programmatic Video Processing with Overlay Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/CTA_OVERLAY_README.md Python code demonstrating how to process a video with a CTA overlay programmatically, either from metadata or a preset configuration. ```python from cta_overlay import process_video_with_overlay, OverlayConfig, get_preset # From backlog metadata result = process_video_with_overlay( video_path="/path/to/video.mp4", campaign_metadata={\"cta_overlay\": {\"enabled\": True, \"text\": \"Visit us\"}}, campaign_name="custom", video_subject="My Video" ) # Using preset config = get_preset("winningcv") from cta_overlay import apply_cta_overlay apply_cta_overlay("/path/to/video.mp4", config) ``` -------------------------------- ### CLI Invocation (Chinese) Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/01-main-entry-points.md Basic command to invoke the CLI for Chinese video generation. Includes the same optional arguments as the English version. ```bash python main.py --language zh [same options as above] ``` -------------------------------- ### Generate and Publish a Single Video to YouTube Source: https://github.com/jack-jackhui/youtube-uploader/blob/main/_autodocs/README.md Use this Python snippet to generate and publish a single video to YouTube with specified topic and campaign details. It utilizes the main function from the project's entry point. ```python import asyncio from main import main # Single command exit_code = main(argparse.Namespace( language='en', topic='Why AI is Transforming Tech', campaign='Q2_2024', script_file=None, backlog=None, day=None )) ```