Merge pull request #1 from thaitien280401-stack/copilot/update-app-for-vietnam-market
Scheduler: 1 video per 3h with title deduplicationpull/2482/head
commit
c00db83c96
@ -0,0 +1,358 @@
|
||||
# 🇻🇳 HƯỚNG DẪN CÀI ĐẶT VÀ CHẠY TRÊN VPS
|
||||
|
||||
## Mục lục
|
||||
|
||||
1. [Yêu cầu hệ thống](#1-yêu-cầu-hệ-thống)
|
||||
2. [Cài đặt trên VPS](#2-cài-đặt-trên-vps)
|
||||
3. [Cấu hình bắt buộc](#3-cấu-hình-bắt-buộc-configtoml)
|
||||
4. [Các chế độ chạy](#4-các-chế-độ-chạy)
|
||||
5. [Chạy nền trên VPS](#5-chạy-nền-trên-vps-với-systemd)
|
||||
6. [Chạy với Docker](#6-chạy-với-docker-tùy-chọn)
|
||||
7. [Kiểm tra và khắc phục lỗi](#7-kiểm-tra-và-khắc-phục-lỗi)
|
||||
8. [Bảng tóm tắt cấu hình](#8-bảng-tóm-tắt-cấu-hình-cần-cập-nhật)
|
||||
|
||||
---
|
||||
|
||||
## 1. Yêu cầu hệ thống
|
||||
|
||||
| Thành phần | Yêu cầu tối thiểu |
|
||||
|---|---|
|
||||
| **OS** | Ubuntu 20.04+ / Debian 11+ |
|
||||
| **RAM** | 2 GB (khuyến nghị 4 GB) |
|
||||
| **Disk** | 10 GB trống |
|
||||
| **Python** | 3.10, 3.11 hoặc 3.12 |
|
||||
| **FFmpeg** | Bắt buộc (cài tự động nếu thiếu) |
|
||||
|
||||
---
|
||||
|
||||
## 2. Cài đặt trên VPS
|
||||
|
||||
### Bước 1: Cập nhật hệ thống và cài đặt phụ thuộc
|
||||
|
||||
```bash
|
||||
sudo apt update && sudo apt upgrade -y
|
||||
sudo apt install -y python3 python3-pip python3-venv ffmpeg git
|
||||
```
|
||||
|
||||
### Bước 2: Clone dự án
|
||||
|
||||
```bash
|
||||
cd /opt
|
||||
git clone https://github.com/thaitien280401-stack/RedditVideoMakerBot.git
|
||||
cd RedditVideoMakerBot
|
||||
```
|
||||
|
||||
### Bước 3: Tạo virtual environment
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
```
|
||||
|
||||
### Bước 4: Cài đặt thư viện
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### Bước 5: Cài đặt Playwright browser (cần cho chế độ screenshot)
|
||||
|
||||
```bash
|
||||
python -m playwright install
|
||||
python -m playwright install-deps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Cấu hình bắt buộc (`config.toml`)
|
||||
|
||||
Khi chạy lần đầu, chương trình sẽ tự tạo file `config.toml` và hỏi bạn nhập thông tin.
|
||||
Bạn cũng có thể tạo trước file `config.toml` trong thư mục gốc dự án:
|
||||
|
||||
```toml
|
||||
# ===== CẤU HÌNH BẮT BUỘC =====
|
||||
|
||||
[threads.creds]
|
||||
access_token = "YOUR_THREADS_ACCESS_TOKEN" # Lấy từ Meta Developer Portal
|
||||
user_id = "YOUR_THREADS_USER_ID" # Threads User ID
|
||||
|
||||
[threads.thread]
|
||||
target_user_id = "" # Để trống = dùng user của bạn
|
||||
post_id = "" # Để trống = tự động chọn thread mới nhất
|
||||
keywords = "viral, trending, hài hước" # Từ khóa lọc (tùy chọn)
|
||||
max_comment_length = 500
|
||||
min_comment_length = 1
|
||||
post_lang = "vi"
|
||||
min_comments = 5
|
||||
blocked_words = "spam, quảng cáo"
|
||||
channel_name = "Threads Vietnam"
|
||||
|
||||
[settings]
|
||||
allow_nsfw = false
|
||||
theme = "dark"
|
||||
times_to_run = 1
|
||||
opacity = 0.9
|
||||
resolution_w = 1080
|
||||
resolution_h = 1920
|
||||
|
||||
[settings.background]
|
||||
background_video = "minecraft"
|
||||
background_audio = "lofi"
|
||||
background_audio_volume = 0.15
|
||||
|
||||
[settings.tts]
|
||||
voice_choice = "googletranslate" # Tốt nhất cho tiếng Việt
|
||||
silence_duration = 0.3
|
||||
no_emojis = false
|
||||
|
||||
# ===== SCHEDULER (lên lịch tự động) =====
|
||||
|
||||
[scheduler]
|
||||
enabled = true # BẬT lên lịch tự động
|
||||
cron = "0 */3 * * *" # Mỗi 3 giờ tạo 1 video
|
||||
timezone = "Asia/Ho_Chi_Minh" # Múi giờ Việt Nam
|
||||
max_videos_per_day = 8 # Tối đa 8 video/ngày
|
||||
|
||||
# ===== UPLOAD TỰ ĐỘNG (tùy chọn) =====
|
||||
|
||||
[uploaders.youtube]
|
||||
enabled = false
|
||||
client_id = ""
|
||||
client_secret = ""
|
||||
refresh_token = ""
|
||||
|
||||
[uploaders.tiktok]
|
||||
enabled = false
|
||||
client_key = ""
|
||||
client_secret = ""
|
||||
refresh_token = ""
|
||||
|
||||
[uploaders.facebook]
|
||||
enabled = false
|
||||
page_id = ""
|
||||
access_token = ""
|
||||
```
|
||||
|
||||
### Cách lấy Threads API credentials
|
||||
|
||||
1. Truy cập [Meta Developer Portal](https://developers.facebook.com/)
|
||||
2. Tạo App mới → chọn "Business" type
|
||||
3. Thêm product "Threads API"
|
||||
4. Vào Settings → Basic → lấy **App ID**
|
||||
5. Tạo Access Token cho Threads API
|
||||
6. Lấy **User ID** từ Threads API endpoint: `GET /me?fields=id,username`
|
||||
|
||||
---
|
||||
|
||||
## 4. Các chế độ chạy
|
||||
|
||||
### 4.1. Manual (thủ công) — Mặc định
|
||||
Tạo video 1 lần, không upload:
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
### 4.2. Auto (tạo + upload)
|
||||
Tạo video và tự động upload lên các platform đã cấu hình:
|
||||
```bash
|
||||
python main.py --mode auto
|
||||
```
|
||||
|
||||
### 4.3. ⭐ Scheduled (lên lịch tự động) — KHUYẾN NGHỊ CHO VPS
|
||||
Chạy liên tục trên VPS, tự động tạo video theo lịch trình:
|
||||
```bash
|
||||
python main.py --mode scheduled
|
||||
```
|
||||
|
||||
**Mặc định:**
|
||||
- Cron: `0 */3 * * *` → Tạo 1 video **mỗi 3 giờ**
|
||||
- Lịch chạy: 00:00, 03:00, 06:00, 09:00, 12:00, 15:00, 18:00, 21:00 (giờ VN)
|
||||
- **= 8 video/ngày**
|
||||
- Timezone: `Asia/Ho_Chi_Minh`
|
||||
- Tự động bỏ qua các chủ đề đã tạo video (title deduplication)
|
||||
- Giới hạn tối đa `max_videos_per_day` video mỗi ngày
|
||||
|
||||
### Tùy chỉnh lịch chạy
|
||||
|
||||
Thay đổi `cron` trong `config.toml`:
|
||||
|
||||
| Cron Expression | Mô tả | Video/ngày |
|
||||
|---|---|---|
|
||||
| `0 */3 * * *` | Mỗi 3 giờ (mặc định) | 8 |
|
||||
| `0 */4 * * *` | Mỗi 4 giờ | 6 |
|
||||
| `0 */6 * * *` | Mỗi 6 giờ | 4 |
|
||||
| `0 8,14,20 * * *` | Lúc 8h, 14h, 20h | 3 |
|
||||
| `0 */2 * * *` | Mỗi 2 giờ | 12 |
|
||||
|
||||
---
|
||||
|
||||
## 5. Chạy nền trên VPS với systemd
|
||||
|
||||
### Bước 1: Tạo systemd service
|
||||
|
||||
```bash
|
||||
sudo nano /etc/systemd/system/threads-video-bot.service
|
||||
```
|
||||
|
||||
Dán nội dung sau:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Threads Video Maker Bot
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/RedditVideoMakerBot
|
||||
ExecStart=/opt/RedditVideoMakerBot/venv/bin/python main.py --mode scheduled
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
### Bước 2: Kích hoạt và khởi động
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable threads-video-bot
|
||||
sudo systemctl start threads-video-bot
|
||||
```
|
||||
|
||||
### Bước 3: Kiểm tra trạng thái
|
||||
|
||||
```bash
|
||||
# Xem trạng thái
|
||||
sudo systemctl status threads-video-bot
|
||||
|
||||
# Xem log realtime
|
||||
sudo journalctl -u threads-video-bot -f
|
||||
|
||||
# Xem log gần nhất
|
||||
sudo journalctl -u threads-video-bot --since "1 hour ago"
|
||||
|
||||
# Restart
|
||||
sudo systemctl restart threads-video-bot
|
||||
|
||||
# Dừng
|
||||
sudo systemctl stop threads-video-bot
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Chạy với Docker (tùy chọn)
|
||||
|
||||
### Build image
|
||||
|
||||
```bash
|
||||
cd /opt/RedditVideoMakerBot
|
||||
docker build -t threads-video-bot .
|
||||
```
|
||||
|
||||
### Chạy container
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name threads-bot \
|
||||
--restart unless-stopped \
|
||||
-v $(pwd)/config.toml:/app/config.toml \
|
||||
-v $(pwd)/results:/app/results \
|
||||
-v $(pwd)/video_creation/data:/app/video_creation/data \
|
||||
threads-video-bot python3 main.py --mode scheduled
|
||||
```
|
||||
|
||||
### Xem log
|
||||
|
||||
```bash
|
||||
docker logs -f threads-bot
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Kiểm tra và khắc phục lỗi
|
||||
|
||||
### Kiểm tra trạng thái
|
||||
|
||||
```bash
|
||||
# Service đang chạy?
|
||||
sudo systemctl is-active threads-video-bot
|
||||
|
||||
# Xem lỗi gần nhất
|
||||
sudo journalctl -u threads-video-bot --since "30 min ago" --no-pager
|
||||
|
||||
# Đếm video đã tạo
|
||||
ls -la results/*/
|
||||
```
|
||||
|
||||
### Lỗi thường gặp
|
||||
|
||||
| Lỗi | Nguyên nhân | Cách khắc phục |
|
||||
|---|---|---|
|
||||
| `ModuleNotFoundError` | Thiếu thư viện | `source venv/bin/activate && pip install -r requirements.txt` |
|
||||
| `FileNotFoundError: ffmpeg` | Chưa cài FFmpeg | `sudo apt install ffmpeg` |
|
||||
| `Threads API error 401` | Token hết hạn | Tạo access token mới từ Meta Developer Portal |
|
||||
| `No suitable thread found` | Hết thread mới | Đợi có thread mới hoặc thay `target_user_id` |
|
||||
| `playwright._impl._errors` | Thiếu browser | `python -m playwright install && python -m playwright install-deps` |
|
||||
| `Đã đạt giới hạn X video/ngày` | Đã tạo đủ video | Bình thường, sẽ reset vào ngày hôm sau |
|
||||
|
||||
### Lịch sử title (tránh trùng lặp)
|
||||
|
||||
- File lưu: `video_creation/data/title_history.json`
|
||||
- Xem title đã tạo: `cat video_creation/data/title_history.json | python -m json.tool`
|
||||
- Reset (cho phép tạo lại tất cả): `echo "[]" > video_creation/data/title_history.json`
|
||||
|
||||
---
|
||||
|
||||
## 8. Bảng tóm tắt cấu hình cần cập nhật
|
||||
|
||||
### ⚠️ BẮT BUỘC phải thay đổi
|
||||
|
||||
| Mục | Key trong config.toml | Mô tả | Cách lấy |
|
||||
|---|---|---|---|
|
||||
| **Threads Token** | `threads.creds.access_token` | Access token API | [Meta Developer Portal](https://developers.facebook.com/) |
|
||||
| **Threads User ID** | `threads.creds.user_id` | User ID Threads | API endpoint `/me?fields=id` |
|
||||
|
||||
### 📋 Nên tùy chỉnh
|
||||
|
||||
| Mục | Key | Mặc định | Gợi ý |
|
||||
|---|---|---|---|
|
||||
| Tên kênh | `threads.thread.channel_name` | "Threads Vietnam" | Tên kênh của bạn |
|
||||
| Từ khóa | `threads.thread.keywords` | "" | "viral, trending, hài hước" |
|
||||
| Từ bị chặn | `threads.thread.blocked_words` | "" | "spam, quảng cáo, 18+" |
|
||||
| Lịch chạy | `scheduler.cron` | `0 */3 * * *` | Xem bảng ở mục 4 |
|
||||
| Max video/ngày | `scheduler.max_videos_per_day` | 8 | Tùy chỉnh |
|
||||
|
||||
### 🔧 Tùy chọn: Upload tự động
|
||||
|
||||
| Platform | Keys cần cấu hình |
|
||||
|---|---|
|
||||
| **YouTube** | `uploaders.youtube.client_id`, `client_secret`, `refresh_token` |
|
||||
| **TikTok** | `uploaders.tiktok.client_key`, `client_secret`, `refresh_token` |
|
||||
| **Facebook** | `uploaders.facebook.page_id`, `access_token` |
|
||||
|
||||
---
|
||||
|
||||
## Tóm tắt nhanh
|
||||
|
||||
```bash
|
||||
# 1. Cài đặt
|
||||
cd /opt/RedditVideoMakerBot
|
||||
python3 -m venv venv && source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
python -m playwright install && python -m playwright install-deps
|
||||
|
||||
# 2. Cấu hình
|
||||
nano config.toml # Nhập thông tin Threads API
|
||||
|
||||
# 3. Test thử 1 video
|
||||
python main.py
|
||||
|
||||
# 4. Chạy tự động trên VPS (mỗi 3h = 8 video/ngày)
|
||||
python main.py --mode scheduled
|
||||
|
||||
# 5. Hoặc chạy nền với systemd (khuyến nghị)
|
||||
sudo systemctl enable --now threads-video-bot
|
||||
```
|
||||
@ -0,0 +1,119 @@
|
||||
# 🇻🇳 Kế Hoạch Chuyển Đổi: Reddit Video Maker → Threads Vietnam Video Maker
|
||||
|
||||
## Tổng Quan
|
||||
Chuyển đổi ứng dụng Reddit Video Maker Bot thành công cụ tự động tạo video từ nội dung Threads (Meta) cho thị trường Việt Nam, với khả năng tự động đăng lên TikTok, YouTube và Facebook.
|
||||
|
||||
---
|
||||
|
||||
## Giai Đoạn 1: Thay Thế Reddit bằng Threads API
|
||||
### 1.1 Module `threads/` - Lấy nội dung từ Threads
|
||||
- Tạo `threads/__init__.py`
|
||||
- Tạo `threads/threads_client.py` - Client gọi Threads API (Meta Graph API)
|
||||
- Đăng nhập OAuth2 với Threads API
|
||||
- Lấy danh sách bài viết trending/hot
|
||||
- Lấy replies (comments) của bài viết
|
||||
- Lọc nội dung theo từ khóa, độ dài, ngôn ngữ
|
||||
- Cấu trúc dữ liệu trả về tương tự reddit_object:
|
||||
```python
|
||||
{
|
||||
"thread_url": "https://threads.net/@user/post/...",
|
||||
"thread_title": "Nội dung bài viết",
|
||||
"thread_id": "abc123",
|
||||
"thread_author": "@username",
|
||||
"is_nsfw": False,
|
||||
"thread_post": "Nội dung đầy đủ",
|
||||
"comments": [
|
||||
{
|
||||
"comment_body": "Nội dung reply",
|
||||
"comment_url": "permalink",
|
||||
"comment_id": "xyz789",
|
||||
"comment_author": "@user2"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 Cập nhật Screenshot cho Threads
|
||||
- Tạo `video_creation/threads_screenshot.py`
|
||||
- Render HTML template theo style Threads
|
||||
- Hỗ trợ giao diện dark/light mode
|
||||
- Hiển thị avatar, username, verified badge
|
||||
- Font hỗ trợ tiếng Việt (Unicode đầy đủ)
|
||||
|
||||
---
|
||||
|
||||
## Giai Đoạn 2: Tối Ưu Cho Thị Trường Việt Nam
|
||||
### 2.1 Vietnamese TTS
|
||||
- Sử dụng Google Translate TTS (gTTS) với ngôn ngữ `vi`
|
||||
- Hỗ trợ giọng đọc tiếng Việt tự nhiên
|
||||
- Cấu hình mặc định `post_lang = "vi"`
|
||||
|
||||
### 2.2 Xử Lý Văn Bản Tiếng Việt
|
||||
- Cập nhật `utils/voice.py` cho tiếng Việt
|
||||
- Xử lý dấu, ký tự Unicode Vietnamese
|
||||
- Tối ưu ngắt câu cho TTS tiếng Việt
|
||||
|
||||
---
|
||||
|
||||
## Giai Đoạn 3: Auto-Posting - Đăng Tự Động
|
||||
### 3.1 Module `uploaders/`
|
||||
- `uploaders/__init__.py`
|
||||
- `uploaders/base_uploader.py` - Base class
|
||||
- `uploaders/tiktok_uploader.py` - Đăng lên TikTok
|
||||
- Sử dụng TikTok Content Posting API
|
||||
- Hỗ trợ set caption, hashtags
|
||||
- Schedule posting
|
||||
- `uploaders/youtube_uploader.py` - Đăng lên YouTube
|
||||
- Sử dụng YouTube Data API v3
|
||||
- Upload video với title, description, tags
|
||||
- Set privacy (public/private/unlisted)
|
||||
- Schedule publishing
|
||||
- `uploaders/facebook_uploader.py` - Đăng lên Facebook
|
||||
- Sử dụng Facebook Graph API
|
||||
- Upload video lên Page hoặc Profile
|
||||
- Set caption, scheduling
|
||||
|
||||
### 3.2 Upload Manager
|
||||
- `uploaders/upload_manager.py`
|
||||
- Quản lý upload đồng thời nhiều platform
|
||||
- Retry logic khi upload thất bại
|
||||
- Logging và tracking trạng thái
|
||||
|
||||
---
|
||||
|
||||
## Giai Đoạn 4: Hệ Thống Lên Lịch Tự Động
|
||||
### 4.1 Module `scheduler/`
|
||||
- `scheduler/__init__.py`
|
||||
- `scheduler/scheduler.py` - Lên lịch tạo và đăng video
|
||||
- Sử dụng APScheduler
|
||||
- Cron-style scheduling
|
||||
- Hỗ trợ múi giờ Việt Nam (Asia/Ho_Chi_Minh)
|
||||
- `scheduler/pipeline.py` - Pipeline tự động
|
||||
- Fetch content → TTS → Screenshots → Video → Upload
|
||||
- Error handling và retry
|
||||
- Notification khi hoàn thành
|
||||
|
||||
---
|
||||
|
||||
## Giai Đoạn 5: Cập Nhật Cấu Hình & Entry Point
|
||||
### 5.1 Config mới
|
||||
- Cập nhật `utils/.config.template.toml` thêm sections:
|
||||
- `[threads.creds]` - Threads API credentials
|
||||
- `[uploaders.tiktok]` - TikTok config
|
||||
- `[uploaders.youtube]` - YouTube config
|
||||
- `[uploaders.facebook]` - Facebook config
|
||||
- `[scheduler]` - Scheduling config
|
||||
|
||||
### 5.2 Entry Point
|
||||
- Cập nhật `main.py` cho workflow mới
|
||||
- Hỗ trợ 3 modes: manual, auto, scheduled
|
||||
|
||||
---
|
||||
|
||||
## Dependencies Mới
|
||||
```
|
||||
google-api-python-client # YouTube Data API
|
||||
google-auth-oauthlib # Google OAuth
|
||||
apscheduler # Task scheduling
|
||||
httpx # Async HTTP client (Threads API)
|
||||
```
|
||||
@ -0,0 +1,236 @@
|
||||
"""
|
||||
Scheduler - Hệ thống lên lịch tự động tạo và đăng video.
|
||||
|
||||
Sử dụng APScheduler để lên lịch các tác vụ tự động.
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from os import name
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from typing import Optional
|
||||
|
||||
from utils import settings
|
||||
from utils.cleanup import cleanup
|
||||
from utils.console import print_markdown, print_step, print_substep
|
||||
from utils.id import extract_id
|
||||
from utils.title_history import save_title
|
||||
|
||||
|
||||
def run_pipeline(post_id: Optional[str] = None) -> Optional[str]:
|
||||
"""Chạy toàn bộ pipeline tạo video từ Threads.
|
||||
|
||||
Pipeline:
|
||||
1. Lấy nội dung từ Threads
|
||||
2. Tạo TTS audio
|
||||
3. Tạo screenshots
|
||||
4. Tải background video/audio
|
||||
5. Ghép video cuối cùng
|
||||
6. Upload lên các platform (nếu được cấu hình)
|
||||
|
||||
Args:
|
||||
post_id: ID cụ thể của thread (optional).
|
||||
|
||||
Returns:
|
||||
Đường dẫn file video đã tạo, hoặc None nếu thất bại.
|
||||
"""
|
||||
from threads.threads_client import get_threads_posts
|
||||
from video_creation.background import (
|
||||
chop_background,
|
||||
download_background_audio,
|
||||
download_background_video,
|
||||
get_background_config,
|
||||
)
|
||||
from video_creation.final_video import make_final_video
|
||||
from video_creation.threads_screenshot import get_screenshots_of_threads_posts
|
||||
from video_creation.voices import save_text_to_mp3
|
||||
|
||||
print_step("🚀 Bắt đầu pipeline tạo video...")
|
||||
|
||||
try:
|
||||
# Step 1: Lấy nội dung từ Threads
|
||||
print_step("📱 Bước 1: Lấy nội dung từ Threads...")
|
||||
thread_object = get_threads_posts(post_id)
|
||||
thread_id = extract_id(thread_object)
|
||||
print_substep(f"Thread ID: {thread_id}", style="bold blue")
|
||||
|
||||
# Step 2: Tạo TTS audio
|
||||
print_step("🎙️ Bước 2: Tạo audio TTS...")
|
||||
length, number_of_comments = save_text_to_mp3(thread_object)
|
||||
length = math.ceil(length)
|
||||
|
||||
# Step 3: Tạo screenshots
|
||||
print_step("📸 Bước 3: Tạo hình ảnh...")
|
||||
get_screenshots_of_threads_posts(thread_object, number_of_comments)
|
||||
|
||||
# Step 4: Background
|
||||
print_step("🎬 Bước 4: Xử lý background...")
|
||||
bg_config = {
|
||||
"video": get_background_config("video"),
|
||||
"audio": get_background_config("audio"),
|
||||
}
|
||||
download_background_video(bg_config["video"])
|
||||
download_background_audio(bg_config["audio"])
|
||||
chop_background(bg_config, length, thread_object)
|
||||
|
||||
# Step 5: Ghép video cuối cùng
|
||||
print_step("🎥 Bước 5: Tạo video cuối cùng...")
|
||||
make_final_video(number_of_comments, length, thread_object, bg_config)
|
||||
|
||||
# Tìm file video đã tạo
|
||||
subreddit = (
|
||||
settings.config.get("threads", {}).get("thread", {}).get("channel_name", "threads")
|
||||
)
|
||||
results_dir = f"./results/{subreddit}"
|
||||
video_path = None
|
||||
if os.path.exists(results_dir):
|
||||
files = sorted(
|
||||
[f for f in os.listdir(results_dir) if f.endswith(".mp4")],
|
||||
key=lambda x: os.path.getmtime(os.path.join(results_dir, x)),
|
||||
reverse=True,
|
||||
)
|
||||
if files:
|
||||
video_path = os.path.join(results_dir, files[0])
|
||||
|
||||
# Step 6: Upload (nếu cấu hình)
|
||||
upload_config = settings.config.get("uploaders", {})
|
||||
has_uploaders = any(
|
||||
upload_config.get(p, {}).get("enabled", False) for p in ["youtube", "tiktok", "facebook"]
|
||||
)
|
||||
|
||||
if has_uploaders and video_path:
|
||||
print_step("📤 Bước 6: Upload video lên các platform...")
|
||||
from uploaders.upload_manager import UploadManager
|
||||
|
||||
manager = UploadManager()
|
||||
title = thread_object.get("thread_title", "Threads Video")[:100]
|
||||
description = thread_object.get("thread_post", "")[:500]
|
||||
|
||||
# Tìm thumbnail nếu có
|
||||
thumbnail_path = None
|
||||
thumb_candidate = f"./assets/temp/{thread_id}/thumbnail.png"
|
||||
if os.path.exists(thumb_candidate):
|
||||
thumbnail_path = thumb_candidate
|
||||
|
||||
results = manager.upload_to_all(
|
||||
video_path=video_path,
|
||||
title=title,
|
||||
description=description,
|
||||
thumbnail_path=thumbnail_path,
|
||||
)
|
||||
|
||||
print_step("📊 Kết quả upload:")
|
||||
for platform, url in results.items():
|
||||
if url:
|
||||
print_substep(f" ✅ {platform}: {url}", style="bold green")
|
||||
else:
|
||||
print_substep(f" ❌ {platform}: Thất bại", style="bold red")
|
||||
|
||||
print_step("✅ Pipeline hoàn tất!")
|
||||
|
||||
# Lưu title vào lịch sử để tránh tạo trùng lặp
|
||||
title = thread_object.get("thread_title", "")
|
||||
tid = thread_object.get("thread_id", "")
|
||||
if title:
|
||||
save_title(title=title, thread_id=tid, source="threads")
|
||||
|
||||
return video_path
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"❌ Lỗi pipeline: {e}", style="bold red")
|
||||
raise
|
||||
|
||||
|
||||
def run_scheduled():
|
||||
"""Chạy pipeline theo lịch trình đã cấu hình.
|
||||
|
||||
Sử dụng APScheduler để lên lịch.
|
||||
"""
|
||||
try:
|
||||
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
except ImportError:
|
||||
print_substep(
|
||||
"Cần cài đặt APScheduler: pip install apscheduler",
|
||||
style="bold red",
|
||||
)
|
||||
return
|
||||
|
||||
scheduler_config = settings.config.get("scheduler", {})
|
||||
enabled = scheduler_config.get("enabled", False)
|
||||
|
||||
if not enabled:
|
||||
print_substep("Scheduler chưa được kích hoạt trong config!", style="bold yellow")
|
||||
return
|
||||
|
||||
timezone = scheduler_config.get("timezone", "Asia/Ho_Chi_Minh")
|
||||
cron_expression = scheduler_config.get(
|
||||
"cron", "0 */3 * * *"
|
||||
) # Mặc định mỗi 3 giờ (8 lần/ngày: 00, 03, 06, 09, 12, 15, 18, 21h)
|
||||
max_videos_per_day = scheduler_config.get("max_videos_per_day", 8)
|
||||
|
||||
# Parse cron expression
|
||||
cron_parts = cron_expression.split()
|
||||
if len(cron_parts) != 5:
|
||||
print_substep(
|
||||
"Cron expression không hợp lệ! Format: minute hour day month weekday", style="bold red"
|
||||
)
|
||||
return
|
||||
|
||||
scheduler = BlockingScheduler(timezone=timezone)
|
||||
|
||||
videos_today = {"count": 0, "date": datetime.now().strftime("%Y-%m-%d")}
|
||||
|
||||
def scheduled_job():
|
||||
"""Job được chạy theo lịch."""
|
||||
current_date = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# Reset counter nếu sang ngày mới
|
||||
if current_date != videos_today["date"]:
|
||||
videos_today["count"] = 0
|
||||
videos_today["date"] = current_date
|
||||
|
||||
if videos_today["count"] >= max_videos_per_day:
|
||||
print_substep(
|
||||
f"Đã đạt giới hạn {max_videos_per_day} video/ngày. Bỏ qua.",
|
||||
style="bold yellow",
|
||||
)
|
||||
return
|
||||
|
||||
print_step(f"⏰ Scheduler: Bắt đầu tạo video lúc {datetime.now().strftime('%H:%M:%S')}...")
|
||||
try:
|
||||
result = run_pipeline()
|
||||
if result:
|
||||
videos_today["count"] += 1
|
||||
print_substep(
|
||||
f"Video #{videos_today['count']}/{max_videos_per_day} ngày hôm nay",
|
||||
style="bold blue",
|
||||
)
|
||||
except Exception as e:
|
||||
print_substep(f"Scheduler job thất bại: {e}", style="bold red")
|
||||
|
||||
trigger = CronTrigger(
|
||||
minute=cron_parts[0],
|
||||
hour=cron_parts[1],
|
||||
day=cron_parts[2],
|
||||
month=cron_parts[3],
|
||||
day_of_week=cron_parts[4],
|
||||
timezone=timezone,
|
||||
)
|
||||
|
||||
scheduler.add_job(scheduled_job, trigger, id="video_pipeline", replace_existing=True)
|
||||
|
||||
print_step(f"📅 Scheduler đã khởi động!")
|
||||
print_substep(f" Cron: {cron_expression}", style="bold blue")
|
||||
print_substep(f" Timezone: {timezone}", style="bold blue")
|
||||
print_substep(f" Max videos/ngày: {max_videos_per_day}", style="bold blue")
|
||||
print_substep(" Nhấn Ctrl+C để dừng", style="bold yellow")
|
||||
|
||||
try:
|
||||
scheduler.start()
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
scheduler.shutdown()
|
||||
print_step("Scheduler đã dừng.")
|
||||
@ -0,0 +1,268 @@
|
||||
"""
|
||||
Threads API Client - Lấy nội dung từ Meta Threads cho thị trường Việt Nam.
|
||||
|
||||
Meta Threads API sử dụng Graph API endpoint.
|
||||
Docs: https://developers.facebook.com/docs/threads
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import requests
|
||||
|
||||
from utils import settings
|
||||
from utils.console import print_step, print_substep
|
||||
from utils.title_history import is_title_used
|
||||
from utils.videos import check_done
|
||||
from utils.voice import sanitize_text
|
||||
|
||||
THREADS_API_BASE = "https://graph.threads.net/v1.0"
|
||||
|
||||
|
||||
class ThreadsClient:
|
||||
"""Client để tương tác với Threads API (Meta)."""
|
||||
|
||||
def __init__(self):
|
||||
self.access_token = settings.config["threads"]["creds"]["access_token"]
|
||||
self.user_id = settings.config["threads"]["creds"]["user_id"]
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
"Authorization": f"Bearer {self.access_token}",
|
||||
}
|
||||
)
|
||||
|
||||
def _get(self, endpoint: str, params: Optional[dict] = None) -> dict:
|
||||
"""Make a GET request to the Threads API."""
|
||||
url = f"{THREADS_API_BASE}/{endpoint}"
|
||||
if params is None:
|
||||
params = {}
|
||||
params["access_token"] = self.access_token
|
||||
response = self.session.get(url, params=params)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_user_threads(self, user_id: Optional[str] = None, limit: int = 25) -> List[dict]:
|
||||
"""Lấy danh sách threads của user.
|
||||
|
||||
Args:
|
||||
user_id: Threads user ID. Mặc định là user đã cấu hình.
|
||||
limit: Số lượng threads tối đa cần lấy.
|
||||
|
||||
Returns:
|
||||
Danh sách các thread objects.
|
||||
"""
|
||||
uid = user_id or self.user_id
|
||||
data = self._get(
|
||||
f"{uid}/threads",
|
||||
params={
|
||||
"fields": "id,media_type,media_url,permalink,text,timestamp,username,shortcode,is_reply,reply_audience",
|
||||
"limit": limit,
|
||||
},
|
||||
)
|
||||
return data.get("data", [])
|
||||
|
||||
def get_thread_replies(self, thread_id: str, limit: int = 50) -> List[dict]:
|
||||
"""Lấy replies (comments) của một thread.
|
||||
|
||||
Args:
|
||||
thread_id: ID của thread.
|
||||
limit: Số lượng replies tối đa.
|
||||
|
||||
Returns:
|
||||
Danh sách replies.
|
||||
"""
|
||||
data = self._get(
|
||||
f"{thread_id}/replies",
|
||||
params={
|
||||
"fields": "id,text,timestamp,username,permalink,hide_status",
|
||||
"limit": limit,
|
||||
"reverse": "true",
|
||||
},
|
||||
)
|
||||
return data.get("data", [])
|
||||
|
||||
def get_thread_by_id(self, thread_id: str) -> dict:
|
||||
"""Lấy thông tin chi tiết của một thread.
|
||||
|
||||
Args:
|
||||
thread_id: ID của thread.
|
||||
|
||||
Returns:
|
||||
Thread object.
|
||||
"""
|
||||
return self._get(
|
||||
thread_id,
|
||||
params={
|
||||
"fields": "id,media_type,media_url,permalink,text,timestamp,username,shortcode",
|
||||
},
|
||||
)
|
||||
|
||||
def search_threads_by_keyword(self, threads: List[dict], keywords: List[str]) -> List[dict]:
|
||||
"""Lọc threads theo từ khóa.
|
||||
|
||||
Args:
|
||||
threads: Danh sách threads.
|
||||
keywords: Danh sách từ khóa cần tìm.
|
||||
|
||||
Returns:
|
||||
Danh sách threads chứa từ khóa.
|
||||
"""
|
||||
filtered = []
|
||||
for thread in threads:
|
||||
text = thread.get("text", "").lower()
|
||||
for keyword in keywords:
|
||||
if keyword.lower() in text:
|
||||
filtered.append(thread)
|
||||
break
|
||||
return filtered
|
||||
|
||||
|
||||
def _contains_blocked_words(text: str) -> bool:
|
||||
"""Kiểm tra xem text có chứa từ bị chặn không."""
|
||||
blocked_words = settings.config["threads"]["thread"].get("blocked_words", "")
|
||||
if not blocked_words:
|
||||
return False
|
||||
blocked_list = [w.strip().lower() for w in blocked_words.split(",") if w.strip()]
|
||||
text_lower = text.lower()
|
||||
return any(word in text_lower for word in blocked_list)
|
||||
|
||||
|
||||
def get_threads_posts(POST_ID: str = None) -> dict:
|
||||
"""Lấy nội dung từ Threads để tạo video.
|
||||
|
||||
Tương tự get_subreddit_threads() nhưng cho Threads.
|
||||
|
||||
Args:
|
||||
POST_ID: ID cụ thể của thread. Nếu None, lấy thread mới nhất phù hợp.
|
||||
|
||||
Returns:
|
||||
Dict chứa thread content và replies.
|
||||
"""
|
||||
print_substep("Đang kết nối với Threads API...")
|
||||
|
||||
client = ThreadsClient()
|
||||
content = {}
|
||||
|
||||
thread_config = settings.config["threads"]["thread"]
|
||||
max_comment_length = int(thread_config.get("max_comment_length", 500))
|
||||
min_comment_length = int(thread_config.get("min_comment_length", 1))
|
||||
min_comments = int(thread_config.get("min_comments", 5))
|
||||
|
||||
print_step("Đang lấy nội dung từ Threads...")
|
||||
|
||||
if POST_ID:
|
||||
# Lấy thread cụ thể theo ID
|
||||
thread = client.get_thread_by_id(POST_ID)
|
||||
else:
|
||||
# Lấy threads mới nhất và chọn thread phù hợp
|
||||
target_user = thread_config.get("target_user_id", "") or client.user_id
|
||||
threads_list = client.get_user_threads(user_id=target_user, limit=25)
|
||||
|
||||
if not threads_list:
|
||||
print_substep("Không tìm thấy threads nào!", style="bold red")
|
||||
raise ValueError("No threads found")
|
||||
|
||||
# Lọc theo từ khóa nếu có
|
||||
keywords = thread_config.get("keywords", "")
|
||||
if keywords:
|
||||
keyword_list = [k.strip() for k in keywords.split(",") if k.strip()]
|
||||
threads_list = client.search_threads_by_keyword(threads_list, keyword_list)
|
||||
|
||||
# Chọn thread phù hợp (chưa tạo video, đủ replies, title chưa dùng)
|
||||
thread = None
|
||||
for t in threads_list:
|
||||
thread_id = t.get("id", "")
|
||||
# Kiểm tra xem đã tạo video cho thread này chưa
|
||||
text = t.get("text", "")
|
||||
if not text or _contains_blocked_words(text):
|
||||
continue
|
||||
# Kiểm tra title đã được sử dụng chưa (tránh trùng lặp)
|
||||
title_candidate = text[:200] if len(text) > 200 else text
|
||||
if is_title_used(title_candidate):
|
||||
print_substep(
|
||||
f"Bỏ qua thread đã tạo video: {text[:50]}...",
|
||||
style="bold yellow",
|
||||
)
|
||||
continue
|
||||
# Kiểm tra số lượng replies
|
||||
try:
|
||||
replies = client.get_thread_replies(thread_id, limit=min_comments + 5)
|
||||
if len(replies) >= min_comments:
|
||||
thread = t
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if thread is None:
|
||||
# Nếu không tìm được thread đủ comments, lấy thread đầu tiên
|
||||
if threads_list:
|
||||
thread = threads_list[0]
|
||||
else:
|
||||
print_substep("Không tìm thấy thread phù hợp!", style="bold red")
|
||||
raise ValueError("No suitable thread found")
|
||||
|
||||
thread_id = thread.get("id", "")
|
||||
thread_text = thread.get("text", "")
|
||||
thread_url = thread.get(
|
||||
"permalink", f"https://www.threads.net/post/{thread.get('shortcode', '')}"
|
||||
)
|
||||
thread_username = thread.get("username", "unknown")
|
||||
|
||||
print_substep(f"Video sẽ được tạo từ: {thread_text[:100]}...", style="bold green")
|
||||
print_substep(f"Thread URL: {thread_url}", style="bold green")
|
||||
print_substep(f"Tác giả: @{thread_username}", style="bold blue")
|
||||
|
||||
content["thread_url"] = thread_url
|
||||
content["thread_title"] = thread_text[:200] if len(thread_text) > 200 else thread_text
|
||||
content["thread_id"] = re.sub(r"[^\w\s-]", "", thread_id)
|
||||
content["thread_author"] = f"@{thread_username}"
|
||||
content["is_nsfw"] = False
|
||||
content["thread_post"] = thread_text
|
||||
content["comments"] = []
|
||||
|
||||
if settings.config["settings"].get("storymode", False):
|
||||
# Story mode - đọc toàn bộ nội dung bài viết
|
||||
content["thread_post"] = thread_text
|
||||
else:
|
||||
# Comment mode - lấy replies
|
||||
try:
|
||||
replies = client.get_thread_replies(thread_id, limit=50)
|
||||
except Exception as e:
|
||||
print_substep(f"Lỗi khi lấy replies: {e}", style="bold red")
|
||||
replies = []
|
||||
|
||||
for reply in replies:
|
||||
reply_text = reply.get("text", "")
|
||||
reply_username = reply.get("username", "unknown")
|
||||
|
||||
if not reply_text:
|
||||
continue
|
||||
if reply.get("hide_status", "") == "HIDDEN":
|
||||
continue
|
||||
if _contains_blocked_words(reply_text):
|
||||
continue
|
||||
|
||||
sanitised = sanitize_text(reply_text)
|
||||
if not sanitised or sanitised.strip() == "":
|
||||
continue
|
||||
|
||||
if len(reply_text) > max_comment_length:
|
||||
continue
|
||||
if len(reply_text) < min_comment_length:
|
||||
continue
|
||||
|
||||
content["comments"].append(
|
||||
{
|
||||
"comment_body": reply_text,
|
||||
"comment_url": reply.get("permalink", ""),
|
||||
"comment_id": re.sub(r"[^\w\s-]", "", reply.get("id", "")),
|
||||
"comment_author": f"@{reply_username}",
|
||||
}
|
||||
)
|
||||
|
||||
print_substep(
|
||||
f"Đã lấy nội dung từ Threads thành công! ({len(content.get('comments', []))} replies)",
|
||||
style="bold green",
|
||||
)
|
||||
return content
|
||||
@ -0,0 +1,129 @@
|
||||
"""
|
||||
Base Uploader - Lớp cơ sở cho tất cả uploaders.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional
|
||||
|
||||
from utils.console import print_step, print_substep
|
||||
|
||||
|
||||
@dataclass
|
||||
class VideoMetadata:
|
||||
"""Metadata cho video cần upload."""
|
||||
|
||||
file_path: str
|
||||
title: str
|
||||
description: str = ""
|
||||
tags: List[str] = field(default_factory=list)
|
||||
hashtags: List[str] = field(default_factory=list)
|
||||
thumbnail_path: Optional[str] = None
|
||||
schedule_time: Optional[str] = None # ISO 8601 format
|
||||
privacy: str = "public" # public, private, unlisted
|
||||
category: str = "Entertainment"
|
||||
language: str = "vi" # Vietnamese
|
||||
|
||||
|
||||
class BaseUploader(ABC):
|
||||
"""Lớp cơ sở cho tất cả platform uploaders."""
|
||||
|
||||
platform_name: str = "Unknown"
|
||||
|
||||
def __init__(self):
|
||||
self._authenticated = False
|
||||
|
||||
@abstractmethod
|
||||
def authenticate(self) -> bool:
|
||||
"""Xác thực với platform API.
|
||||
|
||||
Returns:
|
||||
True nếu xác thực thành công.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def upload(self, metadata: VideoMetadata) -> Optional[str]:
|
||||
"""Upload video lên platform.
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
|
||||
Returns:
|
||||
URL của video đã upload, hoặc None nếu thất bại.
|
||||
"""
|
||||
pass
|
||||
|
||||
def validate_video(self, metadata: VideoMetadata) -> bool:
|
||||
"""Kiểm tra video có hợp lệ trước khi upload.
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata cần kiểm tra.
|
||||
|
||||
Returns:
|
||||
True nếu hợp lệ.
|
||||
"""
|
||||
if not os.path.exists(metadata.file_path):
|
||||
print_substep(
|
||||
f"[{self.platform_name}] File không tồn tại: {metadata.file_path}", style="bold red"
|
||||
)
|
||||
return False
|
||||
|
||||
file_size = os.path.getsize(metadata.file_path)
|
||||
if file_size == 0:
|
||||
print_substep(
|
||||
f"[{self.platform_name}] File rỗng: {metadata.file_path}", style="bold red"
|
||||
)
|
||||
return False
|
||||
|
||||
if not metadata.title:
|
||||
print_substep(f"[{self.platform_name}] Thiếu tiêu đề video", style="bold red")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def safe_upload(self, metadata: VideoMetadata, max_retries: int = 3) -> Optional[str]:
|
||||
"""Upload video với retry logic.
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
max_retries: Số lần thử lại tối đa.
|
||||
|
||||
Returns:
|
||||
URL của video đã upload, hoặc None nếu thất bại.
|
||||
"""
|
||||
if not self.validate_video(metadata):
|
||||
return None
|
||||
|
||||
if not self._authenticated:
|
||||
print_step(f"Đang xác thực với {self.platform_name}...")
|
||||
if not self.authenticate():
|
||||
print_substep(f"Xác thực {self.platform_name} thất bại!", style="bold red")
|
||||
return None
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
print_step(f"Đang upload lên {self.platform_name} (lần {attempt}/{max_retries})...")
|
||||
url = self.upload(metadata)
|
||||
if url:
|
||||
print_substep(
|
||||
f"Upload {self.platform_name} thành công! URL: {url}",
|
||||
style="bold green",
|
||||
)
|
||||
return url
|
||||
except Exception as e:
|
||||
print_substep(
|
||||
f"[{self.platform_name}] Lỗi upload (lần {attempt}): {e}",
|
||||
style="bold red",
|
||||
)
|
||||
if attempt < max_retries:
|
||||
backoff = min(2**attempt, 60) # Exponential backoff, max 60s
|
||||
print_substep(f"Chờ {backoff}s trước khi thử lại...", style="bold yellow")
|
||||
time.sleep(backoff)
|
||||
|
||||
print_substep(
|
||||
f"Upload {self.platform_name} thất bại sau {max_retries} lần thử!", style="bold red"
|
||||
)
|
||||
return None
|
||||
@ -0,0 +1,218 @@
|
||||
"""
|
||||
Facebook Uploader - Upload video lên Facebook sử dụng Graph API.
|
||||
|
||||
Yêu cầu:
|
||||
- Facebook Developer App
|
||||
- Page Access Token (cho Page upload) hoặc User Access Token
|
||||
- Permissions: publish_video, pages_manage_posts
|
||||
Docs: https://developers.facebook.com/docs/video-api/guides/publishing
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
|
||||
from uploaders.base_uploader import BaseUploader, VideoMetadata
|
||||
from utils import settings
|
||||
from utils.console import print_substep
|
||||
|
||||
|
||||
class FacebookUploader(BaseUploader):
|
||||
"""Upload video lên Facebook Page/Profile."""
|
||||
|
||||
platform_name = "Facebook"
|
||||
|
||||
# Facebook API endpoints
|
||||
GRAPH_API_BASE = "https://graph.facebook.com/v21.0"
|
||||
|
||||
# Limits
|
||||
MAX_DESCRIPTION_LENGTH = 63206
|
||||
MAX_TITLE_LENGTH = 255
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024 * 1024 # 10 GB
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.config = settings.config.get("uploaders", {}).get("facebook", {})
|
||||
self.access_token = None
|
||||
self.page_id = None
|
||||
|
||||
def authenticate(self) -> bool:
|
||||
"""Xác thực với Facebook Graph API.
|
||||
|
||||
Sử dụng Page Access Token cho upload lên Page.
|
||||
|
||||
Returns:
|
||||
True nếu xác thực thành công.
|
||||
"""
|
||||
self.access_token = self.config.get("access_token", "")
|
||||
self.page_id = self.config.get("page_id", "")
|
||||
|
||||
if not self.access_token:
|
||||
print_substep("Facebook: Thiếu access_token", style="bold red")
|
||||
return False
|
||||
|
||||
if not self.page_id:
|
||||
print_substep("Facebook: Thiếu page_id", style="bold red")
|
||||
return False
|
||||
|
||||
# Verify token
|
||||
try:
|
||||
response = requests.get(
|
||||
f"{self.GRAPH_API_BASE}/me",
|
||||
params={"access_token": self.access_token},
|
||||
timeout=15,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if "id" in data:
|
||||
self._authenticated = True
|
||||
print_substep(
|
||||
f"Facebook: Xác thực thành công (Page: {data.get('name', self.page_id)}) ✅",
|
||||
style="bold green",
|
||||
)
|
||||
return True
|
||||
else:
|
||||
print_substep("Facebook: Token không hợp lệ", style="bold red")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"Facebook: Lỗi xác thực - {e}", style="bold red")
|
||||
return False
|
||||
|
||||
def upload(self, metadata: VideoMetadata) -> Optional[str]:
|
||||
"""Upload video lên Facebook Page.
|
||||
|
||||
Sử dụng Resumable Upload API cho file lớn.
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
|
||||
Returns:
|
||||
URL video trên Facebook, hoặc None nếu thất bại.
|
||||
"""
|
||||
if not self.access_token or not self.page_id:
|
||||
return None
|
||||
|
||||
file_size = os.path.getsize(metadata.file_path)
|
||||
|
||||
title = metadata.title[: self.MAX_TITLE_LENGTH]
|
||||
description = self._build_description(metadata)
|
||||
|
||||
# Step 1: Initialize upload session
|
||||
try:
|
||||
init_response = requests.post(
|
||||
f"{self.GRAPH_API_BASE}/{self.page_id}/videos",
|
||||
data={
|
||||
"upload_phase": "start",
|
||||
"file_size": file_size,
|
||||
"access_token": self.access_token,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
init_response.raise_for_status()
|
||||
init_data = init_response.json()
|
||||
|
||||
upload_session_id = init_data.get("upload_session_id", "")
|
||||
video_id = init_data.get("video_id", "")
|
||||
|
||||
if not upload_session_id:
|
||||
print_substep("Facebook: Không thể khởi tạo upload session", style="bold red")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"Facebook: Lỗi khởi tạo upload - {e}", style="bold red")
|
||||
return None
|
||||
|
||||
# Step 2: Upload video chunks
|
||||
try:
|
||||
chunk_size = 4 * 1024 * 1024 # 4 MB chunks
|
||||
start_offset = 0
|
||||
|
||||
with open(metadata.file_path, "rb") as video_file:
|
||||
while start_offset < file_size:
|
||||
chunk = video_file.read(chunk_size)
|
||||
transfer_response = requests.post(
|
||||
f"{self.GRAPH_API_BASE}/{self.page_id}/videos",
|
||||
data={
|
||||
"upload_phase": "transfer",
|
||||
"upload_session_id": upload_session_id,
|
||||
"start_offset": start_offset,
|
||||
"access_token": self.access_token,
|
||||
},
|
||||
files={"video_file_chunk": ("chunk", chunk, "application/octet-stream")},
|
||||
timeout=120,
|
||||
)
|
||||
transfer_response.raise_for_status()
|
||||
transfer_data = transfer_response.json()
|
||||
|
||||
start_offset = int(transfer_data.get("start_offset", file_size))
|
||||
end_offset = int(transfer_data.get("end_offset", file_size))
|
||||
|
||||
if start_offset >= file_size:
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"Facebook: Lỗi upload file - {e}", style="bold red")
|
||||
return None
|
||||
|
||||
# Step 3: Finish upload
|
||||
try:
|
||||
finish_data = {
|
||||
"upload_phase": "finish",
|
||||
"upload_session_id": upload_session_id,
|
||||
"access_token": self.access_token,
|
||||
"title": title,
|
||||
"description": description[: self.MAX_DESCRIPTION_LENGTH],
|
||||
}
|
||||
|
||||
if metadata.schedule_time:
|
||||
finish_data["scheduled_publish_time"] = metadata.schedule_time
|
||||
finish_data["published"] = "false"
|
||||
|
||||
if metadata.thumbnail_path and os.path.exists(metadata.thumbnail_path):
|
||||
with open(metadata.thumbnail_path, "rb") as thumb:
|
||||
finish_response = requests.post(
|
||||
f"{self.GRAPH_API_BASE}/{self.page_id}/videos",
|
||||
data=finish_data,
|
||||
files={"thumb": thumb},
|
||||
timeout=60,
|
||||
)
|
||||
else:
|
||||
finish_response = requests.post(
|
||||
f"{self.GRAPH_API_BASE}/{self.page_id}/videos",
|
||||
data=finish_data,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
finish_response.raise_for_status()
|
||||
finish_result = finish_response.json()
|
||||
|
||||
if finish_result.get("success", False):
|
||||
video_url = f"https://www.facebook.com/{self.page_id}/videos/{video_id}"
|
||||
return video_url
|
||||
else:
|
||||
print_substep("Facebook: Upload hoàn tất nhưng không thành công", style="bold red")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"Facebook: Lỗi kết thúc upload - {e}", style="bold red")
|
||||
return None
|
||||
|
||||
def _build_description(self, metadata: VideoMetadata) -> str:
|
||||
"""Tạo description cho video Facebook."""
|
||||
parts = []
|
||||
if metadata.description:
|
||||
parts.append(metadata.description)
|
||||
|
||||
if metadata.hashtags:
|
||||
hashtag_str = " ".join(f"#{tag}" for tag in metadata.hashtags)
|
||||
parts.append(hashtag_str)
|
||||
|
||||
parts.append("")
|
||||
parts.append("🎬 Video được tạo tự động bởi Threads Video Maker Bot")
|
||||
|
||||
return "\n".join(parts)
|
||||
@ -0,0 +1,227 @@
|
||||
"""
|
||||
TikTok Uploader - Upload video lên TikTok sử dụng Content Posting API.
|
||||
|
||||
Yêu cầu:
|
||||
- TikTok Developer App
|
||||
- Content Posting API access
|
||||
- OAuth2 access token
|
||||
Docs: https://developers.tiktok.com/doc/content-posting-api-get-started
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
|
||||
from uploaders.base_uploader import BaseUploader, VideoMetadata
|
||||
from utils import settings
|
||||
from utils.console import print_substep
|
||||
|
||||
|
||||
class TikTokUploader(BaseUploader):
|
||||
"""Upload video lên TikTok."""
|
||||
|
||||
platform_name = "TikTok"
|
||||
|
||||
# TikTok API endpoints
|
||||
API_BASE = "https://open.tiktokapis.com/v2"
|
||||
TOKEN_URL = "https://open.tiktokapis.com/v2/oauth/token/"
|
||||
|
||||
# Limits
|
||||
MAX_CAPTION_LENGTH = 2200
|
||||
MAX_FILE_SIZE = 4 * 1024 * 1024 * 1024 # 4 GB
|
||||
MIN_DURATION = 3 # seconds
|
||||
MAX_DURATION = 600 # 10 minutes
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.config = settings.config.get("uploaders", {}).get("tiktok", {})
|
||||
self.access_token = None
|
||||
|
||||
def authenticate(self) -> bool:
|
||||
"""Xác thực với TikTok API sử dụng refresh token.
|
||||
|
||||
Returns:
|
||||
True nếu xác thực thành công.
|
||||
"""
|
||||
client_key = self.config.get("client_key", "")
|
||||
client_secret = self.config.get("client_secret", "")
|
||||
refresh_token = self.config.get("refresh_token", "")
|
||||
|
||||
if not all([client_key, client_secret, refresh_token]):
|
||||
print_substep(
|
||||
"TikTok: Thiếu credentials (client_key, client_secret, refresh_token)",
|
||||
style="bold red",
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.TOKEN_URL,
|
||||
json={
|
||||
"client_key": client_key,
|
||||
"client_secret": client_secret,
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
token_data = response.json()
|
||||
self.access_token = token_data.get("data", {}).get("access_token", "")
|
||||
|
||||
if self.access_token:
|
||||
self._authenticated = True
|
||||
print_substep("TikTok: Xác thực thành công! ✅", style="bold green")
|
||||
return True
|
||||
else:
|
||||
print_substep("TikTok: Không lấy được access token", style="bold red")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"TikTok: Lỗi xác thực - {e}", style="bold red")
|
||||
return False
|
||||
|
||||
def upload(self, metadata: VideoMetadata) -> Optional[str]:
|
||||
"""Upload video lên TikTok sử dụng Content Posting API.
|
||||
|
||||
Flow:
|
||||
1. Initialize upload → get upload_url
|
||||
2. Upload video file to upload_url
|
||||
3. Publish video
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
|
||||
Returns:
|
||||
URL video trên TikTok, hoặc None nếu thất bại.
|
||||
"""
|
||||
if not self.access_token:
|
||||
return None
|
||||
|
||||
file_size = os.path.getsize(metadata.file_path)
|
||||
if file_size > self.MAX_FILE_SIZE:
|
||||
print_substep(f"TikTok: File quá lớn ({file_size} bytes)", style="bold red")
|
||||
return None
|
||||
|
||||
# Build caption
|
||||
caption = self._build_caption(metadata)
|
||||
|
||||
# Step 1: Initialize upload
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.access_token}",
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
}
|
||||
|
||||
init_body = {
|
||||
"post_info": {
|
||||
"title": caption,
|
||||
"privacy_level": self._map_privacy(metadata.privacy),
|
||||
"disable_duet": False,
|
||||
"disable_comment": False,
|
||||
"disable_stitch": False,
|
||||
},
|
||||
"source_info": {
|
||||
"source": "FILE_UPLOAD",
|
||||
"video_size": file_size,
|
||||
"chunk_size": file_size, # Single chunk upload
|
||||
"total_chunk_count": 1,
|
||||
},
|
||||
}
|
||||
|
||||
if metadata.schedule_time:
|
||||
init_body["post_info"]["schedule_time"] = metadata.schedule_time
|
||||
|
||||
try:
|
||||
init_response = requests.post(
|
||||
f"{self.API_BASE}/post/publish/inbox/video/init/",
|
||||
headers=headers,
|
||||
json=init_body,
|
||||
timeout=30,
|
||||
)
|
||||
init_response.raise_for_status()
|
||||
init_data = init_response.json()
|
||||
|
||||
publish_id = init_data.get("data", {}).get("publish_id", "")
|
||||
upload_url = init_data.get("data", {}).get("upload_url", "")
|
||||
|
||||
if not upload_url:
|
||||
print_substep("TikTok: Không lấy được upload URL", style="bold red")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"TikTok: Lỗi khởi tạo upload - {e}", style="bold red")
|
||||
return None
|
||||
|
||||
# Step 2: Upload video file
|
||||
try:
|
||||
with open(metadata.file_path, "rb") as video_file:
|
||||
upload_headers = {
|
||||
"Content-Type": "video/mp4",
|
||||
"Content-Length": str(file_size),
|
||||
"Content-Range": f"bytes 0-{file_size - 1}/{file_size}",
|
||||
}
|
||||
upload_response = requests.put(
|
||||
upload_url,
|
||||
headers=upload_headers,
|
||||
data=video_file,
|
||||
timeout=600,
|
||||
)
|
||||
upload_response.raise_for_status()
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"TikTok: Lỗi upload file - {e}", style="bold red")
|
||||
return None
|
||||
|
||||
# Step 3: Check publish status
|
||||
status_url = f"{self.API_BASE}/post/publish/status/fetch/"
|
||||
for attempt in range(10):
|
||||
try:
|
||||
status_response = requests.post(
|
||||
status_url,
|
||||
headers=headers,
|
||||
json={"publish_id": publish_id},
|
||||
timeout=30,
|
||||
)
|
||||
status_data = status_response.json()
|
||||
status = status_data.get("data", {}).get("status", "")
|
||||
|
||||
if status == "PUBLISH_COMPLETE":
|
||||
print_substep("TikTok: Upload thành công! ✅", style="bold green")
|
||||
return f"https://www.tiktok.com/@user/video/{publish_id}"
|
||||
elif status == "FAILED":
|
||||
reason = status_data.get("data", {}).get("fail_reason", "Unknown")
|
||||
print_substep(f"TikTok: Upload thất bại - {reason}", style="bold red")
|
||||
return None
|
||||
|
||||
time.sleep(5) # Wait 5 seconds before checking again
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
|
||||
print_substep("TikTok: Upload timeout", style="bold yellow")
|
||||
return None
|
||||
|
||||
def _build_caption(self, metadata: VideoMetadata) -> str:
|
||||
"""Tạo caption cho video TikTok."""
|
||||
parts = []
|
||||
if metadata.title:
|
||||
parts.append(metadata.title)
|
||||
if metadata.hashtags:
|
||||
hashtag_str = " ".join(f"#{tag}" for tag in metadata.hashtags)
|
||||
parts.append(hashtag_str)
|
||||
caption = " ".join(parts)
|
||||
return caption[: self.MAX_CAPTION_LENGTH]
|
||||
|
||||
@staticmethod
|
||||
def _map_privacy(privacy: str) -> str:
|
||||
"""Map privacy setting to TikTok format."""
|
||||
mapping = {
|
||||
"public": "PUBLIC_TO_EVERYONE",
|
||||
"private": "SELF_ONLY",
|
||||
"friends": "MUTUAL_FOLLOW_FRIENDS",
|
||||
"unlisted": "SELF_ONLY",
|
||||
}
|
||||
return mapping.get(privacy, "PUBLIC_TO_EVERYONE")
|
||||
@ -0,0 +1,137 @@
|
||||
"""
|
||||
Upload Manager - Quản lý upload video lên nhiều platform cùng lúc.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from uploaders.base_uploader import BaseUploader, VideoMetadata
|
||||
from uploaders.facebook_uploader import FacebookUploader
|
||||
from uploaders.tiktok_uploader import TikTokUploader
|
||||
from uploaders.youtube_uploader import YouTubeUploader
|
||||
from utils import settings
|
||||
from utils.console import print_step, print_substep
|
||||
|
||||
|
||||
class UploadManager:
|
||||
"""Quản lý upload video lên nhiều platform."""
|
||||
|
||||
PLATFORM_MAP = {
|
||||
"youtube": YouTubeUploader,
|
||||
"tiktok": TikTokUploader,
|
||||
"facebook": FacebookUploader,
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.uploaders: Dict[str, BaseUploader] = {}
|
||||
self._init_uploaders()
|
||||
|
||||
def _init_uploaders(self):
|
||||
"""Khởi tạo uploaders dựa trên cấu hình."""
|
||||
upload_config = settings.config.get("uploaders", {})
|
||||
|
||||
for platform_name, uploader_class in self.PLATFORM_MAP.items():
|
||||
platform_config = upload_config.get(platform_name, {})
|
||||
if platform_config.get("enabled", False):
|
||||
self.uploaders[platform_name] = uploader_class()
|
||||
print_substep(f"Đã kích hoạt uploader: {platform_name}", style="bold blue")
|
||||
|
||||
def upload_to_all(
|
||||
self,
|
||||
video_path: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
tags: Optional[List[str]] = None,
|
||||
hashtags: Optional[List[str]] = None,
|
||||
thumbnail_path: Optional[str] = None,
|
||||
schedule_time: Optional[str] = None,
|
||||
privacy: str = "public",
|
||||
) -> Dict[str, Optional[str]]:
|
||||
"""Upload video lên tất cả platform đã cấu hình.
|
||||
|
||||
Args:
|
||||
video_path: Đường dẫn file video.
|
||||
title: Tiêu đề video.
|
||||
description: Mô tả video.
|
||||
tags: Danh sách tags.
|
||||
hashtags: Danh sách hashtags.
|
||||
thumbnail_path: Đường dẫn thumbnail.
|
||||
schedule_time: Thời gian lên lịch (ISO 8601).
|
||||
privacy: Quyền riêng tư (public/private/unlisted).
|
||||
|
||||
Returns:
|
||||
Dict mapping platform name -> video URL (hoặc None nếu thất bại).
|
||||
"""
|
||||
if not self.uploaders:
|
||||
print_substep("Không có uploader nào được kích hoạt!", style="bold yellow")
|
||||
return {}
|
||||
|
||||
metadata = VideoMetadata(
|
||||
file_path=video_path,
|
||||
title=title,
|
||||
description=description,
|
||||
tags=tags or [],
|
||||
hashtags=hashtags or self._default_hashtags(),
|
||||
thumbnail_path=thumbnail_path,
|
||||
schedule_time=schedule_time,
|
||||
privacy=privacy,
|
||||
language="vi",
|
||||
)
|
||||
|
||||
results = {}
|
||||
print_step(f"Đang upload video lên {len(self.uploaders)} platform...")
|
||||
|
||||
for platform_name, uploader in self.uploaders.items():
|
||||
print_step(f"📤 Đang upload lên {platform_name}...")
|
||||
url = uploader.safe_upload(metadata)
|
||||
results[platform_name] = url
|
||||
|
||||
# Summary
|
||||
print_step("📊 Kết quả upload:")
|
||||
success_count = 0
|
||||
for platform, url in results.items():
|
||||
if url:
|
||||
print_substep(f" ✅ {platform}: {url}", style="bold green")
|
||||
success_count += 1
|
||||
else:
|
||||
print_substep(f" ❌ {platform}: Thất bại", style="bold red")
|
||||
|
||||
print_substep(
|
||||
f"Upload hoàn tất: {success_count}/{len(results)} platform thành công",
|
||||
style="bold blue",
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
def upload_to_platform(
|
||||
self,
|
||||
platform_name: str,
|
||||
metadata: VideoMetadata,
|
||||
) -> Optional[str]:
|
||||
"""Upload video lên một platform cụ thể.
|
||||
|
||||
Args:
|
||||
platform_name: Tên platform.
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
|
||||
Returns:
|
||||
URL video, hoặc None nếu thất bại.
|
||||
"""
|
||||
if platform_name not in self.uploaders:
|
||||
print_substep(f"Platform '{platform_name}' chưa được kích hoạt!", style="bold red")
|
||||
return None
|
||||
|
||||
return self.uploaders[platform_name].safe_upload(metadata)
|
||||
|
||||
@staticmethod
|
||||
def _default_hashtags() -> List[str]:
|
||||
"""Hashtags mặc định cho thị trường Việt Nam."""
|
||||
return [
|
||||
"threads",
|
||||
"viral",
|
||||
"vietnam",
|
||||
"trending",
|
||||
"foryou",
|
||||
"fyp",
|
||||
"threadsvn",
|
||||
]
|
||||
@ -0,0 +1,227 @@
|
||||
"""
|
||||
YouTube Uploader - Upload video lên YouTube sử dụng YouTube Data API v3.
|
||||
|
||||
Yêu cầu:
|
||||
- Google API credentials (OAuth2)
|
||||
- YouTube Data API v3 enabled
|
||||
- Scopes: https://www.googleapis.com/auth/youtube.upload
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
|
||||
from uploaders.base_uploader import BaseUploader, VideoMetadata
|
||||
from utils import settings
|
||||
from utils.console import print_substep
|
||||
|
||||
|
||||
class YouTubeUploader(BaseUploader):
|
||||
"""Upload video lên YouTube."""
|
||||
|
||||
platform_name = "YouTube"
|
||||
|
||||
# YouTube API endpoints
|
||||
UPLOAD_URL = "https://www.googleapis.com/upload/youtube/v3/videos"
|
||||
VIDEOS_URL = "https://www.googleapis.com/youtube/v3/videos"
|
||||
TOKEN_URL = "https://oauth2.googleapis.com/token"
|
||||
|
||||
# Limits
|
||||
MAX_TITLE_LENGTH = 100
|
||||
MAX_DESCRIPTION_LENGTH = 5000
|
||||
MAX_TAGS = 500 # Total characters for all tags
|
||||
MAX_FILE_SIZE = 256 * 1024 * 1024 * 1024 # 256 GB
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.config = settings.config.get("uploaders", {}).get("youtube", {})
|
||||
self.access_token = None
|
||||
|
||||
def authenticate(self) -> bool:
|
||||
"""Xác thực với YouTube API sử dụng refresh token.
|
||||
|
||||
Cấu hình cần có:
|
||||
- client_id
|
||||
- client_secret
|
||||
- refresh_token (lấy từ OAuth2 flow)
|
||||
|
||||
Returns:
|
||||
True nếu xác thực thành công.
|
||||
"""
|
||||
client_id = self.config.get("client_id", "")
|
||||
client_secret = self.config.get("client_secret", "")
|
||||
refresh_token = self.config.get("refresh_token", "")
|
||||
|
||||
if not all([client_id, client_secret, refresh_token]):
|
||||
print_substep(
|
||||
"YouTube: Thiếu credentials (client_id, client_secret, refresh_token)",
|
||||
style="bold red",
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.TOKEN_URL,
|
||||
data={
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"refresh_token": refresh_token,
|
||||
"grant_type": "refresh_token",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
token_data = response.json()
|
||||
self.access_token = token_data["access_token"]
|
||||
self._authenticated = True
|
||||
print_substep("YouTube: Xác thực thành công! ✅", style="bold green")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print_substep(f"YouTube: Lỗi xác thực - {e}", style="bold red")
|
||||
return False
|
||||
|
||||
def upload(self, metadata: VideoMetadata) -> Optional[str]:
|
||||
"""Upload video lên YouTube.
|
||||
|
||||
Args:
|
||||
metadata: VideoMetadata chứa thông tin video.
|
||||
|
||||
Returns:
|
||||
URL video trên YouTube, hoặc None nếu thất bại.
|
||||
"""
|
||||
if not self.access_token:
|
||||
return None
|
||||
|
||||
title = metadata.title[: self.MAX_TITLE_LENGTH]
|
||||
description = self._build_description(metadata)
|
||||
tags = metadata.tags or []
|
||||
|
||||
# Thêm hashtags vào description
|
||||
if metadata.hashtags:
|
||||
hashtag_str = " ".join(f"#{tag}" for tag in metadata.hashtags)
|
||||
description = f"{description}\n\n{hashtag_str}"
|
||||
|
||||
# Video metadata
|
||||
video_metadata = {
|
||||
"snippet": {
|
||||
"title": title,
|
||||
"description": description[: self.MAX_DESCRIPTION_LENGTH],
|
||||
"tags": tags,
|
||||
"categoryId": self._get_category_id(metadata.category),
|
||||
"defaultLanguage": metadata.language,
|
||||
"defaultAudioLanguage": metadata.language,
|
||||
},
|
||||
"status": {
|
||||
"privacyStatus": metadata.privacy,
|
||||
"selfDeclaredMadeForKids": False,
|
||||
},
|
||||
}
|
||||
|
||||
# Schedule publish time
|
||||
if metadata.schedule_time and metadata.privacy != "public":
|
||||
video_metadata["status"]["publishAt"] = metadata.schedule_time
|
||||
video_metadata["status"]["privacyStatus"] = "private"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.access_token}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
# Step 1: Initiate resumable upload
|
||||
params = {
|
||||
"uploadType": "resumable",
|
||||
"part": "snippet,status",
|
||||
}
|
||||
|
||||
init_response = requests.post(
|
||||
self.UPLOAD_URL,
|
||||
headers=headers,
|
||||
params=params,
|
||||
json=video_metadata,
|
||||
timeout=30,
|
||||
)
|
||||
init_response.raise_for_status()
|
||||
|
||||
upload_url = init_response.headers.get("Location")
|
||||
if not upload_url:
|
||||
print_substep("YouTube: Không thể khởi tạo upload session", style="bold red")
|
||||
return None
|
||||
|
||||
# Step 2: Upload video file
|
||||
file_size = os.path.getsize(metadata.file_path)
|
||||
# Dynamic timeout: minimum 120s, add 60s per 100MB
|
||||
upload_timeout = max(120, 60 * (file_size // (100 * 1024 * 1024) + 1))
|
||||
with open(metadata.file_path, "rb") as video_file:
|
||||
upload_response = requests.put(
|
||||
upload_url,
|
||||
headers={
|
||||
"Content-Type": "video/mp4",
|
||||
"Content-Length": str(file_size),
|
||||
},
|
||||
data=video_file,
|
||||
timeout=upload_timeout,
|
||||
)
|
||||
upload_response.raise_for_status()
|
||||
|
||||
video_data = upload_response.json()
|
||||
video_id = video_data.get("id", "")
|
||||
|
||||
if not video_id:
|
||||
print_substep(
|
||||
"YouTube: Upload thành công nhưng không lấy được video ID", style="bold yellow"
|
||||
)
|
||||
return None
|
||||
|
||||
# Step 3: Upload thumbnail if available
|
||||
if metadata.thumbnail_path and os.path.exists(metadata.thumbnail_path):
|
||||
self._upload_thumbnail(video_id, metadata.thumbnail_path)
|
||||
|
||||
video_url = f"https://www.youtube.com/watch?v={video_id}"
|
||||
return video_url
|
||||
|
||||
def _upload_thumbnail(self, video_id: str, thumbnail_path: str):
|
||||
"""Upload thumbnail cho video."""
|
||||
try:
|
||||
url = f"https://www.googleapis.com/upload/youtube/v3/thumbnails/set"
|
||||
with open(thumbnail_path, "rb") as thumb_file:
|
||||
response = requests.post(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {self.access_token}"},
|
||||
params={"videoId": video_id},
|
||||
files={"media": thumb_file},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
print_substep("YouTube: Đã upload thumbnail ✅", style="bold green")
|
||||
except Exception as e:
|
||||
print_substep(f"YouTube: Lỗi upload thumbnail - {e}", style="bold yellow")
|
||||
|
||||
def _build_description(self, metadata: VideoMetadata) -> str:
|
||||
"""Tạo description cho video YouTube."""
|
||||
parts = []
|
||||
if metadata.description:
|
||||
parts.append(metadata.description)
|
||||
parts.append("")
|
||||
parts.append("🎬 Video được tạo tự động bởi Threads Video Maker Bot")
|
||||
parts.append(f"🌐 Ngôn ngữ: Tiếng Việt")
|
||||
return "\n".join(parts)
|
||||
|
||||
@staticmethod
|
||||
def _get_category_id(category: str) -> str:
|
||||
"""Map category name to YouTube category ID."""
|
||||
categories = {
|
||||
"Entertainment": "24",
|
||||
"People & Blogs": "22",
|
||||
"Comedy": "23",
|
||||
"Education": "27",
|
||||
"Science & Technology": "28",
|
||||
"News & Politics": "25",
|
||||
"Gaming": "20",
|
||||
"Music": "10",
|
||||
}
|
||||
return categories.get(category, "24")
|
||||
@ -0,0 +1,108 @@
|
||||
"""
|
||||
Title History - Lưu và kiểm tra các title đã được sử dụng để tránh trùng lặp.
|
||||
|
||||
Lưu trữ danh sách title đã tạo video vào file JSON.
|
||||
Khi chọn thread mới, kiểm tra xem title đã được sử dụng chưa.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from utils.console import print_substep
|
||||
|
||||
TITLE_HISTORY_PATH = "./video_creation/data/title_history.json"
|
||||
|
||||
|
||||
def _ensure_file_exists() -> None:
|
||||
"""Tạo file title_history.json nếu chưa tồn tại."""
|
||||
os.makedirs(os.path.dirname(TITLE_HISTORY_PATH), exist_ok=True)
|
||||
if not os.path.exists(TITLE_HISTORY_PATH):
|
||||
with open(TITLE_HISTORY_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump([], f)
|
||||
|
||||
|
||||
def load_title_history() -> list:
|
||||
"""Đọc danh sách title đã sử dụng.
|
||||
|
||||
Returns:
|
||||
Danh sách các dict chứa thông tin title đã dùng.
|
||||
"""
|
||||
_ensure_file_exists()
|
||||
try:
|
||||
with open(TITLE_HISTORY_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return []
|
||||
|
||||
|
||||
def is_title_used(title: str) -> bool:
|
||||
"""Kiểm tra xem title đã được sử dụng chưa.
|
||||
|
||||
So sánh bằng cách chuẩn hóa (lowercase, strip) để tránh trùng lặp
|
||||
do khác biệt chữ hoa/thường hoặc khoảng trắng.
|
||||
|
||||
Args:
|
||||
title: Title cần kiểm tra.
|
||||
|
||||
Returns:
|
||||
True nếu title đã được sử dụng, False nếu chưa.
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
return False
|
||||
|
||||
history = load_title_history()
|
||||
normalized_title = title.strip().lower()
|
||||
|
||||
for entry in history:
|
||||
saved_title = entry.get("title", "").strip().lower()
|
||||
if saved_title == normalized_title:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def save_title(title: str, thread_id: str = "", source: str = "threads") -> None:
|
||||
"""Lưu title đã sử dụng vào lịch sử.
|
||||
|
||||
Args:
|
||||
title: Title của video đã tạo.
|
||||
thread_id: ID của thread (để tham chiếu).
|
||||
source: Nguồn nội dung (threads/reddit).
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
return
|
||||
|
||||
_ensure_file_exists()
|
||||
|
||||
history = load_title_history()
|
||||
|
||||
# Kiểm tra trùng trước khi lưu
|
||||
normalized_title = title.strip().lower()
|
||||
for entry in history:
|
||||
if entry.get("title", "").strip().lower() == normalized_title:
|
||||
print_substep(f"Title đã tồn tại trong lịch sử, bỏ qua: {title[:50]}...", style="dim")
|
||||
return
|
||||
|
||||
entry = {
|
||||
"title": title.strip(),
|
||||
"thread_id": thread_id,
|
||||
"source": source,
|
||||
"created_at": int(time.time()),
|
||||
}
|
||||
history.append(entry)
|
||||
|
||||
with open(TITLE_HISTORY_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(history, f, ensure_ascii=False, indent=4)
|
||||
|
||||
print_substep(f"Đã lưu title vào lịch sử: {title[:50]}...", style="bold green")
|
||||
|
||||
|
||||
def get_title_count() -> int:
|
||||
"""Đếm số title đã sử dụng.
|
||||
|
||||
Returns:
|
||||
Số lượng title trong lịch sử.
|
||||
"""
|
||||
return len(load_title_history())
|
||||
@ -0,0 +1,343 @@
|
||||
"""
|
||||
Threads Screenshot Generator - Tạo hình ảnh giả lập giao diện Threads.
|
||||
|
||||
Sử dụng Pillow để render hình ảnh thay vì chụp screenshot từ trình duyệt,
|
||||
vì Threads không có giao diện web tĩnh dễ chụp như Reddit.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
from typing import Dict, Final, List, Optional, Tuple
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from rich.progress import track
|
||||
|
||||
from utils import settings
|
||||
from utils.console import print_step, print_substep
|
||||
|
||||
# Threads color themes
|
||||
THEMES = {
|
||||
"dark": {
|
||||
"bg_color": (0, 0, 0),
|
||||
"card_bg": (30, 30, 30),
|
||||
"text_color": (255, 255, 255),
|
||||
"secondary_text": (140, 140, 140),
|
||||
"border_color": (50, 50, 50),
|
||||
"accent_color": (0, 149, 246), # Threads blue
|
||||
"reply_line": (60, 60, 60),
|
||||
},
|
||||
"light": {
|
||||
"bg_color": (255, 255, 255),
|
||||
"card_bg": (255, 255, 255),
|
||||
"text_color": (0, 0, 0),
|
||||
"secondary_text": (130, 130, 130),
|
||||
"border_color": (219, 219, 219),
|
||||
"accent_color": (0, 149, 246),
|
||||
"reply_line": (200, 200, 200),
|
||||
},
|
||||
}
|
||||
|
||||
# Avatar color palette for comments
|
||||
AVATAR_COLORS = [
|
||||
(88, 101, 242), # Blue
|
||||
(237, 66, 69), # Red
|
||||
(87, 242, 135), # Green
|
||||
(254, 231, 92), # Yellow
|
||||
(235, 69, 158), # Pink
|
||||
]
|
||||
|
||||
|
||||
def _get_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
|
||||
"""Load font hỗ trợ tiếng Việt."""
|
||||
font_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fonts")
|
||||
if bold:
|
||||
font_path = os.path.join(font_dir, "Roboto-Bold.ttf")
|
||||
else:
|
||||
font_path = os.path.join(font_dir, "Roboto-Medium.ttf")
|
||||
|
||||
try:
|
||||
return ImageFont.truetype(font_path, size)
|
||||
except (OSError, IOError):
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> List[str]:
|
||||
"""Wrap text to fit within max_width pixels."""
|
||||
words = text.split()
|
||||
lines = []
|
||||
current_line = ""
|
||||
|
||||
for word in words:
|
||||
test_line = f"{current_line} {word}".strip()
|
||||
bbox = font.getbbox(test_line)
|
||||
if bbox[2] <= max_width:
|
||||
current_line = test_line
|
||||
else:
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = word
|
||||
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
|
||||
return lines if lines else [""]
|
||||
|
||||
|
||||
def _draw_avatar(draw: ImageDraw.Draw, x: int, y: int, size: int, color: Tuple[int, ...]):
|
||||
"""Vẽ avatar tròn placeholder."""
|
||||
draw.ellipse([x, y, x + size, y + size], fill=color)
|
||||
# Vẽ chữ cái đầu trong avatar
|
||||
font = _get_font(size // 2, bold=True)
|
||||
draw.text(
|
||||
(x + size // 4, y + size // 6),
|
||||
"T",
|
||||
fill=(255, 255, 255),
|
||||
font=font,
|
||||
)
|
||||
|
||||
|
||||
def create_thread_post_image(
|
||||
thread_obj: dict,
|
||||
theme_name: str = "dark",
|
||||
width: int = 1080,
|
||||
) -> Image.Image:
|
||||
"""Tạo hình ảnh cho bài viết Threads chính (title/post).
|
||||
|
||||
Args:
|
||||
thread_obj: Thread object chứa thông tin bài viết.
|
||||
theme_name: Theme name ("dark" hoặc "light").
|
||||
width: Chiều rộng hình ảnh.
|
||||
|
||||
Returns:
|
||||
PIL Image object.
|
||||
"""
|
||||
theme = THEMES.get(theme_name, THEMES["dark"])
|
||||
|
||||
padding = 40
|
||||
content_width = width - (padding * 2)
|
||||
avatar_size = 60
|
||||
|
||||
# Fonts
|
||||
username_font = _get_font(28, bold=True)
|
||||
body_font = _get_font(32)
|
||||
meta_font = _get_font(22)
|
||||
|
||||
author = thread_obj.get("thread_author", "@user")
|
||||
text = thread_obj.get("thread_title", thread_obj.get("thread_post", ""))
|
||||
|
||||
# Tính chiều cao
|
||||
text_lines = _wrap_text(text, body_font, content_width - avatar_size - 30)
|
||||
line_height = 42
|
||||
text_height = len(text_lines) * line_height
|
||||
|
||||
total_height = padding + avatar_size + 20 + text_height + 60 + padding
|
||||
|
||||
# Tạo image
|
||||
img = Image.new("RGBA", (width, total_height), theme["bg_color"])
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
y_cursor = padding
|
||||
|
||||
# Avatar
|
||||
_draw_avatar(draw, padding, y_cursor, avatar_size, theme["accent_color"])
|
||||
|
||||
# Username
|
||||
draw.text(
|
||||
(padding + avatar_size + 15, y_cursor + 5),
|
||||
author,
|
||||
fill=theme["text_color"],
|
||||
font=username_font,
|
||||
)
|
||||
|
||||
# Timestamp
|
||||
draw.text(
|
||||
(padding + avatar_size + 15, y_cursor + 35),
|
||||
"🧵 Threads",
|
||||
fill=theme["secondary_text"],
|
||||
font=meta_font,
|
||||
)
|
||||
|
||||
y_cursor += avatar_size + 20
|
||||
|
||||
# Thread line (vertical line from avatar to content)
|
||||
line_x = padding + avatar_size // 2
|
||||
draw.line(
|
||||
[(line_x, padding + avatar_size + 5), (line_x, y_cursor - 5)],
|
||||
fill=theme["reply_line"],
|
||||
width=3,
|
||||
)
|
||||
|
||||
# Body text
|
||||
for line in text_lines:
|
||||
draw.text(
|
||||
(padding + 10, y_cursor),
|
||||
line,
|
||||
fill=theme["text_color"],
|
||||
font=body_font,
|
||||
)
|
||||
y_cursor += line_height
|
||||
|
||||
# Interaction bar
|
||||
y_cursor += 20
|
||||
icons = "❤️ 💬 🔄 ✈️"
|
||||
draw.text(
|
||||
(padding + 10, y_cursor),
|
||||
icons,
|
||||
fill=theme["secondary_text"],
|
||||
font=meta_font,
|
||||
)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def create_comment_image(
|
||||
comment: dict,
|
||||
index: int,
|
||||
theme_name: str = "dark",
|
||||
width: int = 1080,
|
||||
) -> Image.Image:
|
||||
"""Tạo hình ảnh cho một reply/comment trên Threads.
|
||||
|
||||
Args:
|
||||
comment: Comment dict.
|
||||
index: Số thứ tự comment.
|
||||
theme_name: Theme name.
|
||||
width: Chiều rộng hình ảnh.
|
||||
|
||||
Returns:
|
||||
PIL Image object.
|
||||
"""
|
||||
theme = THEMES.get(theme_name, THEMES["dark"])
|
||||
|
||||
padding = 40
|
||||
content_width = width - (padding * 2)
|
||||
avatar_size = 50
|
||||
|
||||
# Fonts
|
||||
username_font = _get_font(24, bold=True)
|
||||
body_font = _get_font(30)
|
||||
meta_font = _get_font(20)
|
||||
|
||||
author = comment.get("comment_author", f"@user{index}")
|
||||
text = comment.get("comment_body", "")
|
||||
|
||||
# Tính chiều cao
|
||||
text_lines = _wrap_text(text, body_font, content_width - avatar_size - 30)
|
||||
line_height = 40
|
||||
text_height = len(text_lines) * line_height
|
||||
|
||||
total_height = padding + avatar_size + 15 + text_height + 40 + padding
|
||||
|
||||
# Tạo image
|
||||
img = Image.new("RGBA", (width, total_height), theme["bg_color"])
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
y_cursor = padding
|
||||
|
||||
# Reply line at top
|
||||
draw.line(
|
||||
[(padding, 0), (padding, y_cursor)],
|
||||
fill=theme["reply_line"],
|
||||
width=2,
|
||||
)
|
||||
|
||||
# Avatar (smaller for comments)
|
||||
avatar_color = AVATAR_COLORS[index % len(AVATAR_COLORS)]
|
||||
_draw_avatar(draw, padding, y_cursor, avatar_size, avatar_color)
|
||||
|
||||
# Username
|
||||
draw.text(
|
||||
(padding + avatar_size + 12, y_cursor + 5),
|
||||
author,
|
||||
fill=theme["text_color"],
|
||||
font=username_font,
|
||||
)
|
||||
|
||||
# Time indicator
|
||||
draw.text(
|
||||
(padding + avatar_size + 12, y_cursor + 30),
|
||||
"Trả lời",
|
||||
fill=theme["secondary_text"],
|
||||
font=meta_font,
|
||||
)
|
||||
|
||||
y_cursor += avatar_size + 15
|
||||
|
||||
# Body text
|
||||
for line in text_lines:
|
||||
draw.text(
|
||||
(padding + 10, y_cursor),
|
||||
line,
|
||||
fill=theme["text_color"],
|
||||
font=body_font,
|
||||
)
|
||||
y_cursor += line_height
|
||||
|
||||
# Bottom separator
|
||||
y_cursor += 10
|
||||
draw.line(
|
||||
[(padding, y_cursor), (width - padding, y_cursor)],
|
||||
fill=theme["border_color"],
|
||||
width=1,
|
||||
)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def get_screenshots_of_threads_posts(thread_object: dict, screenshot_num: int):
|
||||
"""Tạo screenshots cho bài viết Threads.
|
||||
|
||||
Thay thế get_screenshots_of_reddit_posts() cho Threads.
|
||||
|
||||
Args:
|
||||
thread_object: Thread object từ threads_client.py.
|
||||
screenshot_num: Số lượng screenshots cần tạo.
|
||||
"""
|
||||
W: Final[int] = int(settings.config["settings"]["resolution_w"])
|
||||
H: Final[int] = int(settings.config["settings"]["resolution_h"])
|
||||
theme: str = settings.config["settings"].get("theme", "dark")
|
||||
storymode: bool = settings.config["settings"].get("storymode", False)
|
||||
|
||||
print_step("Đang tạo hình ảnh cho bài viết Threads...")
|
||||
|
||||
thread_id = re.sub(r"[^\w\s-]", "", thread_object["thread_id"])
|
||||
Path(f"assets/temp/{thread_id}/png").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Tạo hình ảnh cho bài viết chính (title)
|
||||
title_img = create_thread_post_image(
|
||||
thread_object,
|
||||
theme_name=theme if theme in THEMES else "dark",
|
||||
width=W,
|
||||
)
|
||||
title_img.save(f"assets/temp/{thread_id}/png/title.png")
|
||||
print_substep("Đã tạo hình ảnh tiêu đề", style="bold green")
|
||||
|
||||
if storymode:
|
||||
# Story mode - chỉ cần 1 hình cho toàn bộ nội dung
|
||||
story_img = create_thread_post_image(
|
||||
{
|
||||
"thread_author": thread_object.get("thread_author", "@user"),
|
||||
"thread_title": thread_object.get("thread_post", ""),
|
||||
},
|
||||
theme_name=theme if theme in THEMES else "dark",
|
||||
width=W,
|
||||
)
|
||||
story_img.save(f"assets/temp/{thread_id}/png/story_content.png")
|
||||
else:
|
||||
# Comment mode - tạo hình cho từng reply
|
||||
comments = thread_object.get("comments", [])[:screenshot_num]
|
||||
for idx, comment in enumerate(track(comments, "Đang tạo hình ảnh replies...")):
|
||||
if idx >= screenshot_num:
|
||||
break
|
||||
|
||||
comment_img = create_comment_image(
|
||||
comment,
|
||||
index=idx,
|
||||
theme_name=theme if theme in THEMES else "dark",
|
||||
width=W,
|
||||
)
|
||||
comment_img.save(f"assets/temp/{thread_id}/png/comment_{idx}.png")
|
||||
|
||||
print_substep("Đã tạo tất cả hình ảnh thành công! ✅", style="bold green")
|
||||
Loading…
Reference in new issue