Download audio_handler_fastapi.py from vppmp/vptruyen: direct link, hf CLI and curl.
- Browser
- Download file 139 kB
-
https://huggingface.co/spaces/vppmp/vptruyen/resolve/main/audio_handler_fastapi.py
- Command line
-
hf download hf://spaces/vppmp/vptruyen/audio_handler_fastapi.py
-
curl -L -o audio_handler_fastapi.py https://huggingface.co/spaces/vppmp/vptruyen/resolve/main/audio_handler_fastapi.py
139 kB
import nest_asyncio
nest_asyncio.apply()
import asyncio
import base64
import os
import re
import shutil
import subprocess
import pickle
import random
import traceback
import time
import tempfile
import json
import io
from collections import deque
import httpx
import socket
import aiodns
import edge_tts
from gradio_client import Client # Import cho TTS HuggingFace (giọng Ngọc Huyền)
import pandas as pd
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook
# --- CÁC THƯ VIỆN FRAMEWORK ---
from fastapi import FastAPI, Request, BackgroundTasks
from contextlib import asynccontextmanager
from scrapers import get_scraper # <<< DÒNG MỚI
# --- CÁC THƯ VIỆN GOOGLE API ---
from google.auth.transport.requests import Request as GoogleAuthRequest
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.oauth2.credentials import Credentials
# --- BỘ ĐỆM CHỐNG LẶP REQUEST TỪ TELEGRAM ---
processed_update_ids = deque(maxlen=500)
# --- DICTIONARY LƯU TRẠNG THÁI NGƯỜI DÙNG ---
user_sessions = {}
from trace_handler import process_content_for_trace # <<< DÒNG MỚI: Import hàm logic từ file mới
# ==============================================================================
# --- PHẦN CẤU HÌNH CẦN THAY ĐỔI CHO MÔI TRƯỜNG HUGGING FACE ---
# ==============================================================================
# --- ĐƯỜNG DẪN TRÊN HỆ THỐNG TỆP TẠM THỜI CỦA HUGGING FACE ---
# Chúng ta sẽ sử dụng thư mục /tmp/ để lưu trữ file tạm thời.
BASE_DATA_DIR = "/tmp/audio_bot_data"
WORKING_EXCEL_PATH = os.path.join(BASE_DATA_DIR, "Input.xlsx")
AUDIO_TXT_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Input/")
AUDIO_MP3_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Sound/")
AUDIO_FINAL_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Final/")
AUDIO_VIDEO_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Video/")
YTB_TOKEN_SAVE_PATH = os.path.join(BASE_DATA_DIR, "YTB/Account/") # Thư mục chứa token sau khi tải từ Drive
TEMP_PATH = os.path.join(BASE_DATA_DIR, "Temp/")
# --- ID CỦA CÁC FILE VÀ THƯ MỤC TRÊN GOOGLE DRIVE ---
# ID file Excel chính
DRIVE_EXCEL_FILE_ID = "16a00UFwedILbo_ujvProGmgRlJZw6qDp"
# !!! QUAN TRỌNG: Bạn cần tạo các thư mục sau trên Google Drive và dán ID của chúng vào đây
DRIVE_YTB_ACCOUNT_FOLDER_ID = "1_Drudczqoaq03L5dbkVJoA1FWgJ6R2MO" # Thư mục chứa các file token .pickle của YouTube
DRIVE_AUDIO_VIDEO_FOLDER_ID = "1uIbjogmCT-xySHleVPR3senWD7IMUE71" # <-- THAY ID NÀY: Thư mục để lưu video .mp4 cuối cùng
# --- THÊM CÁC ID MỚI CHO CÁC THƯ MỤC TRUNG GIAN ---
DRIVE_AUDIO_TXT_FOLDER_ID = "1Sg9_1XcABwTtIflqBPpGjsk5Epkz-QFe" # <-- THAY ID NÀY
DRIVE_AUDIO_MP3_FOLDER_ID = "1_eE1ZRjKPZChzlDjcUKsg0s5Rnkt6B4Y" # <-- THAY ID NÀY
DRIVE_AUDIO_FINAL_FOLDER_ID = "16L1UKQuWRGdpq5sIZ5q0rea7Q5_GidPF" # <-- THAY ID NÀY
# --- LẤY BIẾN MÔI TRƯỜNG TỪ HUGGING FACE SECRETS ---
GOOGLE_APP_SCRIPT_URL = os.getenv("GOOGLE_APP_SCRIPT_URL") # URL của Google Apps Script Web App
GOOGLE_APP_SCRIPT_KEY = os.getenv("GOOGLE_APP_SCRIPT_KEY") # Khóa dùng chung với Google Apps Script
# Biến toàn cục cho Google TTS API Key, sẽ được đọc từ Excel khi khởi động
GOOGLE_TTS_API_KEY = ""
# ==============================================================================
# --- ĐỊNH NGHĨA CÁC TRẠNG THÁI & KEYBOARD (ĐÃ CHUYỂN SANG ĐỊNH DẠNG JSON) ---
# ==============================================================================
# Logic trạng thái được giữ nguyên
AUDIO_MENU_STATE = 100
AWAITING_EPISODE_COUNT_STATE = 101
AWAITING_URL_FOR_SCRAPING_STATE = 102
AWAITING_ADD_MORE_URL_CONFIRMATION_STATE = 103
AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE = 104
AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE = 105
AWAITING_PAGE_COUNT_STATE = 106
AWAITING_ONE_CLICK_YT_CONFIRM_STATE = 107
AWAITING_ONE_CLICK_YT_ACCOUNT_STATE = 108
# <<< MỚI: Thêm các trạng thái chọn giọng đọc
AWAITING_GEN_MP3_VOICE_CHOICE_STATE = 109
AWAITING_ONE_CLICK_VOICE_CHOICE_STATE = 110
AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE = 111
# <<< BLOCK CODE MỚI BẮT ĐẦU: Thêm các trạng thái cho chức năng Truy Vết
AWAITING_TRACE_PAGE_COUNT_STATE = 201
AWAITING_TRACE_URL_STATE = 202
# <<< BLOCK CODE MỚI KẾT THÚC
# Bàn phím được chuyển thành JSON để gửi qua Google Apps Script
AUDIO_MENU_KEYBOARD = { "inline_keyboard": [
[{"text": "1. Get Link", "callback_data": "audio_get_link"}, {"text": "2. Get File", "callback_data": "audio_get_file"}],
[{"text": "3. Gen MP3", "callback_data": "audio_gen_mp3"}, {"text": "4. Gen MP4", "callback_data": "audio_gen_mp4"}],
[{"text": "5. Merge File", "callback_data": "audio_merge_file"}, {"text": "6. One Click", "callback_data": "audio_one_click"}],
[{"text": "🔎 Truy Vết", "callback_data": "audio_trace"}], # <<< DÒNG MỚI
[{"text": "🚀 Upload Youtube (Recover)", "callback_data": "audio_recovery_upload"}], # <<< DÒNG MỚI
[{"text": "⬅️ Quay lại Menu chính", "callback_data": "back_to_main_menu"}],
]}
RECOVERY_YT_ACCOUNT_KEYBOARD = { "inline_keyboard": [
[{"text": f"{i}", "callback_data": f"recovery_yt_acc_{i}"} for i in range(1, 6)],
[{"text": f"{i}", "callback_data": f"recovery_yt_acc_{i}"} for i in range(6, 11)],
]}
VOICE_CHOICE_KEYBOARD_GEN_MP3 = { "inline_keyboard": [
[{"text": "👨 Giọng Nam (Edge TTS)", "callback_data": "gen_mp3_voice_male"},
{"text": "👩 Giọng Nữ (Google TTS)", "callback_data": "gen_mp3_voice_female"}],
[{"text": "🌸 Ngọc Huyền (HuggingFace)", "callback_data": "gen_mp3_voice_ngochuyen"}]
]}
VOICE_CHOICE_KEYBOARD_ONE_CLICK = { "inline_keyboard": [
[{"text": "👨 Giọng Nam", "callback_data": "one_click_voice_male"},
{"text": "👩 Giọng Nữ", "callback_data": "one_click_voice_female"}],
[{"text": "🌸 Ngọc Huyền", "callback_data": "one_click_voice_ngochuyen"}]
]}
YOUTUBE_UPLOAD_CONFIRM_KEYBOARD = { "inline_keyboard": [[{"text": "✅ Có, upload ngay", "callback_data": "yt_upload_yes"}, {"text": "❌ Không, cảm ơn", "callback_data": "yt_upload_no"}]]}
YOUTUBE_ACCOUNT_KEYBOARD_AUDIO = { "inline_keyboard": [
[{"text": f"{i}", "callback_data": f"yt_account_{i}"} for i in range(1, 6)],
[{"text": f"{i}", "callback_data": f"yt_account_{i}"} for i in range(6, 11)],
]}
EPISODE_COUNT_KEYBOARD = { "inline_keyboard": [
[{"text": "1", "callback_data": "ep_count_1"}, {"text": "2", "callback_data": "ep_count_2"}, {"text": "5", "callback_data": "ep_count_5"}],
[{"text": "10", "callback_data": "ep_count_10"}, {"text": "15", "callback_data": "ep_count_15"}, {"text": "20", "callback_data": "ep_count_20"}],
]}
ADD_MORE_KEYBOARD = {"inline_keyboard": [[{"text": "✅ Có", "callback_data": "add_more_yes"}, {"text": "❌ Không", "callback_data": "add_more_no"}]]}
PAGE_COUNT_KEYBOARD = { "inline_keyboard": [
[{"text": "1 Trang", "callback_data": "page_count_1"}, {"text": "2 Trang", "callback_data": "page_count_2"}, {"text": "4 Trang", "callback_data": "page_count_4"}],
[{"text": "6 Trang", "callback_data": "page_count_6"}, {"text": "10 Trang", "callback_data": "page_count_10"}, {"text": "20 Trang", "callback_data": "page_count_20"}],
]}
ONE_CLICK_YT_CONFIRM_KEYBOARD = { "inline_keyboard": [[{"text": "✅ Có, tự động upload", "callback_data": "one_click_yt_yes"}, {"text": "❌ Không, chỉ tạo video", "callback_data": "one_click_yt_no"}]]}
ONE_CLICK_YT_ACCOUNT_KEYBOARD = { "inline_keyboard": [
[{"text": f"{i}", "callback_data": f"one_click_account_{i}"} for i in range(71, 76)],
[{"text": f"{i}", "callback_data": f"one_click_account_{i}"} for i in range(76, 81)],
]}
# <<< BLOCK CODE MỚI BẮT ĐẦU: Bàn phím chọn số trang cho chức năng Truy Vết
TRACE_PAGE_COUNT_KEYBOARD = { "inline_keyboard": [
[{"text": "1 Trang", "callback_data": "trace_page_count_1"}, {"text": "2 Trang", "callback_data": "trace_page_count_2"}, {"text": "4 Trang", "callback_data": "trace_page_count_4"}],
[{"text": "6 Trang", "callback_data": "trace_page_count_6"}, {"text": "10 Trang", "callback_data": "trace_page_count_10"}, {"text": "20 Trang", "callback_data": "trace_page_count_20"}],
]}
original_getaddrinfo = socket.getaddrinfo
async def custom_getaddrinfo_async(host, port, family=0, type=0, proto=0, flags=0):
resolver = aiodns.DNSResolver(nameservers=['8.8.8.8', '8.8.4.4'])
try:
result = await resolver.query(host, 'A')
addrlist = []
for record in result:
addrlist.append((socket.AF_INET, socket.SOCK_STREAM, 6, '', (record.host, port)))
return addrlist
except aiodns.error.DNSError:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, original_getaddrinfo, host, port, family, type, proto, flags)
def custom_getaddrinfo_sync(*args, **kwargs):
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop.run_until_complete(custom_getaddrinfo_async(*args, **kwargs))
socket.getaddrinfo = custom_getaddrinfo_sync
# --- KẾT THÚC PHẦN DNS FIX ---
# ==============================================================================
# --- CÁC HÀM GIAO TIẾP VÀ TƯƠNG TÁC VỚI HẠ TẦNG (GOOGLE APPS SCRIPT, DRIVE) ---
# ==============================================================================
async def _append_trace_results_to_excel(results: list[dict]) -> bool:
"""Hàm mới để ghi kết quả truy vết vào các cột R, S của sheet 'Audio'."""
def append_data(book):
if "Audio" not in book.sheetnames:
ws = book.create_sheet("Audio")
else:
ws = book["Audio"]
# --- LOGIC ĐÃ SỬA LỖI ---
# Kiểm tra xem header đã tồn tại ở dòng 1 chưa
header_exists = ws.cell(row=1, column=18).value == "Full Sentence"
if not header_exists:
# Nếu chưa có header, ghi vào dòng 1
ws.cell(row=1, column=18, value="Full Sentence") # Cột R
ws.cell(row=1, column=19, value="Masked Words") # Cột S
# Dữ liệu sẽ bắt đầu từ dòng 2
start_row = 2
else:
# Nếu đã có header, tìm dòng trống tiếp theo
start_row = ws.max_row + 1
# Ghi dữ liệu kết quả vào các dòng tiếp theo
for i, item in enumerate(results):
current_row = start_row + i
ws.cell(row=current_row, column=18, value=item.get("sentence"))
ws.cell(row=current_row, column=19, value=item.get("masked_words"))
print(f"✅ Đã chuẩn bị ghi {len(results)} kết quả truy vết vào Excel.")
return await modify_excel_sheet(append_data)
async def run_trace_workflow(chat_id: int, start_url: str, max_pages: int):
"""
Tác vụ nền cho chức năng 'Truy Vết'.
Hàm này điều phối toàn bộ quy trình: cào link, cào nội dung, xử lý và lưu Excel.
*** PHIÊN BẢN SỬA LỖI: Chỉ ghi vào Excel những dòng còn lỗi SAU KHI thay thế. ***
"""
await send_telegram_message(chat_id, f"🔎 Bắt đầu quy trình Truy Vết cho {max_pages} trang từ URL của bạn...")
# 1. Đọc bản đồ thay thế từ Excel (cột O và P)
replacement_map = await _read_replacement_map_from_excel()
# 2. Lấy danh sách các chương cần quét
chapter_list_result = await scrape_website_chapter_list(start_url, max_pages)
if 'error' in chapter_list_result:
await send_telegram_message(chat_id, f"❌ Lỗi khi lấy danh sách chương: {chapter_list_result['error']}", reply_markup=AUDIO_MENU_KEYBOARD)
return
chapter_links_data = chapter_list_result.get('data', [])
if not chapter_links_data:
await send_telegram_message(chat_id, "Không tìm thấy chương nào từ URL đã cho.", reply_markup=AUDIO_MENU_KEYBOARD)
return
await send_telegram_message(chat_id, f"✅ Tìm thấy {len(chapter_links_data)} chương. Bắt đầu quét nội dung, áp dụng thay thế và lọc kết quả...")
# 3. Quét, thay thế và lọc kết quả
final_results_to_report = []
config = await read_audio_config_from_excel()
for i, chapter_data in enumerate(chapter_links_data):
if (i + 1) % 20 == 0: # Gửi thông báo tiến độ sau mỗi 20 chương
await send_telegram_message(chat_id, f"⏳ Đang xử lý chương {i + 1}/{len(chapter_links_data)}...")
scrape_result = await scrape_website_chapter_content(chapter_data['link'], config["replacements"])
if scrape_result:
_, content, _ = scrape_result
# Lấy kết quả truy vết ban đầu
initial_trace_results = process_content_for_trace(content)
# Chỉ xử lý nếu có lỗi ban đầu
if initial_trace_results:
for result in initial_trace_results:
# Áp dụng thay thế cho câu bị lỗi
cleaned_sentence = _apply_replacements(result['sentence'], replacement_map)
# KIỂM TRA LẠI: Chạy lại truy vết trên câu ĐÃ ĐƯỢC LÀM SẠCH
re_traced_errors = process_content_for_trace(cleaned_sentence)
# CHỈ THÊM VÀO BÁO CÁO NẾU VẪN CÒN LỖI SAU KHI THAY THẾ
if re_traced_errors:
# Lấy từ khóa lỗi còn lại để báo cáo cho chính xác
remaining_keywords = re_traced_errors[0]['masked_words']
final_results_to_report.append({
"sentence": cleaned_sentence,
"masked_words": remaining_keywords
})
# 4. Báo cáo kết quả cuối cùng
if not final_results_to_report:
await send_telegram_message(chat_id, "✅ **TRUY VẾT THÀNH CÔNG** 🎉\nSau khi áp dụng các quy tắc thay thế, không còn tìm thấy nội dung nào cần xử lý.", reply_markup=AUDIO_MENU_KEYBOARD)
return
# Chỉ ghi những kết quả thực sự còn lỗi vào Excel
await send_telegram_message(chat_id, f"⚠️ Tìm thấy {len(final_results_to_report)} câu vẫn còn lỗi sau khi thay thế. Đang ghi vào file Excel để bạn xem lại...")
if await _append_trace_results_to_excel(final_results_to_report):
drive_creds = await get_drive_credentials(chat_id)
if drive_creds:
drive_service = build('drive', 'v3', credentials=drive_creds)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
await send_telegram_message(chat_id, "🎉 **TRUY VẾT HOÀN TẤT** 🎉\nĐã cập nhật các lỗi còn lại vào file Input.xlsx và upload lên Google Drive.", reply_markup=AUDIO_MENU_KEYBOARD)
else:
await send_telegram_message(chat_id, "⚠️ Ghi vào Excel cục bộ thành công, nhưng không thể upload lên Drive (lỗi xác thực).", reply_markup=AUDIO_MENU_KEYBOARD)
else:
await send_telegram_message(chat_id, "❌ Lỗi khi ghi kết quả vào file Excel.", reply_markup=AUDIO_MENU_KEYBOARD)
async def _read_replacement_map_from_excel() -> dict:
"""
Đọc bản đồ thay thế tùy chỉnh từ cột O (tìm) và P (thay thế) của sheet 'Audio'.
*** PHIÊN BẢN SỬA LỖI: Chấp nhận ô P trống để thay thế bằng blank. ***
"""
replacements = {}
try:
df = pd.read_excel(
WORKING_EXCEL_PATH,
sheet_name="Audio",
header=None,
usecols=[14, 15], # Cột O và P
engine="openpyxl"
)
# BƯỚC 1: Chỉ xóa những dòng mà cột O (index 14) bị trống.
# Các dòng có cột P trống nhưng cột O có dữ liệu sẽ được giữ lại.
df.dropna(subset=[14], inplace=True)
# BƯỚC 2: Với những dòng đã được giữ lại, hãy điền vào các ô trống (NaN)
# ở cột P (index 15) bằng một chuỗi rỗng "" (blank).
df[15] = df[15].fillna('')
# Bây giờ, vòng lặp sẽ hoạt động chính xác
for index, row in df.iterrows():
find_str = str(row[14])
replace_str = str(row[15])
# if find_str: # Điều kiện này không còn quá cần thiết nhưng giữ lại cho an toàn
replacements[find_str] = replace_str
print(f"✅ Đã đọc {len(replacements)} quy tắc thay thế từ cột O và P (bao gồm cả thay thế bằng blank).")
except Exception as e:
print(f"⚠️ Lỗi khi đọc bản đồ thay thế từ Excel: {e}")
return replacements
def _apply_replacements(text: str, replacement_map: dict) -> str:
"""
Áp dụng một loạt các thao tác tìm và thay thế cho một chuỗi văn bản.
"""
for find_str, replace_str in replacement_map.items():
text = text.replace(find_str, replace_str)
return text
# <<< BLOCK CODE MỚI KẾT THÚC >>>
async def send_telegram_message(chat_id, text, reply_markup=None, parse_mode=None):
"""Gửi tin nhắn văn bản qua Google Apps Script tới Telegram."""
if not GOOGLE_APP_SCRIPT_URL:
print("❌ LỖI NGHIÊM TRỌNG: GOOGLE_APP_SCRIPT_URL chưa được thiết lập.")
return False
if not GOOGLE_APP_SCRIPT_KEY:
print("❌ LỖI NGHIÊM TRỌNG: GOOGLE_APP_SCRIPT_KEY chưa được thiết lập.")
return False
print(f"--> Đang gửi tin nhắn tới chat_id: {chat_id}")
payload = {
"action": "sendMessage",
"proxy_key": GOOGLE_APP_SCRIPT_KEY,
"chat_id": chat_id,
"text": text,
}
if parse_mode:
payload["parse_mode"] = parse_mode
if reply_markup:
payload["reply_markup"] = json.dumps(reply_markup) # Đảm bảo reply_markup là chuỗi JSON
response = None
try:
# GAS ContentService có thể trả redirect; theo redirect để log được phản hồi cuối.
async with httpx.AsyncClient(follow_redirects=True) as client:
response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
response.raise_for_status()
try:
result = response.json()
except ValueError as json_error:
final_url = f"{response.url.scheme}://{response.url.host}{response.url.path}"
content_type = response.headers.get("content-type", "unknown")
raise RuntimeError(
f"GAS không trả JSON (Content-Type={content_type}, URL cuối={final_url})"
) from json_error
if not isinstance(result, dict) or not (
result.get("ok") is True or result.get("success") is True
):
if isinstance(result, dict):
details = result.get("description") or result.get("error") or result
else:
details = response.text[:500]
raise RuntimeError(f"Google Apps Script/Telegram trả lỗi: {details}")
print(f"--> GAS xác nhận gửi thành công tới chat_id {chat_id}")
return True
except Exception as e:
status = f", HTTP {response.status_code}" if response is not None else ""
body = f", body={response.text[:500]!r}" if response is not None else ""
print(f"❌ Lỗi khi gọi Google Apps Script gửi tin nhắn ({type(e).__name__}{status}): {e!r}{body}")
return False
async def scrape_website_chapter_list(url: str, max_pages: int) -> dict:
"""
Hàm chung để cào danh sách chương. Tự động chọn scraper phù hợp.
"""
scraper = get_scraper(url)
if not scraper:
return {"error": "URL không được hỗ trợ", "details": f"Không tìm thấy scraper cho trang: {url}"}
# Tất cả các scraper bây giờ đều là hàm đồng bộ (blocking)
return await asyncio.to_thread(scraper.scrape_chapter_list, url, max_pages)
async def scrape_website_chapter_content(url: str, replacements: list[str]) -> tuple[str, str, str] | None:
"""
Hàm chung để cào nội dung chương. Tự động chọn scraper phù hợp.
"""
scraper = get_scraper(url)
if not scraper:
print(f"URL không được hỗ trợ: {url}")
return None
# Tất cả các scraper bây giờ đều là hàm đồng bộ (blocking)
return await asyncio.to_thread(scraper.scrape_chapter_content, url, replacements)
async def get_drive_credentials(chat_id: int) -> Credentials | None:
"""Xác thực và trả về credentials cho Google Drive."""
# Trong môi trường HF, token được đọc từ secret và ghi vào file tạm
working_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, "driver_main.pickle")
if not os.path.exists(working_token_path):
await send_telegram_message(chat_id, "❌ Lỗi: Không tìm thấy file token chính của Drive.")
return None
with open(working_token_path, 'rb') as token:
credentials = pickle.load(token)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
try:
credentials.refresh(GoogleAuthRequest())
with open(working_token_path, 'wb') as token:
pickle.dump(credentials, token)
print("✅ Token Drive chính đã được làm mới.")
except Exception as e:
await send_telegram_message(chat_id, f"⚠️ Lỗi khi làm mới token Drive: {e}")
return None
else:
return None
return credentials
async def download_file_from_drive(drive_service, file_id: str, save_path: str):
"""Tải một file từ Google Drive về đường dẫn cục bộ."""
try:
print(f"[*] Đang tải file Drive ID '{file_id}' về '{save_path}'...")
os.makedirs(os.path.dirname(save_path), exist_ok=True)
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while not done:
status, done = await asyncio.to_thread(downloader.next_chunk)
if status:
print(f" -> Đã tải {int(status.progress() * 100)}%.")
with open(save_path, 'wb') as f:
f.write(fh.getvalue())
print(f"✅ Tải file thành công.")
return True
except Exception as e:
print(f"❌ Lỗi khi tải file từ Drive: {e}")
return False
async def upload_file_to_drive(drive_service, local_path: str, file_id_to_update: str):
"""Cập nhật một file đã có trên Drive bằng file cục bộ."""
try:
print(f"[*] Đang upload file '{local_path}' để cập nhật Drive ID '{file_id_to_update}'...")
media = MediaFileUpload(local_path)
await asyncio.to_thread(
drive_service.files().update(fileId=file_id_to_update, media_body=media).execute
)
print(f"✅ Upload file Excel thành công.")
return True
except Exception as e:
print(f"❌ Lỗi khi upload file Excel lên Drive: {e}")
return False
async def upload_video_to_drive_audio(drive_service, local_video_path: str, chat_id: int):
"""
(CHỨC NĂNG MỚI) Upload video đã tạo lên thư mục Video trên Drive.
"""
try:
if "DRIVE_FOLDER_ID_FOR_FINAL_VIDEOS" in DRIVE_AUDIO_VIDEO_FOLDER_ID:
await send_telegram_message(chat_id, "⚠️ CẢNH BÁO: DRIVE_AUDIO_VIDEO_FOLDER_ID chưa được cấu hình. Bỏ qua upload video lên Drive.")
return None
file_metadata = {
'name': os.path.basename(local_video_path),
'parents': [DRIVE_AUDIO_VIDEO_FOLDER_ID]
}
media = MediaFileUpload(local_video_path, mimetype='video/mp4', resumable=True)
print(f"[*] Bắt đầu upload video '{os.path.basename(local_video_path)}' lên Google Drive...")
request = drive_service.files().create(body=file_metadata, media_body=media, fields='id')
response = None
while response is None:
status, response = await asyncio.to_thread(request.next_chunk)
if status:
progress = int(status.progress() * 100)
# Chỉ gửi thông báo tiến độ cho các mốc quan trọng để tránh spam
if progress % 25 == 0 and progress > 0:
await send_telegram_message(chat_id, f"⏳ Đang upload video lên Drive... {progress}%")
file_id = response.get('id')
print(f"✅ Upload video lên Drive thành công! File ID: {file_id}")
await send_telegram_message(chat_id, f"✅ Đã upload video lên Google Drive thành công.")
return file_id
except Exception as e:
print(f"❌ Lỗi khi upload video lên Drive: {e}")
await send_telegram_message(chat_id, f"❌ Lỗi khi upload video lên Google Drive: {e}")
return None
async def list_files_in_drive_folder(drive_service, folder_id: str) -> list:
"""
Liệt kê TẤT CẢ các file trong một thư mục trên Drive, xử lý giới hạn 100 file/trang.
"""
all_files = []
page_token = None
try:
while True:
query = f"'{folder_id}' in parents and trashed=false"
# Thêm pageSize=1000 để tối ưu, và pageToken để lấy trang tiếp theo
response = await asyncio.to_thread(
drive_service.files().list(
q=query,
spaces='drive',
fields='nextPageToken, files(id, name)', # Lấy thêm nextPageToken
pageSize=1000, # Yêu cầu tối đa 1000 file mỗi lần
pageToken=page_token
).execute
)
# Thêm các file từ trang hiện tại vào danh sách tổng
all_files.extend(response.get('files', []))
# Lấy token của trang tiếp theo
page_token = response.get('nextPageToken', None)
# Nếu không còn trang tiếp theo, thoát khỏi vòng lặp
if page_token is None:
break
print(f"✅ Đã lấy thành công {len(all_files)} file từ thư mục ID: {folder_id}")
return all_files
except Exception as e:
print(f"❌ Lỗi khi liệt kê file trong thư mục Drive '{folder_id}': {e}")
return []
async def upload_file_to_drive_folder(drive_service, local_file_path: str, drive_folder_id: str) -> str | None:
"""Upload một file cục bộ lên một thư mục cụ thể trên Drive."""
try:
file_metadata = {
'name': os.path.basename(local_file_path),
'parents': [drive_folder_id]
}
media = MediaFileUpload(local_file_path, resumable=True)
request = drive_service.files().create(body=file_metadata, media_body=media, fields='id')
response = None
while response is None:
status, response = await asyncio.to_thread(request.next_chunk)
if status:
print(f" -> Đang upload '{os.path.basename(local_file_path)}' lên Drive... {int(status.progress() * 100)}%")
file_id = response.get('id')
print(f"✅ Upload file lên Drive thành công! File ID: {file_id}")
return file_id
except Exception as e:
print(f"❌ Lỗi khi upload file '{os.path.basename(local_file_path)}' lên Drive: {e}")
return None
async def delete_files_in_drive_folder(drive_service, folder_id: str, chat_id: int):
"""Xóa tất cả các file trong một thư mục trên Drive."""
await send_telegram_message(chat_id, f"🗑️ Bắt đầu dọn dẹp thư mục trung gian trên Drive...")
files_to_delete = await list_files_in_drive_folder(drive_service, folder_id)
if not files_to_delete:
print(f"✅ Không có file nào để dọn dẹp trong thư mục ID: {folder_id}")
return
for file in files_to_delete:
try:
await asyncio.to_thread(drive_service.files().delete(fileId=file.get('id')).execute)
print(f" -> Đã xóa file: {file.get('name')}")
except Exception as e:
print(f"❌ Lỗi khi xóa file '{file.get('name')}': {e}")
await send_telegram_message(chat_id, f"✅ Đã dọn dẹp xong các file trung gian.")
# ==============================================================================
# --- CÁC HÀM XỬ LÝ LÕI (CORE FUNCTIONS) - SAO CHÉP TỪ FILE GỐC VÀ TINH CHỈNH ---
# ==============================================================================
# Ghi chú: Logic bên trong các hàm này gần như được giữ nguyên.
# Chỉ thay đổi nhỏ liên quan đến đường dẫn file và cách đọc cấu hình.
def split_text_into_chunks(text: str, max_bytes: int = 4500) -> list[str]:
"""Tách văn bản thành các đoạn nhỏ hơn để phù hợp với API TTS."""
# --- LOGIC CŨ GIỮ NGUYÊN ---
sentences = re.split(r"(?<=\.)\s*", text)
chunks = []
current_chunk = ""
for sentence in sentences:
if not sentence.strip():
continue
separator = " " if current_chunk else ""
if len((current_chunk + separator + sentence).encode("utf-8")) > max_bytes:
if current_chunk:
chunks.append(current_chunk)
current_chunk = sentence
else:
current_chunk += separator + sentence
if current_chunk:
chunks.append(current_chunk.strip())
return chunks
async def merge_mp3_files_ffmpeg(segment_paths: list[str], final_output_path: str) -> bool:
"""Nối nhiều file MP3 thành một bằng ffmpeg."""
# --- LOGIC CŨ GIỮ NGUYÊN ---
# Đảm bảo thư mục đích tồn tại
os.makedirs(os.path.dirname(final_output_path), exist_ok=True)
list_file_path = os.path.join(TEMP_PATH, f"{os.path.basename(final_output_path)}.list.txt")
with open(list_file_path, "w", encoding="utf-8") as f:
for path in segment_paths:
f.write(f"file '{os.path.abspath(path)}'\n")
ffmpeg_cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", final_output_path]
try:
process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
_, stderr = await process.communicate()
if process.returncode != 0:
print(f"Lỗi FFmpeg khi nối file: {stderr.decode()}"); return False
return True
except FileNotFoundError:
print("Lỗi: Lệnh 'ffmpeg' không được tìm thấy."); return False
finally:
if os.path.exists(list_file_path):
os.remove(list_file_path)
async def convert_text_to_mp3_edge(text: str, output_path: str) -> bool:
"""Chuyển văn bản thành file mp3 bằng Microsoft Edge TTS."""
try:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
communicate = edge_tts.Communicate(text, voice="vi-VN-NamMinhNeural", rate="+10%")
await communicate.save(output_path)
return True
except Exception as e:
print(f"Lỗi khi gọi Edge TTS API cho {os.path.basename(output_path)}: {e}")
return False
# ==============================================================================
# --- HÀM TTS HUGGINGFACE (GIỌNG NGỌC HUYỀN) ---
# ==============================================================================
def _split_sentences_for_hf(text: str) -> list[str]:
"""Tách văn bản thành các câu riêng biệt để gửi cho HuggingFace TTS."""
text = re.sub(r'\s+', ' ', text).strip()
if not text: return []
sentences = re.split(r'(?<=[.?!…])\s+', text)
return [s.strip() for s in sentences if s.strip()]
async def convert_text_to_mp3_hf_ngochuyen(text: str, output_path: str, chat_id: int = None) -> bool:
"""
Chuyển văn bản thành file MP3 bằng HuggingFace Spaces TTS (giọng Ngọc Huyền).
Sử dụng cơ chế 88 Space song song với Queue & Retry tương tự DanTri.
"""
# 1. Cấu hình danh sách 88 Space
HF_SPACES = []
for i in range(1, 9): HF_SPACES.append(f"ktvoice/kt{i:03d}")
for g in range(0, 10):
prefix = f"ktvoice{g}"
for i in range(1, 9): HF_SPACES.append(f"{prefix}/kt{i:03d}")
VOICE_NAME = "Ngọc Huyền"
PAUSE_MODE = "Trung bình"
SPEED = 1.0
SILENCE_BETWEEN_SENTENCES = 0.8
MAX_RETRIES = 3
sentences = _split_sentences_for_hf(text)
if not sentences:
print("Lỗi: Văn bản đầu vào không chứa câu hợp lệ.")
return False
print(f"🎙️ [TTS HF] Bắt đầu xử lý: {len(sentences)} câu | Giọng: {VOICE_NAME}")
if chat_id:
await send_telegram_message(chat_id, f"🎙️ Đang tạo giọng đọc '{VOICE_NAME}' (HuggingFace)...\n- Tổng: {len(sentences)} câu")
# 2. Khởi tạo Clients (Preload song song)
active_clients = {}
def preload_client(space_name):
try:
return space_name, Client(space_name)
except Exception as e:
print(f"❌ Space chết: {space_name} ({e}) -> Bỏ qua.")
return space_name, None
loop = asyncio.get_event_loop()
print(f"🔌 Đang kiểm tra kết nối đến {len(HF_SPACES)} Spaces...")
preload_tasks = [loop.run_in_executor(None, preload_client, space) for space in HF_SPACES]
results = await asyncio.gather(*preload_tasks)
for space_name, client_obj in results:
if client_obj:
active_clients[space_name] = client_obj
available_spaces = list(active_clients.keys())
if not available_spaces:
print("❌ Toàn bộ Spaces đều không kết nối được!")
return False
print(f"✅ Đã kết nối: {len(available_spaces)}/{len(HF_SPACES)} Spaces hoạt động.")
if chat_id:
await send_telegram_message(chat_id, f"✅ Kết nối: {len(available_spaces)}/{len(HF_SPACES)} Spaces.")
# Phân tải thông minh: Mỗi account chỉ dùng 1 space/batch
def get_account_prefix(space_name):
return space_name.split('/')[0]
def select_balanced_spaces(all_spaces, count):
random.shuffle(all_spaces)
used_accounts = set()
selected = []
remaining = []
for sp in all_spaces:
acc = get_account_prefix(sp)
if acc not in used_accounts:
selected.append(sp)
used_accounts.add(acc)
else:
remaining.append(sp)
if len(selected) >= count:
break
if len(selected) < count:
random.shuffle(remaining)
selected.extend(remaining[:count - len(selected)])
return selected[:count]
temp_wav_files_map = {}
tasks_queue = list(enumerate(sentences))
sentence_retry_count = {i: 0 for i in range(len(sentences))}
# 3. Worker function
def call_gradio_tts_sync(space_name, sentence_text, index):
try:
client = active_clients.get(space_name)
if not client: raise ValueError("Client mất kết nối")
result = client.predict(
sentence_text, VOICE_NAME, None, "", "preset", PAUSE_MODE, SPEED, api_name="/tts"
)
print(f"[TTS HF] Space: {space_name} | Result type: {type(result)} | Index: {index}")
audio_origin_path = None
if isinstance(result, (list, tuple)):
for item in result:
if isinstance(item, str) and (item.endswith('.wav') or item.endswith('.mp3') or os.path.exists(str(item))):
audio_origin_path = item
break
if not audio_origin_path and len(result) > 0 and result[0] is not None:
audio_origin_path = result[0]
elif isinstance(result, str):
audio_origin_path = result
elif isinstance(result, dict):
audio_origin_path = result.get('audio') or result.get('path') or result.get('name')
if not audio_origin_path or not os.path.exists(str(audio_origin_path)):
raise ValueError(f"API trả về không chứa file audio hợp lệ. Result: {result}")
dest_filename = f"part_{index}_{random.randint(10000,99999)}.wav"
dest_path = os.path.join(TEMP_PATH, dest_filename)
shutil.copy(str(audio_origin_path), dest_path)
return index, dest_path, None
except Exception as e:
return index, None, f"Lỗi tại {space_name}: {str(e)}"
# 4. Queue processing
while tasks_queue:
num_tasks_to_run = min(len(tasks_queue), len(available_spaces))
current_batch = tasks_queue[:num_tasks_to_run]
tasks_queue = tasks_queue[num_tasks_to_run:]
spaces_for_batch = select_balanced_spaces(available_spaces, num_tasks_to_run)
print(f"--- ⚡ Batch: {len(current_batch)} câu (Còn lại: {len(tasks_queue)}) ---")
batch_futures = []
for i, (sent_idx, sent_text) in enumerate(current_batch):
space = spaces_for_batch[i]
batch_futures.append(
loop.run_in_executor(None, call_gradio_tts_sync, space, sent_text, sent_idx)
)
results = await asyncio.gather(*batch_futures)
for res_idx, res_path, res_error in results:
if res_path:
temp_wav_files_map[res_idx] = res_path
else:
retry_times = sentence_retry_count[res_idx]
if retry_times < MAX_RETRIES:
sentence_retry_count[res_idx] += 1
print(f"⚠️ Câu {res_idx+1} lỗi: {res_error} | Thử lại lần {sentence_retry_count[res_idx]}")
tasks_queue.append((res_idx, sentences[res_idx]))
else:
print(f"❌ Câu {res_idx+1} thất bại hoàn toàn sau {MAX_RETRIES} lần thử.")
# 5. Ghép file
sorted_indices = sorted(temp_wav_files_map.keys())
if not sorted_indices:
print("❌ Không tạo được file audio nào.")
return False
if len(sorted_indices) < len(sentences):
print(f"⚠️ Cảnh báo: Chỉ tạo được {len(sorted_indices)}/{len(sentences)} câu.")
concat_list_path = os.path.join(TEMP_PATH, f"concat_hf_{os.path.basename(output_path)}.txt")
try:
print("⏳ Đang ghép nối file...")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Tạo file silence
silence_wav_path = os.path.join(TEMP_PATH, "silence_hf_gap.wav")
ffmpeg_create_silence = ['ffmpeg', '-y', '-f', 'lavfi', '-i', f'anullsrc=r=24000:cl=mono', '-t', str(SILENCE_BETWEEN_SENTENCES), silence_wav_path]
process = await asyncio.create_subprocess_exec(*ffmpeg_create_silence, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await process.communicate()
# Tạo concat list
with open(concat_list_path, "w") as f:
for idx in sorted_indices:
wav_file = temp_wav_files_map[idx]
f.write(f"file '{os.path.abspath(wav_file)}'\n")
if idx < sorted_indices[-1]:
f.write(f"file '{os.path.abspath(silence_wav_path)}'\n")
# Ghép thành WAV rồi convert sang MP3
temp_wav_output = output_path.replace('.mp3', '_temp.wav')
ffmpeg_concat = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', temp_wav_output]
process = await asyncio.create_subprocess_exec(*ffmpeg_concat, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
_, stderr = await process.communicate()
if process.returncode != 0:
raise subprocess.CalledProcessError(process.returncode, ffmpeg_concat, stderr=stderr)
# Convert WAV -> MP3
ffmpeg_to_mp3 = ['ffmpeg', '-y', '-i', temp_wav_output, '-codec:a', 'libmp3lame', '-b:a', '128k', output_path]
process = await asyncio.create_subprocess_exec(*ffmpeg_to_mp3, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
_, stderr = await process.communicate()
if process.returncode != 0:
raise subprocess.CalledProcessError(process.returncode, ffmpeg_to_mp3, stderr=stderr)
# Dọn file WAV tạm
if os.path.exists(temp_wav_output): os.remove(temp_wav_output)
if os.path.exists(silence_wav_path): os.remove(silence_wav_path)
print(f"✅ Hoàn tất TTS HuggingFace: {output_path}")
if chat_id:
await send_telegram_message(chat_id, f"✅ Hoàn tất giọng đọc ({len(sorted_indices)}/{len(sentences)} câu).")
return True
except Exception as e:
print(f"❌ Lỗi ghép file TTS HuggingFace: {e}")
return False
finally:
for path in temp_wav_files_map.values():
if os.path.exists(path): os.remove(path)
if os.path.exists(concat_list_path): os.remove(concat_list_path)
async def convert_text_to_mp3_google(text: str, output_path: str) -> bool:
"""Chuyển văn bản thành file mp3 bằng Google TTS API."""
# --- SỬA ĐỔI ---
# Sử dụng biến GOOGLE_TTS_API_KEY toàn cục đã được đọc lúc khởi động.
if not GOOGLE_TTS_API_KEY:
print("Lỗi: GOOGLE_TTS_API_KEY chưa được cấu hình.")
return False
url = f"https://texttospeech.googleapis.com/v1/text:synthesize?key={GOOGLE_TTS_API_KEY}"
body = {
"input": {"text": text},
"voice": {"languageCode": "vi-VN", "name": "vi-VN-Standard-A", "ssmlGender": "FEMALE"},
"audioConfig": {"audioEncoding": "MP3", "speakingRate": 1.15, "pitch": 0.0, "volumeGainDb": 0.0}
}
try:
# Đảm bảo thư mục đích tồn tại
os.makedirs(os.path.dirname(output_path), exist_ok=True)
response = await asyncio.to_thread(requests.post, url, json=body, timeout=180)
response.raise_for_status()
audio_content = response.json().get("audioContent")
if audio_content:
with open(output_path, "wb") as f:
f.write(base64.b64decode(audio_content))
return True
return False
except Exception as e:
print(f"Lỗi khi gọi Google TTS API cho {os.path.basename(output_path)}: {e}")
return False
async def read_audio_config_from_excel() -> dict:
"""
Đọc cấu hình từ file Excel.
THAY ĐỔI: Hàm này giờ sẽ đọc Google Drive File ID cho ảnh và font.
"""
config = {
"top": "", "end": "", "replacements": [],
"story_name": "Audio Book", "title_suffix": "Audio",
# Các key cho đường dẫn cục bộ sau khi tải về
"image_path": None, "title_font_path": None, "chap_font_path": None,
# Các key mới để lưu File ID từ Google Drive
"image_file_id": None, "title_font_file_id": None, "chap_font_file_id": None,
"title_font_size": 150, "chap_font_size": 130,
"description": "", "tags": [] # Thêm key mới
}
try:
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl")
# Đọc các cấu hình văn bản như cũ
if df.shape[0] > 1 and df.shape[1] > 3 and pd.notna(df.iloc[1, 3]): config["top"] = str(df.iloc[1, 3])
if df.shape[0] > 2 and df.shape[1] > 3 and pd.notna(df.iloc[2, 3]): config["end"] = str(df.iloc[2, 3])
if df.shape[1] > 4: config["replacements"] = df.iloc[1:10, 4].dropna().astype(str).tolist()
if df.shape[0] > 3 and df.shape[1] > 6 and pd.notna(df.iloc[3, 6]): config["story_name"] = str(df.iloc[3, 6])
if df.shape[0] > 0 and df.shape[1] > 10 and pd.notna(df.iloc[0, 10]): config["title_suffix"] = str(df.iloc[0, 10])
# === THAY ĐỔI QUAN TRỌNG: Đọc Google Drive File ID thay vì đường dẫn tĩnh ===
# Ô F2 (index 1, 5) -> image_file_id
if df.shape[0] > 1 and df.shape[1] > 5 and pd.notna(df.iloc[1, 5]): config["image_file_id"] = str(df.iloc[1, 5])
# Ô G2 (index 1, 6) -> title_font_file_id
if df.shape[0] > 1 and df.shape[1] > 6 and pd.notna(df.iloc[1, 6]): config["title_font_file_id"] = str(df.iloc[1, 6])
# Ô H2 (index 1, 7) -> chap_font_file_id
if df.shape[0] > 1 and df.shape[1] > 7 and pd.notna(df.iloc[1, 7]): config["chap_font_file_id"] = str(df.iloc[1, 7])
# Đọc kích thước font
if df.shape[0] > 2 and df.shape[1] > 6 and pd.notna(df.iloc[2, 6]): config["title_font_size"] = int(df.iloc[2, 6])
if df.shape[0] > 2 and df.shape[1] > 7 and pd.notna(df.iloc[2, 7]): config["chap_font_size"] = int(df.iloc[2, 7])
# <<< BLOCK CODE MỚI BẮT ĐẦU
# Đọc Description từ ô L1 (index 0, 11)
if df.shape[1] > 11 and pd.notna(df.iloc[0, 11]):
config["description"] = str(df.iloc[0, 11])
# Đọc Tags từ ô M1 (index 0, 12), tách chuỗi thành list
if df.shape[1] > 12 and pd.notna(df.iloc[0, 12]):
tags_str = str(df.iloc[0, 12])
config["tags"] = [tag.strip() for tag in tags_str.split(',') if tag.strip()]
# <<< BLOCK CODE MỚI KẾT THÚC
except Exception as e:
print(f"Lỗi khi đọc cấu hình từ Excel: {e}")
return config
async def scrape_chapter_content(url: str, replacements: list[str]) -> tuple[str, str, str] | None:
"""Bóc tách nội dung của một chương truyện."""
# --- LOGIC CŨ GIỮ NGUYÊN ---
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}
try:
response = await asyncio.to_thread(requests.get, url, headers=headers, timeout=20)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
title_tag = soup.select_one("a.chapter-title")
raw_title = title_tag.get_text(strip=True) if title_tag else "Không tìm thấy tiêu đề"
match = re.search(r"Chương\s*(\d+)", raw_title, re.IGNORECASE)
chapter_number_str = f"unk_{pd.Timestamp.now().strftime('%H%M%S')}"
if match:
chapter_number_str = match.group(1).zfill(4)
final_title = raw_title
if not final_title.endswith('.'): final_title += '.'
content_div = soup.select_one("div#chapter-c")
if not content_div: return None
for ad_element in content_div.select("div, script, ins, style, [class*='ads']"):
ad_element.decompose()
content = content_div.get_text("\n", strip=True)
for unwanted_str in replacements:
content = content.replace(unwanted_str, "")
content = "\n".join(line for line in content.split('\n') if line.strip())
return final_title, content, chapter_number_str
except Exception as e:
print(f"Lỗi khi bóc tách nội dung từ {url}: {e}"); return None
async def read_links_from_excel() -> list[str]:
"""Đọc danh sách link từ file Excel cục bộ."""
# --- LOGIC CŨ GIỮ NGUYÊN ---
try:
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl")
if 1 in df.columns:
return df.loc[1:, 1].dropna().astype(str).tolist()
except FileNotFoundError:
print(f"Lỗi: Không tìm thấy file Excel tại {WORKING_EXCEL_PATH}")
return []
except Exception as e:
print(f"Lỗi khi đọc link từ Excel: {e}")
return []
return []
def escape_ffmpeg_text(text):
"""Thoát các ký tự đặc biệt cho bộ lọc drawtext của ffmpeg."""
# --- LOGIC CŨ GIỮ NGUYÊN ---
return text.replace('\\', '\\\\').replace("'", r"\'").replace(':', r'\:').replace('%', r'\%').replace(',', r'\,')
async def generate_single_mp4_with_effect(mp3_path: str, config: dict, chat_id: int) -> str | None:
"""Tạo video từ file MP3 và ảnh nền (đã tối ưu hóa tốc độ)."""
required_paths = [mp3_path, config.get("image_path"), config.get("title_font_path"), config.get("chap_font_path")]
for path in required_paths:
if not path or not os.path.exists(path): # Kiểm tra cả None và sự tồn tại
error_msg = f"❌ Lỗi Gen MP4: Không tìm thấy file hoặc đường dẫn tài nguyên: {path}"
print(error_msg)
await send_telegram_message(chat_id, error_msg)
return None
base_name = os.path.splitext(os.path.basename(mp3_path))[0]
output_path = os.path.join(AUDIO_VIDEO_FOLDER, f"{base_name}.mp4")
temp_video_path = os.path.join(TEMP_PATH, f"temp_{base_name}.mp4")
try:
story_name_text = escape_ffmpeg_text(config.get("story_name", ""))
chap_text_final = f"Tập {base_name}"
chap_nums = base_name.split('_')
if len(chap_nums) == 2:
try:
start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1])
chap_text_final = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
except ValueError:
chap_text_final = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
chap_text = escape_ffmpeg_text(chap_text_final)
title_font = str(config.get("title_font_path")).replace('\\', '/')
print(f"[*] Bước 1/2: Đang tạo video mẫu 3 giây cho '{base_name}'...")
drawtext_filter = (
f"drawtext=fontfile='{title_font}':text='{story_name_text}':fontsize={config.get('title_font_size', 150)}:fontcolor=Red:x=100:y=50:shadowcolor=black@0.7:shadowx=2:shadowy=2,"
f"drawtext=fontfile='{title_font}':text='{chap_text}':fontsize={config.get('chap_font_size', 130)}:fontcolor=Red:x=100:y=320:shadowcolor=black@0.7:shadowx=2:shadowy=2"
)
ffmpeg_cmd_step1 = [
'ffmpeg', '-y', '-loop', '1', '-i', str(config.get("image_path")),
'-vf', drawtext_filter, '-t', '3', '-pix_fmt', 'yuv420p',
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '28', temp_video_path
]
process1 = await asyncio.create_subprocess_exec(*ffmpeg_cmd_step1, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
_, stderr1 = await process1.communicate()
if process1.returncode != 0:
print(f"❌ LỖI FFMPEG (Bước 1): {stderr1.decode()}"); return None
print(f"[*] Bước 2/2: Đang ghép video và audio cho '{base_name}'...")
ffmpeg_cmd_step2 = [
'ffmpeg', '-y', '-stream_loop', '-1', '-i', temp_video_path,
'-i', mp3_path, '-map', '0:v:0', '-map', '1:a:0',
'-c:v', 'copy', '-af', 'volume=1.3','-c:a', 'aac', '-b:a', '128k', '-shortest', output_path
]
process2 = await asyncio.create_subprocess_exec(*ffmpeg_cmd_step2, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
_, stderr2 = await process2.communicate()
if process2.returncode != 0:
print(f"❌ LỖI FFMPEG (Bước 2): {stderr2.decode()}"); return None
print(f"✅ Tạo MP4 thành công (tối ưu): {output_path}")
return output_path
except Exception as e:
print(f"❌ Lỗi không xác định khi tạo MP4 cho '{base_name}': {e}"); return None
finally:
if os.path.exists(temp_video_path):
os.remove(temp_video_path)
async def modify_excel_sheet(modifications: callable):
"""Hàm lõi an toàn để sửa đổi file Excel cục bộ."""
# --- LOGIC CŨ GIỮ NGUYÊN, BỎ KHÓA ASYNCIO VÌ ĐANG CHẠY TRONG 1 LUỒNG ---
try:
book = load_workbook(WORKING_EXCEL_PATH)
modifications(book)
book.save(WORKING_EXCEL_PATH)
return True
except Exception as e:
print(f"Lỗi nghiêm trọng khi sửa đổi file Excel: {e}")
return False
async def clear_excel_audio_links():
"""Xóa dữ liệu ở cột B và C của sheet 'Audio'."""
def clear_data(book):
if "Audio" not in book.sheetnames: return
ws = book["Audio"]
for row in ws.iter_rows(min_row=2, min_col=2, max_col=3):
for cell in row:
cell.value = None
print("✅ Đã xóa dữ liệu link trong sheet 'Audio'.")
return await modify_excel_sheet(clear_data)
async def update_audio_sheet(data: list[dict], is_first_scrape: bool) -> bool:
"""Cập nhật SỐ CHƯƠNG CHUẨN, link và tiêu đề vào sheet 'Audio'."""
new_chap_nums = [item.get("chapter_number") for item in data]
new_links = [item["link"] for item in data]
new_titles = [item["title"] for item in data]
def update_data(book):
ws = book["Audio"]
if ws.cell(row=1, column=1).value is None: # Kiểm tra header cột A
ws.cell(row=1, column=1, value="Chapter Number")
ws.cell(row=1, column=2, value="Link")
ws.cell(row=1, column=3, value="Title")
start_row = 2 if is_first_scrape else ws.max_row + 1
for i, (chap_num, link, title) in enumerate(zip(new_chap_nums, new_links, new_titles)):
# Ghi dữ liệu vào đúng cột: A, B, C
if chap_num is not None:
ws.cell(row=start_row + i, column=1, value=chap_num) # <<< Cột A
ws.cell(row=start_row + i, column=2, value=link) # <<< Cột B
ws.cell(row=start_row + i, column=3, value=title) # <<< Cột C
print(f"✅ Đã cập nhật {len(new_links)} link mới (vào cột A, B, C) trong sheet 'Audio'.")
return await modify_excel_sheet(update_data)
async def update_excel_for_youtube(video_data: list[dict]) -> bool:
"""Cập nhật đường dẫn video và tiêu đề cho YouTube."""
def update_yt_data(book):
if "Audio" not in book.sheetnames: return
ws = book["Audio"]
paths = [item['path'] for item in video_data]
titles = [item['title'] for item in video_data]
for i, (path, title) in enumerate(zip(paths, titles)):
ws.cell(row=i + 2, column=9, value=path)
ws.cell(row=i + 2, column=10, value=title)
print(f"✅ Đã cập nhật {len(paths)} video vào Excel cho YouTube.")
return await modify_excel_sheet(update_yt_data)
async def rewrite_excel_links(links_to_keep: list[dict]):
"""Xóa và ghi lại các cột số chương/link/tiêu đề trong sheet 'Audio'."""
def modify_links(book):
if "Audio" not in book.sheetnames: return
ws = book["Audio"]
# Xóa dữ liệu từ cột A đến C (index 1-3)
for row in ws.iter_rows(min_row=2, min_col=1, max_col=3):
for cell in row:
cell.value = None
# Ghi lại dữ liệu mới
for i, item in enumerate(links_to_keep):
if item.get('chapter_number') is not None:
ws.cell(row=i + 2, column=1, value=item.get('chapter_number')) # Cột A
ws.cell(row=i + 2, column=2, value=item.get('link')) # Cột B
ws.cell(row=i + 2, column=3, value=item.get('title')) # Cột C
print(f"✅ Đã ghi lại {len(links_to_keep)} link chưa xử lý vào Excel.")
return await modify_excel_sheet(modify_links)
async def upload_single_video_to_youtube_audio(account_number: int, video_path: str, video_title: str, chat_id: int, config: dict) -> bool:
"""Upload một video lên YouTube, đã tích hợp quy trình xác thực mới."""
try:
# 1. Lấy credentials chính của Drive
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
raise Exception("Không thể lấy credentials của Drive.")
drive_service = build('drive', 'v3', credentials=drive_creds)
# 2. Tìm và tải file token của tài khoản YouTube từ Drive
token_filename = f'token_youtube_account_{account_number}.pickle'
print(f"[*] Đang tìm kiếm '{token_filename}' trong thư mục Drive '{DRIVE_YTB_ACCOUNT_FOLDER_ID}'...")
query = f"name='{token_filename}' and '{DRIVE_YTB_ACCOUNT_FOLDER_ID}' in parents and trashed=false"
response = await asyncio.to_thread(drive_service.files().list(q=query, fields='files(id, name)').execute)
files = response.get('files', [])
if not files:
await send_telegram_message(chat_id, f"❌ Lỗi: Không tìm thấy file token cho tài khoản {account_number} trên Drive.")
return False
file_id = files[0].get('id')
local_yt_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, token_filename)
await download_file_from_drive(drive_service, file_id, local_yt_token_path)
# 3. Load credentials YouTube và thực hiện upload
with open(local_yt_token_path, 'rb') as token:
yt_creds = pickle.load(token)
if not yt_creds or not yt_creds.valid:
if yt_creds and yt_creds.expired and yt_creds.refresh_token:
print(f"[*] Token YouTube cho tài khoản {account_number} đã hết hạn, đang làm mới...")
yt_creds.refresh(GoogleAuthRequest())
# Lưu lại file token mới vào thư mục tạm
with open(local_yt_token_path, 'wb') as token:
pickle.dump(yt_creds, token)
print(f"[*] Làm mới token thành công. Đang upload token mới lên Google Drive...")
# === PHẦN SỬA ĐỔI QUAN TRỌNG ===
# Tìm file token cũ trên Drive để lấy ID và ghi đè
token_file_on_drive = files[0] # files là kết quả từ drive_service.files().list()
media = MediaFileUpload(local_yt_token_path)
await asyncio.to_thread(
drive_service.files().update(fileId=token_file_on_drive.get('id'), media_body=media).execute
)
print(f"[*] Upload token mới thành công.")
# === KẾT THÚC SỬA ĐỔI ===
else:
raise Exception(f"Token cho tài khoản {account_number} không hợp lệ hoặc đã hết hạn.")
youtube = build('youtube', 'v3', credentials=yt_creds)
body = {
'snippet': {
'title': video_title,
'description': config.get("description", ""), # <<< DÒNG THAY ĐỔI
'tags': config.get("tags", []), # <<< DÒNG THAY ĐỔI
'categoryId': '22'
},
'status': {
'privacyStatus': 'public',
'selfDeclaredMadeForKids': False
}
}
media = MediaFileUpload(video_path, chunksize=-1, resumable=True)
request = youtube.videos().insert(part=",".join(body.keys()), body=body, media_body=media)
response = None
while response is None:
status, response = await asyncio.to_thread(request.next_chunk)
if status: print(f" -> Uploading to YouTube... {int(status.progress() * 100)}%")
# === PHẦN SỬA ĐỔI QUAN TRỌNG ===
if response and 'id' in response:
video_id = response.get('id')
await send_telegram_message(chat_id, f"✅ Upload YouTube thành công: `{video_title}`\n🔗 Link: https://www.youtube.com/watch?v={video_id}")
return True
else:
# Nếu không có 'id', upload đã thất bại. Gửi thông báo lỗi chi tiết.
error_details = str(response) if response else "Không nhận được phản hồi từ YouTube API."
print(f"❌ Lỗi Upload YouTube: {error_details}")
await send_telegram_message(chat_id, f"❌ Lỗi khi upload video `{video_title}` lên YouTube.\n<b>Chi tiết:</b> <pre>{error_details}</pre>", parse_mode="HTML")
return False
except Exception as e:
await send_telegram_message(chat_id, f"❌ Lỗi khi upload video `{video_title}`: {e}")
return False
async def process_and_generate_text_files(chat_id: int):
"""Quy trình cho nút 'Get File', chạy dưới dạng tác vụ nền."""
await send_telegram_message(chat_id=chat_id, text="🔍 Bắt đầu quy trình Get File...")
replacement_map = await _read_replacement_map_from_excel()
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive."); return
drive_service = build('drive', 'v3', credentials=drive_creds)
try:
# Sửa: Đọc đúng các cột A, B, C (index 0, 1, 2)
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1, 2])
all_links_data = []
for index, row in df.loc[1:].iterrows():
chap_num = int(row.get(0)) if pd.notna(row.get(0)) else None # Đọc cột A
link = str(row.get(1)) if pd.notna(row.get(1)) else None # Đọc cột B
title = str(row.get(2)) if pd.notna(row.get(2)) else "" # Đọc cột C
if link:
all_links_data.append({'link': link, 'title': title, 'chapter_number': chap_num})
except Exception as e:
await send_telegram_message(chat_id, f"❌ Lỗi khi đọc file Excel: {e}"); return
if not all_links_data:
await send_telegram_message(chat_id, "Không tìm thấy link nào trong sheet 'Audio'."); return
await send_telegram_message(chat_id, f"✅ Tìm thấy {len(all_links_data)} link. Bắt đầu xử lý...")
config = await read_audio_config_from_excel()
os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
new_count, skipped_count, error_links_data = 0, 0, []
created_local_files = []
existing_txt_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)}
for i, link_data in enumerate(all_links_data):
try:
chapter_number_from_excel = link_data.get('chapter_number')
if chapter_number_from_excel is None:
# Sửa thông báo cho đúng
print(f"⚠️ Bỏ qua link {link_data['link']} vì không có số chương ở cột A.")
error_links_data.append(link_data)
continue
filename = f"{str(chapter_number_from_excel).zfill(4)}.txt"
if filename in existing_txt_on_drive:
skipped_count += 1
continue
result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
if result:
title, body, _ = result
filepath = os.path.join(AUDIO_TXT_FOLDER, filename)
file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
final_content = _apply_replacements(file_content, replacement_map)
with open(filepath, 'w', encoding='utf-8') as f: f.write(final_content)
new_count += 1
created_local_files.append(filepath)
else:
error_links_data.append(link_data)
except Exception as e:
print(f"Lỗi xử lý link {link_data['link']}: {e}")
error_links_data.append(link_data)
if created_local_files:
await send_telegram_message(chat_id, f"Đang upload {len(created_local_files)} file .txt lên Google Drive...")
for local_path in created_local_files:
await upload_file_to_drive_folder(drive_service, local_path, DRIVE_AUDIO_TXT_FOLDER_ID)
await send_telegram_message(chat_id, "...Đang cập nhật lại file Excel...")
await rewrite_excel_links(error_links_data)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
final_message = (f"🎉 **GET FILE HOÀN TẤT** 🎉\n\n"
f"- Tạo mới và upload: **{new_count}** file .txt\n"
f"- Bỏ qua (đã có trên Drive): **{skipped_count}** file\n"
f"- Lỗi: **{len(error_links_data)}** link (được giữ lại trong Excel)\n\n"
f"✅ Các file .txt đã sẵn sàng trên Google Drive.")
await send_telegram_message(chat_id, final_message, reply_markup=AUDIO_MENU_KEYBOARD)
async def run_full_mp3_generation_process(chat_id: int, user_data: dict):
voice_choice = user_data.get("voice_choice", "female")
voice_names = {"male": "Nam", "female": "Nữ", "ngochuyen": "Ngọc Huyền"}
voice_name = voice_names.get(voice_choice, "Nữ")
await send_telegram_message(chat_id=chat_id, text="🚀 Bắt đầu quy trình tạo MP3 (có khả năng phục hồi)...")
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
return
drive_service = build('drive', 'v3', credentials=drive_creds)
# --- GIAI ĐOẠN 1: TẠO MP3 TỪNG CHƯƠNG ---
await send_telegram_message(chat_id, "➡️ GĐ 1/2: Tạo MP3 chương...")
# Tải các file txt từ Drive về
txt_files_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)
if not txt_files_on_drive:
await send_telegram_message(chat_id, "Không tìm thấy file .txt nào trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD); return
os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
await send_telegram_message(chat_id, f"Đang tải {len(txt_files_on_drive)} file .txt từ Drive...")
for file in txt_files_on_drive:
await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_TXT_FOLDER, file['name']))
# Lấy danh sách chapter MP3 đã có trên Drive để bỏ qua
existing_mp3s_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)}
local_txt_files = sorted(os.listdir(AUDIO_TXT_FOLDER))
for i, filename in enumerate(local_txt_files):
base_name = os.path.splitext(filename)[0]
mp3_filename = f"{base_name}.mp3"
if mp3_filename in existing_mp3s_on_drive:
print(f"Bỏ qua {mp3_filename}, đã có trên Drive.")
continue
#await send_telegram_message(chat_id, f"⚙️ 1/2: Đang xử lý `{filename}` ({i + 1}/{len(local_txt_files)})...")
temp_dir = os.path.join(TEMP_PATH, f"temp_{base_name}"); os.makedirs(temp_dir, exist_ok=True)
is_ok, segments, chapter_mp3_path = True, [], os.path.join(AUDIO_MP3_FOLDER, mp3_filename)
#try:
# with open(os.path.join(AUDIO_TXT_FOLDER, filename), "r", encoding="utf-8") as f: text = f.read()
# chunks = split_text_into_chunks(text)
# for j, chunk in enumerate(chunks):
# seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
# if voice_choice == 'male':
# if not await convert_text_to_mp3_edge(chunk, seg_path): is_ok = False; break
# else: # Mặc định hoặc 'female'
# if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
# #segments.append(seg_path)
#
# #if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
# segments.append(seg_path)
# if is_ok and segments and not await merge_mp3_files_ffmpeg(segments, chapter_mp3_path): is_ok = False
#finally: shutil.rmtree(temp_dir)
#if is_ok:
# await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
try:
with open(os.path.join(AUDIO_TXT_FOLDER, filename), "r", encoding="utf-8") as f:
text = f.read()
chunks = split_text_into_chunks(text)
if voice_choice == 'ngochuyen':
# Giọng Ngọc Huyền: gửi toàn bộ text cho HuggingFace xử lý theo câu
if not await convert_text_to_mp3_hf_ngochuyen(text, chapter_mp3_path, chat_id):
is_ok = False
else:
# HF đã tạo file MP3 xong, không cần merge nữa
segments = [] # Clear để skip merge step
else:
for j, chunk in enumerate(chunks):
seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
if voice_choice == 'male':
if not await convert_text_to_mp3_edge(chunk, seg_path): is_ok = False; break
else:
if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
segments.append(seg_path)
# Chỉ merge và upload khi các bước trước thành công
if is_ok and segments:
if await merge_mp3_files_ffmpeg(segments, chapter_mp3_path):
await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
else:
is_ok = False
elif is_ok and voice_choice == 'ngochuyen' and os.path.exists(chapter_mp3_path):
# HF đã tạo file trực tiếp, chỉ cần upload
await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
except Exception as e:
print(f"Lỗi khi xử lý file {filename}: {e}")
is_ok = False
finally:
# Luôn dọn dẹp thư mục tạm sau khi tất cả đã xong
shutil.rmtree(temp_dir)
# --- GIAI ĐOẠN 2: NỐI CÁC FILE MP3 ---
await send_telegram_message(chat_id, f"➡️ GĐ 2/2: Nối các file MP3 chương...")
try:
df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
group_size = int(df_audio.iloc[0, 3])
except: group_size = 20 # Giá trị mặc định
all_chapter_mp3s = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)
if not all_chapter_mp3s:
await send_telegram_message(chat_id, "Lỗi: Không tìm thấy file MP3 chương nào trên Drive để nối."); return
# Tải tất cả MP3 chương về để nối
os.makedirs(AUDIO_MP3_FOLDER, exist_ok=True)
for file in all_chapter_mp3s:
await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_MP3_FOLDER, file['name']))
local_mp3_paths = sorted([os.path.join(AUDIO_MP3_FOLDER, f) for f in os.listdir(AUDIO_MP3_FOLDER)])
file_groups = [local_mp3_paths[i : i + group_size] for i in range(0, len(local_mp3_paths), group_size)]
existing_final_mp3s_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)}
for i, group in enumerate(file_groups):
if not group: continue
first, last = os.path.splitext(os.path.basename(group[0]))[0], os.path.splitext(os.path.basename(group[-1]))[0]
final_name = f"{first}_{last}.mp3"
if final_name in existing_final_mp3s_on_drive:
print(f"Bỏ qua nối file {final_name}, đã có trên Drive.")
continue
#await send_telegram_message(chat_id, f"⚙️ 2/2: Nối nhóm {i + 1}/{len(file_groups)} -> `{final_name}`...")
final_output_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)
if await merge_mp3_files_ffmpeg(group, final_output_path):
await upload_file_to_drive_folder(drive_service, final_output_path, DRIVE_AUDIO_FINAL_FOLDER_ID)
await send_telegram_message(chat_id, "🎉 **QUY TRÌNH MP3 HOÀN TẤT** 🎉\nCác file MP3 đã nối đã sẵn sàng trên Google Drive.", reply_markup=AUDIO_MENU_KEYBOARD)
async def process_and_generate_mp4_files(chat_id: int, user_data: dict):
await send_telegram_message(chat_id=chat_id, text="🔍 Bắt đầu quy trình tạo Video cuối cùng...")
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
return
drive_service = build('drive', 'v3', credentials=drive_creds)
# --- TẢI TÀI NGUYÊN (FONT, ẢNH NỀN) TỪ DRIVE ---
await send_telegram_message(chat_id, "➡️ Bước 1/4: Tải tài nguyên (font, ảnh nền)...")
config = await read_audio_config_from_excel()
try:
# Lấy File ID từ config
image_file_id = config.get("image_file_id")
title_font_id = config.get("title_font_file_id")
chap_font_id = config.get("chap_font_file_id")
if not all([image_file_id, title_font_id, chap_font_id]):
await send_telegram_message(chat_id, "❌ Lỗi cấu hình: Vui lòng cung cấp đủ File ID cho ảnh nền, font tiêu đề và font chương trong file Excel (ô F2, G2, H2).")
return
# Đường dẫn lưu file cục bộ trên Hugging Face
local_image_path = os.path.join(TEMP_PATH, "background_image.jpg")
local_title_font_path = os.path.join(TEMP_PATH, "title_font.ttf")
local_chap_font_path = os.path.join(TEMP_PATH, "chap_font.ttf")
# Tải file từ Drive
await send_telegram_message(chat_id, "...Đang tải ảnh nền...")
await download_file_from_drive(drive_service, image_file_id, local_image_path)
await send_telegram_message(chat_id, "...Đang tải font chữ...")
await download_file_from_drive(drive_service, title_font_id, local_title_font_path)
await download_file_from_drive(drive_service, chap_font_id, local_chap_font_path)
config["image_path"] = local_image_path
config["title_font_path"] = local_title_font_path
config["chap_font_path"] = local_chap_font_path
except Exception as e:
await send_telegram_message(chat_id, f"❌ Lỗi nghiêm trọng khi tải file tài nguyên từ Drive: {e}\nHãy kiểm tra lại File ID trong Excel và quyền truy cập file.")
return
# --- TẢI CÁC FILE MP3 ĐÃ NỐI ---
await send_telegram_message(chat_id, "➡️ Bước 2/4: Tải các file MP3 đã nối...")
final_mp3s_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)
if not final_mp3s_on_drive:
await send_telegram_message(chat_id, "Không tìm thấy file MP3 đã nối nào trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD); return
os.makedirs(AUDIO_FINAL_FOLDER, exist_ok=True)
for file in final_mp3s_on_drive:
await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_FINAL_FOLDER, file['name']))
# --- TẠO VIDEO ---
await send_telegram_message(chat_id, f"✅ Sẵn sàng tạo video. Bước 3/4: Bắt đầu xử lý...")
existing_videos_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}
successful_videos, new_count, success_count, skipped_count = [], 0, 0, 0
local_mp3_files = sorted(os.listdir(AUDIO_FINAL_FOLDER))
for i, mp3_filename in enumerate(local_mp3_files):
#await send_telegram_message(chat_id, f"⚙️ 3/4: Đang tạo video cho `{mp3_filename}` ({i + 1}/{len(local_mp3_files)})...")
base_name = os.path.splitext(mp3_filename)[0]
mp4_filename = f"{base_name}.mp4"
if mp4_filename in existing_videos_on_drive:
print(f"[*] Bỏ qua '{mp4_filename}', đã tồn tại trên Drive.")
skipped_count += 1
# Thêm vào danh sách để vẫn có thể upload lên Youtube nếu cần
successful_videos.append({"path": os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename), "base_name": base_name})
continue
source_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
generated_path = await generate_single_mp4_with_effect(source_mp3_path, config, chat_id)
if generated_path:
success_count += 1
#base_name = os.path.splitext(mp3_filename)[0]
successful_videos.append({"path": generated_path, "base_name": base_name})
await upload_video_to_drive_audio(drive_service, generated_path, chat_id)
if not successful_videos:
await send_telegram_message(chat_id, "❌ Không tạo được video nào.", reply_markup=AUDIO_MENU_KEYBOARD); return
final_message = f"✅ **Tạo Video hoàn tất!**\n- Tạo thành công: **{success_count}** video.\n- Bỏ qua (đã có): **{skipped_count}** video."
await send_telegram_message(chat_id, final_message)
video_data_for_excel = []
for video in successful_videos:
# ... (logic tạo title video giữ nguyên)
chap_range = f"Tập {video['base_name']}"; chap_nums = video["base_name"].split("_")
if len(chap_nums) == 2:
try:
start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1]); chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
except ValueError: chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
video_data_for_excel.append({"path": video["path"], "title": title})
# Upload video cuối cùng lên thư mục video trên Drive
for video_data in video_data_for_excel:
await upload_video_to_drive_audio(drive_service, video_data["path"], chat_id)
# --- BƯỚC DỌN DẸP CUỐI CÙNG ---
await send_telegram_message(chat_id, f"➡️ Bước 4/4: Dọn dẹp các file trung gian trên Drive...")
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)
# --- HỎI UPLOAD YOUTUBE ---
if await update_excel_for_youtube(video_data_for_excel):
user_data["videos_to_upload"] = video_data_for_excel
user_data["config"] = config
# SỬA LỖI: Thêm 2 dòng này để cập nhật trạng thái người dùng
user_data["state"] = AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE
user_sessions[str(chat_id)] = user_data # Cập nhật vào session chung
await send_telegram_message(chat_id, "Đã cập nhật Excel. Bạn có muốn upload lên YouTube không?", reply_markup=YOUTUBE_UPLOAD_CONFIRM_KEYBOARD)
else:
await send_telegram_message(chat_id, "Tạo video thành công nhưng lỗi cập nhật Excel.", reply_markup=AUDIO_MENU_KEYBOARD)
async def run_bulk_youtube_upload(chat_id: int, user_data: dict, account_number: int, config: dict) -> tuple[int, int]:
videos_to_upload = user_data.get("videos_to_upload", [])
if not videos_to_upload:
await send_telegram_message(chat_id, "Không tìm thấy danh sách video để upload.")
return 0, 0
await send_telegram_message(chat_id, f"Bắt đầu upload {len(videos_to_upload)} video lên tài khoản YouTube {account_number}...")
success_count, error_count = 0, 0
successful_uploads = [] # <-- Thêm dòng này
for i, video_data in enumerate(videos_to_upload):
await send_telegram_message(chat_id, f"Đang upload video {i + 1}/{len(videos_to_upload)}: `{video_data['title']}`...")
# === PHẦN SỬA ĐỔI QUAN TRỌNG ===
success = await upload_single_video_to_youtube_audio(
account_number=account_number,
video_path=video_data["path"],
video_title=video_data["title"],
chat_id=chat_id,
config=config
)
if success:
success_count += 1
successful_uploads.append(video_data) # <-- Thêm dòng này
else:
error_count += 1
# === KẾT THÚC SỬA ĐỔI ===
final_message = f"🎉 UPLOAD HOÀN TẤT 🎉\n\n- Thành công: {success_count} video.\n- Thất bại: {error_count} video."
await send_telegram_message(chat_id, final_message, reply_markup=AUDIO_MENU_KEYBOARD)
return successful_uploads # <-- Thay đổi ở đây
async def create_chapter_mp3(local_txt_path: str, output_mp3_path: str, voice: str) -> bool:
"""Tách logic tạo một file MP3 của chương ra hàm riêng."""
base_name = os.path.splitext(os.path.basename(local_txt_path))[0]
temp_dir = os.path.join(TEMP_PATH, f"temp_{base_name}")
os.makedirs(temp_dir, exist_ok=True)
is_ok, segments = True, []
try:
with open(local_txt_path, "r", encoding="utf-8") as f:
text = f.read()
if voice == 'ngochuyen':
# Giọng Ngọc Huyền: gửi toàn bộ text cho HuggingFace
if not await convert_text_to_mp3_hf_ngochuyen(text, output_mp3_path):
is_ok = False
# HF đã tạo file MP3 xong -> return luôn, không cần merge
return is_ok
chunks = split_text_into_chunks(text)
for j, chunk in enumerate(chunks):
seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
if voice == 'male':
if not await convert_text_to_mp3_edge(chunk, seg_path):
is_ok = False
break
else:
if not await convert_text_to_mp3_google(chunk, seg_path):
is_ok = False
break
segments.append(seg_path)
if is_ok and segments:
if not await merge_mp3_files_ffmpeg(segments, output_mp3_path):
is_ok = False
except Exception as e:
print(f"Lỗi trong quá trình tạo MP3 cho {base_name}: {e}")
is_ok = False
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
return is_ok
async def run_one_click_workflow(chat_id: int, user_data: dict):
"""
PHIÊN BẢN DEBUG: Thêm các lệnh print để tìm ra tại sao logic kiểm tra file lại sai.
"""
drive_service = None
try:
await send_telegram_message(chat_id, "🚀 **Bắt đầu Quy trình One Click (PHIÊN BẢN DEBUG)**\n\n`➡️ GĐ 0: Khởi tạo...`")
voice_choice = user_data.get("voice_choice", "female")
config = await read_audio_config_from_excel()
replacement_map = await _read_replacement_map_from_excel()
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds: raise Exception("Không thể xác thực với Google Drive.")
drive_service = build('drive', 'v3', credentials=drive_creds)
await send_telegram_message(chat_id, "🔎 Đang lấy danh sách file trên Google Drive...")
drive_files_map = {
"txt": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)},
"mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)},
"final_mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)},
"video": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}
}
# ==============================================================================
# === DÒNG DEBUG ĐẦU TIÊN: IN RA TOÀN BỘ DANH SÁCH FILE TXT ĐÃ TÌM THẤY =======
# ==============================================================================
print("\n" + "="*80)
print("DEBUG: DANH SÁCH FILE .TXT TÌM THẤY TRÊN DRIVE (KEYS CỦA DICTIONARY):")
print(drive_files_map["txt"].keys())
print(f"Tổng số file: {len(drive_files_map['txt'])}")
print("="*80 + "\n")
await send_telegram_message(chat_id, f"✅ Đã lấy được {len(drive_files_map['txt'])} file TXT từ Drive. Bắt đầu kiểm tra...")
# ==============================================================================
# === GIAI ĐOẠN 1: XỬ LÝ FILE TEXT (.txt) VỚI DEBUG ===========================
# ==============================================================================
await send_telegram_message(chat_id, "`➡️ GĐ 1/4: Xử lý file Text (.txt)...`")
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1])
all_links_data = [{'link': str(row[1]), 'chapter_number': int(row[0])} for _, row in df.loc[1:].iterrows() if pd.notna(row[1]) and pd.notna(row[0])]
links_to_keep_in_excel = []
for link_data in all_links_data:
expected_filename = f"{str(link_data['chapter_number']).zfill(4)}.txt"
local_filepath = os.path.join(AUDIO_TXT_FOLDER, expected_filename)
# ==============================================================================
# === DÒNG DEBUG THỨ HAI: IN RA TÊN FILE DỰ ĐỊNH NGAY TRƯỚC KHI SO SÁNH =====
# ==============================================================================
print(f"\n--- Đang kiểm tra chương {link_data['chapter_number']} ---")
print(f"DEBUG: Tên file dự định được tạo ra là: '{expected_filename}' (Kiểu dữ liệu: {type(expected_filename)})")
if expected_filename in drive_files_map["txt"]:
print(f"DEBUG >>> KẾT QUẢ: TÌM THẤY. File '{expected_filename}' đã có trong danh sách. Sẽ bỏ qua.")
if not os.path.exists(local_filepath):
await download_file_from_drive(drive_service, drive_files_map["txt"][expected_filename], local_filepath)
else:
print(f"DEBUG >>> KẾT QUẢ: KHÔNG TÌM THẤY. File '{expected_filename}' không có trong danh sách. Sẽ tiến hành cào dữ liệu.")
result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
if result:
title, body, _ = result
file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
final_content = _apply_replacements(file_content, replacement_map)
with open(local_filepath, 'w', encoding='utf-8') as f: f.write(final_content)
file_id = await upload_file_to_drive_folder(drive_service, local_filepath, DRIVE_AUDIO_TXT_FOLDER_ID)
if file_id: drive_files_map["txt"][expected_filename] = file_id
else:
links_to_keep_in_excel.append(link_data)
await rewrite_excel_links(links_to_keep_in_excel)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
# ==============================================================================
# === GIAI ĐOẠN 2, 3, 4: Code đầy đủ, tuân thủ logic kiểm tra và download ========
# ==============================================================================
# --- Giai đoạn 2: Xử lý MP3 ---
await send_telegram_message(chat_id, "`✅ GĐ 1`\n`➡️ GĐ 2/4: Tạo file Âm thanh (.mp3)...`")
for txt_filename in sorted(drive_files_map["txt"].keys()):
mp3_filename = f"{os.path.splitext(txt_filename)[0]}.mp3"
local_mp3_path = os.path.join(AUDIO_MP3_FOLDER, mp3_filename)
if mp3_filename in drive_files_map["mp3"]:
if not os.path.exists(local_mp3_path):
await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_filename], local_mp3_path)
else:
local_txt_path = os.path.join(AUDIO_TXT_FOLDER, txt_filename)
if not os.path.exists(local_txt_path):
await download_file_from_drive(drive_service, drive_files_map["txt"][txt_filename], local_txt_path)
is_ok = await create_chapter_mp3(local_txt_path, local_mp3_path, voice_choice)
if is_ok:
file_id = await upload_file_to_drive_folder(drive_service, local_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
if file_id: drive_files_map["mp3"][mp3_filename] = file_id
else:
raise Exception(f"Lỗi tạo MP3 cho {mp3_filename}")
df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
group_size = int(df_audio.iloc[0, 3])
all_chapter_mp3s = sorted(drive_files_map["mp3"].keys())
file_groups = [all_chapter_mp3s[i:i+group_size] for i in range(0, len(all_chapter_mp3s), group_size)]
for group in file_groups:
if not group: continue
final_name = f"{os.path.splitext(group[0])[0]}_{os.path.splitext(group[-1])[0]}.mp3"
local_final_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)
if final_name in drive_files_map["final_mp3"]:
if not os.path.exists(local_final_path):
await download_file_from_drive(drive_service, drive_files_map["final_mp3"][final_name], local_final_path)
else:
local_group_paths = []
for mp3_name in group:
local_path = os.path.join(AUDIO_MP3_FOLDER, mp3_name)
if not os.path.exists(local_path):
await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_name], local_path)
local_group_paths.append(local_path)
if await merge_mp3_files_ffmpeg(local_group_paths, local_final_path):
file_id = await upload_file_to_drive_folder(drive_service, local_final_path, DRIVE_AUDIO_FINAL_FOLDER_ID)
if file_id: drive_files_map["final_mp3"][final_name] = file_id
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)
# --- Giai đoạn 3: Xử lý Video ---
await send_telegram_message(chat_id, "`✅ GĐ 1, 2`\n`➡️ GĐ 3/4: Tạo file Video (.mp4)...`")
image_file_id, title_font_id, chap_font_id = config.get("image_file_id"), config.get("title_font_file_id"), config.get("chap_font_file_id")
if not all([image_file_id, title_font_id, chap_font_id]): raise Exception("Lỗi cấu hình: Thiếu File ID cho ảnh/font.")
config["image_path"] = os.path.join(TEMP_PATH, "background_image.jpg"); config["title_font_path"] = os.path.join(TEMP_PATH, "title_font.ttf"); config["chap_font_path"] = os.path.join(TEMP_PATH, "chap_font.ttf")
await download_file_from_drive(drive_service, image_file_id, config["image_path"]); await download_file_from_drive(drive_service, title_font_id, config["title_font_path"]); await download_file_from_drive(drive_service, chap_font_id, config["chap_font_path"])
successful_videos = []
for mp3_filename in sorted(drive_files_map["final_mp3"].keys()):
mp4_filename = f"{os.path.splitext(mp3_filename)[0]}.mp4"
local_video_path = os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename)
if mp4_filename in drive_files_map["video"]:
if not os.path.exists(local_video_path):
await download_file_from_drive(drive_service, drive_files_map["video"][mp4_filename], local_video_path)
else:
local_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
if not os.path.exists(local_mp3_path):
await download_file_from_drive(drive_service, drive_files_map["final_mp3"][mp3_filename], local_mp3_path)
generated_path = await generate_single_mp4_with_effect(local_mp3_path, config, chat_id)
if generated_path:
file_id = await upload_video_to_drive_audio(drive_service, generated_path, chat_id)
if file_id: drive_files_map["video"][mp4_filename] = file_id
successful_videos.append({"path": local_video_path, "base_name": os.path.splitext(mp4_filename)[0]})
if not successful_videos: raise Exception("Không tạo/tìm thấy được video nào trong GĐ 3.")
video_data_for_excel = []
for video in successful_videos:
chap_range = f"Tập {video['base_name']}"; chap_nums = video["base_name"].split("_")
if len(chap_nums) == 2:
try: start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1]); chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
except ValueError: chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
video_data_for_excel.append({"path": video["path"], "title": title})
await update_excel_for_youtube(video_data_for_excel)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
user_data["videos_to_upload"] = video_data_for_excel
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)
# --- Giai đoạn 4: Upload YouTube ---
upload_decision = user_data.get('one_click_upload_decision', False)
if upload_decision:
account_to_upload = user_data.get('one_click_account_number')
await send_telegram_message(chat_id, f"`✅ GĐ 1, 2, 3`\n`➡️ GĐ 4/4: Upload lên YouTube tài khoản {account_to_upload}...`")
for video_data in video_data_for_excel:
if not os.path.exists(video_data['path']):
video_filename = os.path.basename(video_data['path'])
video_id = drive_files_map["video"].get(video_filename)
if video_id: await download_file_from_drive(drive_service, video_id, video_data['path'])
successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_to_upload, config)
if successfully_uploaded_videos:
await send_telegram_message(chat_id, f"🗑️ Dọn dẹp {len(successfully_uploaded_videos)} video đã upload thành công trên Drive...")
for uploaded_video in successfully_uploaded_videos:
filename = os.path.basename(uploaded_video['path'])
if filename in drive_files_map["video"]: await delete_file_from_drive(drive_service, drive_files_map["video"][filename])
else:
await send_telegram_message(chat_id, "🎉 **QUY TRÌNH HOÀN TẤT!**\n\nĐã tạo video thành công. Không thực hiện upload YouTube theo yêu cầu.", reply_markup=AUDIO_MENU_KEYBOARD)
except Exception as e:
error_traceback = traceback.format_exc()
print(f"❌ LỖI NGHIÊM TRỌNG trong One Click:\n{error_traceback}")
await send_telegram_message(chat_id, f"❌ **Đã xảy ra lỗi nghiêm trọng:**\n\n<pre>{e}</pre>", reply_markup=AUDIO_MENU_KEYBOARD)
finally:
await send_telegram_message(chat_id, "⚙️ Dọn dẹp file tạm cục bộ trên server...")
for path in [AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, TEMP_PATH]:
shutil.rmtree(path, ignore_errors=True)
os.makedirs(path, exist_ok=True)
await send_telegram_message(chat_id, "✅ Dọn dẹp cục bộ hoàn tất.")
async def run_one_click_workflow2(chat_id: int, user_data: dict):
"""
Quy trình One Click AN TOÀN & CÓ KHẢ NĂNG PHỤC HỒI.
- Trước khi tạo mỗi file (TXT/MP3/MP4), kiểm tra xem đã có trên Drive chưa → skip nếu có.
- Nếu bị lỗi giữa chừng, chỉ cần xóa file lỗi cuối cùng rồi chạy lại.
- Hệ thống sẽ tự động skip các file đã hoàn thành và tiếp tục từ file bị lỗi.
"""
drive_service = None
try:
# --- KHỞI TẠO ---
voice_choice = user_data.get("voice_choice", "female")
config = await read_audio_config_from_excel()
replacement_map = await _read_replacement_map_from_excel()
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive. Dừng quy trình.")
return
drive_service = build('drive', 'v3', credentials=drive_creds)
# ==============================================================================
# === BƯỚC 0: QUÉT TOÀN BỘ TRẠNG THÁI FILE TRÊN DRIVE (1 LẦN DUY NHẤT) ========
# ==============================================================================
await send_telegram_message(chat_id, "🔎 Đang quét trạng thái file trên Google Drive...")
drive_files_map = {
"txt": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)},
"mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)},
"final_mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)},
"video": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}
}
await send_telegram_message(chat_id,
f"📊 **Trạng thái hiện tại trên Drive:**\n"
f"- TXT: **{len(drive_files_map['txt'])}** file\n"
f"- MP3 chương: **{len(drive_files_map['mp3'])}** file\n"
f"- MP3 nối: **{len(drive_files_map['final_mp3'])}** file\n"
f"- Video: **{len(drive_files_map['video'])}** file"
)
# ==============================================================================
# === GIAI ĐOẠN 1: GET FILE (.txt) - SKIP NẾU ĐÃ CÓ TRÊN DRIVE ===============
# ==============================================================================
await send_telegram_message(chat_id, "🚀 **Quy trình One Click (Có phục hồi)**\n\n`➡️ Bước 1/4: Get File...`")
# Đọc link từ Excel
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1])
all_links_data = []
for _, row in df.loc[1:].iterrows():
chap_num = int(row.get(0)) if pd.notna(row.get(0)) else None
link = str(row.get(1)) if pd.notna(row.get(1)) else None
if link and chap_num is not None:
all_links_data.append({'link': link, 'chapter_number': chap_num})
# Nếu không có link trong Excel VÀ cũng không có TXT trên Drive → không có gì để làm
if not all_links_data and not drive_files_map["txt"]:
await send_telegram_message(chat_id, "❌ Không tìm thấy link trong Excel và không có file TXT trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD)
return
os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
txt_new, txt_skip, links_error = 0, 0, []
for link_data in all_links_data:
expected_filename = f"{str(link_data['chapter_number']).zfill(4)}.txt"
local_filepath = os.path.join(AUDIO_TXT_FOLDER, expected_filename)
# ✅ KIỂM TRA: File TXT đã có trên Drive chưa?
if expected_filename in drive_files_map["txt"]:
txt_skip += 1
# Download về local nếu cần cho bước sau
if not os.path.exists(local_filepath):
await download_file_from_drive(drive_service, drive_files_map["txt"][expected_filename], local_filepath)
continue
# Chưa có → cào dữ liệu và tạo file
result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
if result:
title, body, _ = result
file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
final_content = _apply_replacements(file_content, replacement_map)
with open(local_filepath, 'w', encoding='utf-8') as f:
f.write(final_content)
file_id = await upload_file_to_drive_folder(drive_service, local_filepath, DRIVE_AUDIO_TXT_FOLDER_ID)
if file_id:
drive_files_map["txt"][expected_filename] = file_id
txt_new += 1
else:
links_error.append(link_data)
# Cập nhật Excel: chỉ giữ lại các link lỗi
await rewrite_excel_links(links_error)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
if links_error:
await send_telegram_message(chat_id, f"⚠️ Có {len(links_error)} link lỗi (đã lưu lại trong Excel).")
await send_telegram_message(chat_id,
f"✅ **GĐ 1 hoàn tất:** Mới: **{txt_new}** | Skip: **{txt_skip}** | Lỗi: **{len(links_error)}**")
# ==============================================================================
# === GIAI ĐOẠN 2: GEN MP3 - SKIP NẾU ĐÃ CÓ TRÊN DRIVE =======================
# ==============================================================================
await send_telegram_message(chat_id, "`➡️ Bước 2/4: Tạo MP3...`")
os.makedirs(AUDIO_MP3_FOLDER, exist_ok=True)
mp3_new, mp3_skip = 0, 0
for txt_filename in sorted(drive_files_map["txt"].keys()):
base_name = os.path.splitext(txt_filename)[0]
mp3_filename = f"{base_name}.mp3"
local_mp3_path = os.path.join(AUDIO_MP3_FOLDER, mp3_filename)
# ✅ KIỂM TRA: File MP3 chương đã có trên Drive chưa?
if mp3_filename in drive_files_map["mp3"]:
mp3_skip += 1
if not os.path.exists(local_mp3_path):
await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_filename], local_mp3_path)
continue
# Chưa có → tạo mới
local_txt_path = os.path.join(AUDIO_TXT_FOLDER, txt_filename)
if not os.path.exists(local_txt_path):
await download_file_from_drive(drive_service, drive_files_map["txt"][txt_filename], local_txt_path)
is_ok = await create_chapter_mp3(local_txt_path, local_mp3_path, voice_choice)
if is_ok:
file_id = await upload_file_to_drive_folder(drive_service, local_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
if file_id:
drive_files_map["mp3"][mp3_filename] = file_id
mp3_new += 1
else:
await send_telegram_message(chat_id,
f"❌ Lỗi tạo MP3 cho `{mp3_filename}`. Dừng quy trình.\n"
f"💡 **Để tiếp tục:** Xóa file lỗi trên Drive (nếu có) rồi chạy lại One Click.",
reply_markup=AUDIO_MENU_KEYBOARD)
return
await send_telegram_message(chat_id,
f"✅ **MP3 chương:** Mới: **{mp3_new}** | Skip: **{mp3_skip}**")
# --- Nối MP3 chương thành các file MP3 lớn ---
df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
group_size = int(df_audio.iloc[0, 3])
all_chapter_mp3s = sorted(drive_files_map["mp3"].keys())
file_groups = [all_chapter_mp3s[i:i+group_size] for i in range(0, len(all_chapter_mp3s), group_size)]
os.makedirs(AUDIO_FINAL_FOLDER, exist_ok=True)
final_new, final_skip = 0, 0
for group in file_groups:
if not group: continue
final_name = f"{os.path.splitext(group[0])[0]}_{os.path.splitext(group[-1])[0]}.mp3"
local_final_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)
# ✅ KIỂM TRA: File MP3 nối đã có trên Drive chưa?
if final_name in drive_files_map["final_mp3"]:
final_skip += 1
if not os.path.exists(local_final_path):
await download_file_from_drive(drive_service, drive_files_map["final_mp3"][final_name], local_final_path)
continue
# Chưa có → nối
local_group_paths = []
for mp3_name in group:
local_path = os.path.join(AUDIO_MP3_FOLDER, mp3_name)
if not os.path.exists(local_path):
await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_name], local_path)
local_group_paths.append(local_path)
if await merge_mp3_files_ffmpeg(local_group_paths, local_final_path):
file_id = await upload_file_to_drive_folder(drive_service, local_final_path, DRIVE_AUDIO_FINAL_FOLDER_ID)
if file_id:
drive_files_map["final_mp3"][final_name] = file_id
final_new += 1
await send_telegram_message(chat_id,
f"✅ **MP3 nối:** Mới: **{final_new}** | Skip: **{final_skip}**")
# Dọn TXT trên Drive (đã xong, không cần nữa)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)
# ==============================================================================
# === GIAI ĐOẠN 3: GEN MP4 - SKIP NẾU ĐÃ CÓ TRÊN DRIVE =======================
# ==============================================================================
await send_telegram_message(chat_id, "`✅ GĐ 1, 2`\n`➡️ Bước 3/4: Tạo Video (.mp4)...`")
# Tải tài nguyên (ảnh nền, font chữ) từ Drive
image_file_id = config.get("image_file_id")
title_font_id = config.get("title_font_file_id")
chap_font_id = config.get("chap_font_file_id")
if not all([image_file_id, title_font_id, chap_font_id]):
await send_telegram_message(chat_id, "❌ Lỗi cấu hình: Thiếu File ID cho ảnh/font trong Excel.", reply_markup=AUDIO_MENU_KEYBOARD)
return
config["image_path"] = os.path.join(TEMP_PATH, "background_image.jpg")
config["title_font_path"] = os.path.join(TEMP_PATH, "title_font.ttf")
config["chap_font_path"] = os.path.join(TEMP_PATH, "chap_font.ttf")
await download_file_from_drive(drive_service, image_file_id, config["image_path"])
await download_file_from_drive(drive_service, title_font_id, config["title_font_path"])
await download_file_from_drive(drive_service, chap_font_id, config["chap_font_path"])
successful_videos = []
video_new, video_skip = 0, 0
for mp3_filename in sorted(drive_files_map["final_mp3"].keys()):
mp4_filename = f"{os.path.splitext(mp3_filename)[0]}.mp4"
local_video_path = os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename)
# ✅ KIỂM TRA: File video đã có trên Drive chưa?
if mp4_filename in drive_files_map["video"]:
video_skip += 1
if not os.path.exists(local_video_path):
await download_file_from_drive(drive_service, drive_files_map["video"][mp4_filename], local_video_path)
else:
# Chưa có → tạo mới
local_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
if not os.path.exists(local_mp3_path):
await download_file_from_drive(drive_service, drive_files_map["final_mp3"][mp3_filename], local_mp3_path)
generated_path = await generate_single_mp4_with_effect(local_mp3_path, config, chat_id)
if generated_path:
file_id = await upload_video_to_drive_audio(drive_service, generated_path, chat_id)
if file_id:
drive_files_map["video"][mp4_filename] = file_id
video_new += 1
successful_videos.append({"path": local_video_path, "base_name": os.path.splitext(mp4_filename)[0]})
await send_telegram_message(chat_id,
f"✅ **Video:** Mới: **{video_new}** | Skip: **{video_skip}**")
if not successful_videos:
await send_telegram_message(chat_id, "❌ Không tạo/tìm thấy được video nào.", reply_markup=AUDIO_MENU_KEYBOARD)
return
# Chuẩn bị dữ liệu cho Excel & YouTube
video_data_for_excel = []
for video in successful_videos:
chap_range = f"Tập {video['base_name']}"
chap_nums = video["base_name"].split("_")
if len(chap_nums) == 2:
try:
start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1])
chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
except ValueError:
chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
video_data_for_excel.append({"path": video["path"], "title": title})
await update_excel_for_youtube(video_data_for_excel)
user_data["videos_to_upload"] = video_data_for_excel
# Dọn MP3 trên Drive (đã có video rồi, không cần nữa)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)
# ==============================================================================
# === GIAI ĐOẠN 4: UPLOAD YOUTUBE & DỌN DẸP VIDEO TRÊN DRIVE ===================
# ==============================================================================
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
upload_decision = user_data.get('one_click_upload_decision', False)
if upload_decision:
account_to_upload = user_data.get('one_click_account_number')
await send_telegram_message(chat_id, f"`✅ GĐ 1, 2, 3`\n`➡️ Bước 4/4: Upload lên YouTube tài khoản {account_to_upload}...`")
# Đảm bảo video tồn tại trên local trước khi upload
for video_data in video_data_for_excel:
if not os.path.exists(video_data['path']):
video_filename = os.path.basename(video_data['path'])
video_id = drive_files_map["video"].get(video_filename)
if video_id:
await download_file_from_drive(drive_service, video_id, video_data['path'])
successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_to_upload, config)
if successfully_uploaded_videos:
await send_telegram_message(chat_id, f"🗑️ Dọn dẹp {len(successfully_uploaded_videos)} video đã upload trên Drive...")
for uploaded_video in successfully_uploaded_videos:
filename = os.path.basename(uploaded_video['path'])
if filename in drive_files_map["video"]:
await delete_file_from_drive(drive_service, drive_files_map["video"][filename])
else:
await send_telegram_message(chat_id, "🎉 **QUY TRÌNH HOÀN TẤT!**\n\nĐã tạo video thành công. Không upload YouTube theo yêu cầu.", reply_markup=AUDIO_MENU_KEYBOARD)
except Exception as e:
error_traceback = traceback.format_exc()
print(f"❌ LỖI NGHIÊM TRỌNG trong One Click 2:\n{error_traceback}")
await send_telegram_message(chat_id, f"❌ **Đã xảy ra lỗi nghiêm trọng:**\n\n`{e}`\n\n💡 **Để tiếp tục:** Xóa file lỗi (nếu có) trên Drive rồi chạy lại One Click.", reply_markup=AUDIO_MENU_KEYBOARD)
finally:
await send_telegram_message(chat_id, "⚙️ Dọn dẹp file tạm cục bộ...")
for path in [AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, TEMP_PATH]:
shutil.rmtree(path, ignore_errors=True)
os.makedirs(path, exist_ok=True)
await send_telegram_message(chat_id, "✅ Dọn dẹp cục bộ hoàn tất.")
async def start_recovery_upload_process(chat_id: int, user_data: dict, account_number: int):
"""
Tải video từ Drive về, đọc Excel để lấy tiêu đề, và bắt đầu upload hàng loạt.
"""
video_files_to_recover = user_data.get("recovery_video_files", [])
if not video_files_to_recover:
await send_telegram_message(chat_id, "Lỗi: Không tìm thấy danh sách video cần phục hồi.")
return
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds: return
drive_service = build('drive', 'v3', credentials=drive_creds)
try:
# 1. Tải các video từ Drive về thư mục tạm cục bộ
await send_telegram_message(chat_id, f"Bắt đầu tải {len(video_files_to_recover)} video từ Drive về server...")
os.makedirs(AUDIO_VIDEO_FOLDER, exist_ok=True)
local_video_paths = []
for file_info in video_files_to_recover:
local_path = os.path.join(AUDIO_VIDEO_FOLDER, file_info['name'])
await download_file_from_drive(drive_service, file_info['id'], local_path)
local_video_paths.append(local_path)
# 2. Đọc file Excel để lấy tiêu đề (logic này giữ nguyên)
await send_telegram_message(chat_id, "Đang đọc file Excel để lấy tiêu đề video...")
df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
path_to_title_map = {}
for index, row in df.iterrows():
if index == 0: continue
path_cell, title_cell = row.get(8), row.get(9)
if pd.notna(path_cell) and pd.notna(title_cell):
path_to_title_map[os.path.basename(str(path_cell))] = str(title_cell)
# 3. Xây dựng lại danh sách và gọi hàm upload (logic này giữ nguyên)
videos_to_upload = []
for full_path in local_video_paths:
filename = os.path.basename(full_path)
title = path_to_title_map.get(filename, os.path.splitext(filename)[0])
videos_to_upload.append({"path": full_path, "title": title})
config = await read_audio_config_from_excel()
user_data['videos_to_upload'] = videos_to_upload
# Tạo một bản đồ tra cứu từ tên file -> ID trên Drive
name_to_id_map = {file_info['name']: file_info['id'] for file_info in video_files_to_recover}
# Gọi hàm upload và nhận lại danh sách các video đã thành công
successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_number, config)
# === PHẦN THÊM MỚI: DỌN DẸP FILE TRÊN DRIVE ===
if successfully_uploaded_videos:
await send_telegram_message(chat_id, f"🗑️ Bắt đầu dọn dẹp {len(successfully_uploaded_videos)} file MP4 đã upload thành công trên Google Drive...")
deleted_count = 0
for video_info in successfully_uploaded_videos:
filename = os.path.basename(video_info['path'])
file_id_to_delete = name_to_id_map.get(filename)
if file_id_to_delete:
# Cần một hàm delete_file_from_drive, hãy đảm bảo bạn có nó
if await delete_file_from_drive(drive_service, file_id_to_delete):
deleted_count += 1
await send_telegram_message(chat_id, f"✅ Đã dọn dẹp xong {deleted_count} file.")
# === KẾT THÚC PHẦN THÊM MỚI ===
except Exception as e:
print(f"Lỗi nghiêm trọng trong quá trình upload phục hồi: {e}")
await send_telegram_message(chat_id, f"❌ Đã xảy ra lỗi nghiêm trọng: {e}")
async def delete_file_from_drive(drive_service, file_id: str) -> bool:
"""Xóa một file trên Drive bằng ID."""
try:
await asyncio.to_thread(drive_service.files().delete(fileId=file_id).execute)
print(f" -> Đã xóa file trên Drive: {file_id}")
return True
except Exception as e:
print(f"❌ Lỗi khi xóa file trên Drive '{file_id}': {e}")
return False
# ==============================================================================
# --- PHẦN KHỞI ĐỘNG VÀ XỬ LÝ WEBHOOK CỦA FASTAPI ---
# ==============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Hàm chạy một lần khi bot khởi động."""
print("🚀 Bắt đầu quá trình khởi tạo bot qua lifespan...")
global GOOGLE_TTS_API_KEY
# 1. Tạo các thư mục làm việc cục bộ
for path in [BASE_DATA_DIR, AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, YTB_TOKEN_SAVE_PATH, TEMP_PATH]:
os.makedirs(path, exist_ok=True)
print("✅ Đã tạo các thư mục làm việc cục bộ.")
# 2. Giải mã và lưu token chính của Drive từ Secret
base64_pickle_string = os.getenv("PICKLE_TOKEN_B64")
if not base64_pickle_string:
print("❌ LỖI NGHIÊM TRỌNG: Secret 'PICKLE_TOKEN_B64' chưa được thiết lập.")
yield; return # Thoát sớm
try:
pickle_binary_data = base64.b64decode(base64_pickle_string)
working_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, "driver_main.pickle")
with open(working_token_path, "wb") as f: f.write(pickle_binary_data)
print(f"✅ Đã tạo file token chính của Drive tại: {working_token_path}")
except Exception as e:
print(f"❌ Lỗi khi giải mã và tạo file token chính: {e}")
yield; return
# 3. Tải file Excel và đọc các cấu hình cần thiết
try:
ADMIN_CHAT_ID = 6685326330 # ID admin để gửi thông báo lỗi nếu cần
credentials = await get_drive_credentials(ADMIN_CHAT_ID)
if not credentials: raise Exception("Không thể lấy credentials của Drive.")
drive_service = build('drive', 'v3', credentials=credentials)
print("✅ Đã kết nối thành công với Google Drive API.")
await download_file_from_drive(drive_service, DRIVE_EXCEL_FILE_ID, WORKING_EXCEL_PATH)
# Đọc Google TTS API Key từ Excel (ô D2 sheet Input)
df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
key_value = df_input.iloc[1, 3]
if pd.notna(key_value) and str(key_value).strip():
GOOGLE_TTS_API_KEY = str(key_value).strip()
print("✅ Đã đọc thành công Google TTS API Key.")
else:
print("❌ CẢNH BÁO: Google TTS API Key (ô D2, sheet 'Input') bị trống.")
except Exception as e:
print(f"❌ LỖI nghiêm trọng trong quá trình khởi tạo: {e}")
print("✅ Bot đã sẵn sàng nhận yêu cầu.")
yield
print("🔌 Bot đang tắt...")
app = FastAPI(lifespan=lifespan)
@app.post("/webhook")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
"""Xử lý Telegram updates được Google Apps Script chuyển tiếp."""
try:
update_json = await request.json()
update_id = update_json.get("update_id")
if update_id in processed_update_ids:
return {"status": "ok, duplicate ignored"}
processed_update_ids.append(update_id)
except Exception as e:
print(f"!!! Lỗi parsing request: {e}")
return {"status": "error"}
chat_id, user_id, data, text = None, None, None, None
user_data = {}
if "callback_query" in update_json:
query = update_json["callback_query"]
chat_id = query["message"]["chat"]["id"]
user_id = query["from"]["id"]
data = query["data"]
user_data = user_sessions.get(str(user_id), {}) # Lấy state hiện tại của user
state = user_data.get("state")
# --- LUỒNG XỬ LÝ NÚT BẤM ---
if data == "audio_get_link":
user_data["is_first_scrape"] = True
user_data["state"] = AWAITING_EPISODE_COUNT_STATE
await send_telegram_message(chat_id, "Bước 1: Bạn muốn **nối** bao nhiêu chương MP3 thành 1 file?", EPISODE_COUNT_KEYBOARD)
# <<< BLOCK CODE MỚI BẮT ĐẦU: Xử lý luồng cho nút "Truy Vết"
elif data == "audio_trace":
user_data["state"] = AWAITING_TRACE_PAGE_COUNT_STATE
await send_telegram_message(chat_id, "Bạn muốn **truy vết** dữ liệu từ bao nhiêu trang?", TRACE_PAGE_COUNT_KEYBOARD)
elif state == AWAITING_TRACE_PAGE_COUNT_STATE and data.startswith("trace_page_count_"):
user_data["pages_to_trace"] = int(data.replace("trace_page_count_", ""))
user_data["state"] = AWAITING_TRACE_URL_STATE
await send_telegram_message(chat_id, f"Ok, sẽ truy vết từ {user_data['pages_to_trace']} trang.\n\nVui lòng gửi đường dẫn trang truyện (trang đầu tiên):")
# <<< BLOCK CODE MỚI KẾT THÚC
elif state == AWAITING_EPISODE_COUNT_STATE and data.startswith("ep_count_"):
user_data["merge_count"] = int(data.replace("ep_count_", ""))
user_data["state"] = AWAITING_PAGE_COUNT_STATE
await send_telegram_message(chat_id, f"Đã lưu số lượng nối file là {user_data['merge_count']}.\n\nBước 2: Bạn muốn **lấy dữ liệu** từ bao nhiêu trang?", PAGE_COUNT_KEYBOARD)
elif state == AWAITING_PAGE_COUNT_STATE and data.startswith("page_count_"):
user_data["pages_to_scrape"] = int(data.replace("page_count_", ""))
user_data["state"] = AWAITING_URL_FOR_SCRAPING_STATE
await send_telegram_message(chat_id, f"Ok, sẽ lấy dữ liệu từ {user_data['pages_to_scrape']} trang.\n\nBước 3: Vui lòng gửi đường dẫn trang truyện (trang đầu tiên):")
elif data == "audio_get_file":
background_tasks.add_task(process_and_generate_text_files, chat_id)
await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Get File'. Quy trình đang chạy trong nền...")
# <<< CHỈNH SỬA: Thêm bước hỏi giọng đọc cho Gen MP3
elif data == "audio_gen_mp3":
user_data["state"] = AWAITING_GEN_MP3_VOICE_CHOICE_STATE
await send_telegram_message(chat_id, "Bạn muốn dùng giọng đọc nào?", reply_markup=VOICE_CHOICE_KEYBOARD_GEN_MP3)
# <<< MỚI: Xử lý lựa chọn giọng đọc cho Gen MP3
elif state == AWAITING_GEN_MP3_VOICE_CHOICE_STATE:
if data == "gen_mp3_voice_male":
user_data["voice_choice"] = "male"
elif data == "gen_mp3_voice_ngochuyen":
user_data["voice_choice"] = "ngochuyen"
else:
user_data["voice_choice"] = "female"
user_data["state"] = AUDIO_MENU_STATE # Reset state
background_tasks.add_task(run_full_mp3_generation_process, chat_id, user_data)
await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Gen MP3'. Quy trình đang chạy trong nền...")
elif data == "audio_gen_mp4":
background_tasks.add_task(process_and_generate_mp4_files, chat_id, user_data)
await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Gen MP4'. Quy trình đang chạy trong nền...")
elif data == "audio_one_click":
user_data["state"] = AWAITING_ONE_CLICK_VOICE_CHOICE_STATE
await send_telegram_message(chat_id, "Bạn muốn dùng giọng đọc nào cho quy trình One Click?", reply_markup=VOICE_CHOICE_KEYBOARD_ONE_CLICK)
# <<< MỚI: Xử lý lựa chọn giọng đọc cho One Click và chuyển sang bước tiếp theo
elif state == AWAITING_ONE_CLICK_VOICE_CHOICE_STATE:
if data == "one_click_voice_male":
user_data["voice_choice"] = "male"
elif data == "one_click_voice_ngochuyen":
user_data["voice_choice"] = "ngochuyen"
else:
user_data["voice_choice"] = "female"
user_data["state"] = AWAITING_ONE_CLICK_YT_CONFIRM_STATE
await send_telegram_message(chat_id, "Tiếp theo, sau khi quy trình hoàn tất, bạn có muốn tự động upload video lên YouTube không?", ONE_CLICK_YT_CONFIRM_KEYBOARD)
elif state == AWAITING_ONE_CLICK_YT_CONFIRM_STATE:
if data == "one_click_yt_yes":
user_data['one_click_upload_decision'] = True
user_data["state"] = AWAITING_ONE_CLICK_YT_ACCOUNT_STATE
await send_telegram_message(chat_id, "Vui lòng chọn tài khoản YouTube sẽ dùng để upload:", ONE_CLICK_YT_ACCOUNT_KEYBOARD)
else: # one_click_yt_no
user_data['one_click_upload_decision'] = False
await send_telegram_message(chat_id, "Đã hiểu. Bắt đầu quy trình tạo video mà không upload...")
background_tasks.add_task(run_one_click_workflow, chat_id, user_data)
elif state == AWAITING_ONE_CLICK_YT_ACCOUNT_STATE and data.startswith("one_click_account_"):
account_num = int(data.replace("one_click_account_", ""))
user_data['one_click_account_number'] = account_num
# Đặt lại trạng thái NGAY LẬP TỨC để tránh bị gọi lại
user_data["state"] = AUDIO_MENU_STATE
await send_telegram_message(chat_id, f"Ok. Sẽ tự động upload lên tài khoản {account_num} sau khi xong. Bắt đầu quy trình...")
background_tasks.add_task(run_one_click_workflow, chat_id, user_data)
elif state == AWAITING_ADD_MORE_URL_CONFIRMATION_STATE:
if data == "add_more_yes":
user_data["state"] = AWAITING_URL_FOR_SCRAPING_STATE
await send_telegram_message(chat_id, "Ok, vui lòng gửi đường dẫn trang truyện tiếp theo:")
else:
user_data["state"] = AUDIO_MENU_STATE
await send_telegram_message(chat_id, "✅ Đã lấy link xong. Trở về menu Audio.", AUDIO_MENU_KEYBOARD)
elif state == AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE:
if data == "yt_upload_yes":
user_data["state"] = AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE
await send_telegram_message(chat_id, "Vui lòng chọn tài khoản YouTube để upload:", YOUTUBE_ACCOUNT_KEYBOARD_AUDIO)
else:
user_data["state"] = AUDIO_MENU_STATE
await send_telegram_message(chat_id, "Đã hiểu. Trở về menu Audio.", AUDIO_MENU_KEYBOARD)
elif state == AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE and data.startswith("yt_account_"):
account_num = int(data.replace("yt_account_", ""))
config = user_data.get("config") # Lấy config đã lưu
# Kiểm tra xem config có tồn tại không
if not config:
await send_telegram_message(chat_id, "Lỗi: Mất phiên làm việc. Vui lòng thử lại từ bước Gen MP4.")
else:
user_data["state"] = AUDIO_MENU_STATE # Reset state sau khi đã nhận lệnh
await send_telegram_message(chat_id, f"Đã chọn tài khoản {account_num}. Bắt đầu upload hàng loạt...")
background_tasks.add_task(run_bulk_youtube_upload, chat_id, user_data, account_num, config)
elif data == "audio_recovery_upload":
await send_telegram_message(chat_id, "🔎 Đang kiểm tra video trên Google Drive...")
drive_creds = await get_drive_credentials(chat_id)
if not drive_creds:
await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
return
drive_service = build('drive', 'v3', credentials=drive_creds)
# Lấy danh sách video từ thư mục output trên Drive
video_files_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)
if not video_files_on_drive:
await send_telegram_message(chat_id, "✅ Không có video nào trên Google Drive cần upload.")
user_data["state"] = AUDIO_MENU_STATE
else:
# Lưu lại danh sách file tìm thấy để dùng ở bước sau
user_data["recovery_video_files"] = video_files_on_drive
await send_telegram_message(chat_id, f"🔍 Tìm thấy {len(video_files_on_drive)} video. Bạn muốn upload lên tài khoản YouTube nào?", reply_markup=RECOVERY_YT_ACCOUNT_KEYBOARD)
user_data["state"] = AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE
elif state == AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE and data.startswith("recovery_yt_acc_"):
# Khi người dùng chọn một tài khoản để upload phục hồi
account_num = int(data.replace("recovery_yt_acc_", ""))
user_data["state"] = AUDIO_MENU_STATE # Reset state
await send_telegram_message(chat_id, f"✅ Đã nhận lệnh. Bắt đầu quá trình upload phục hồi cho tài khoản {account_num}...")
background_tasks.add_task(start_recovery_upload_process, chat_id, user_data, account_num)
# === BLOCK CODE MỚI KẾT THÚC ===
# Lưu lại trạng thái của người dùng sau mỗi lần tương tác
if user_id:
user_data = user_sessions.get(str(user_id), {})
elif "message" in update_json:
message = update_json["message"]
chat_id = message["chat"]["id"]
user_id = message["from"]["id"]
text = message.get("text", "").strip()
user_data = user_sessions.get(str(user_id), {})
state = user_data.get("state")
if text == "/audio": # Lệnh để mở menu audio
user_data["state"] = AUDIO_MENU_STATE
await send_telegram_message(chat_id, "🎧 Chức năng Gen Audio. Vui lòng chọn:", AUDIO_MENU_KEYBOARD)
elif state == AWAITING_URL_FOR_SCRAPING_STATE:
if "http" not in text.lower(): # <<< THAY ĐỔI
await send_telegram_message(chat_id, "❌ URL không hợp lệ. Vui lòng gửi lại:")
else:
pages_to_scrape = user_data.get("pages_to_scrape", 1)
merge_count = user_data.get("merge_count", 20)
is_first = user_data.get("is_first_scrape", True)
await send_telegram_message(chat_id, f"🔎 Đang lấy dữ liệu từ {pages_to_scrape} trang...")
result_dict = await scrape_website_chapter_list(text, pages_to_scrape) # <<< THAY ĐỔI
if 'error' in result_dict:
await send_telegram_message(chat_id, f"❌ Không lấy được dữ liệu. Lý do: {result_dict.get('error')}")
else:
data = result_dict.get('data', [])
if not data:
await send_telegram_message(chat_id, "Không lấy được chương nào từ URL bạn gửi.")
elif await update_audio_sheet(data, is_first):
# Cập nhật số lượng nối file vào D1
def update_merge_count(book):
ws = book["Audio"]
ws.cell(row=1, column=4, value=str(merge_count))
await modify_excel_sheet(update_merge_count)
# Upload lại file Excel lên Drive
drive_creds = await get_drive_credentials(chat_id)
if drive_creds:
drive_service = build('drive', 'v3', credentials=drive_creds)
await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
user_data["is_first_scrape"] = False
user_data["state"] = AWAITING_ADD_MORE_URL_CONFIRMATION_STATE
await send_telegram_message(chat_id, f"✅ Đã lấy và cập nhật thành công {len(data)} chương. Bạn có muốn thêm link từ truyện khác không?", ADD_MORE_KEYBOARD)
else:
user_data["state"] = AUDIO_MENU_STATE
await send_telegram_message(chat_id, "Lỗi khi cập nhật file Excel.", AUDIO_MENU_KEYBOARD)
elif state == AWAITING_TRACE_URL_STATE:
if "http" not in text.lower():
await send_telegram_message(chat_id, "❌ URL không hợp lệ. Vui lòng gửi lại:")
else:
pages_to_trace = user_data.get("pages_to_trace", 1)
# Reset trạng thái ngay lập tức để tránh xử lý lại
user_data["state"] = AUDIO_MENU_STATE
# Chạy tác vụ nền để không block bot
background_tasks.add_task(run_trace_workflow, chat_id, text, pages_to_trace)
await send_telegram_message(chat_id, "✅ Đã nhận yêu cầu. Bắt đầu chạy quy trình Truy Vết trong nền...")
# <<< BLOCK CODE MỚI KẾT THÚC
else:
await send_telegram_message(chat_id, "Lệnh không hợp lệ. Vui lòng dùng lệnh /audio để bắt đầu hoặc sử dụng các nút bấm.")
# Lưu lại trạng thái của người dùng
if user_id:
user_sessions[str(user_id)] = user_data
return {"status": "ok"}
@app.get("/")
def read_root():
return {"message": "Audio Bot handler is running."}
import nest_asyncio
nest_asyncio.apply()
import asyncio
import base64
import os
import re
import shutil
import subprocess
import pickle
import random
import traceback
import time
import tempfile
import json
import io
from collections import deque
import httpx
import socket
import aiodns
import edge_tts
from gradio_client import Client # Import cho TTS HuggingFace (giọng Ngọc Huyền)
import pandas as pd
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook
# --- CÁC THƯ VIỆN FRAMEWORK ---
from fastapi import FastAPI, Request, BackgroundTasks
from contextlib import asynccontextmanager
from scrapers import get_scraper # <<< DÒNG MỚI
# --- CÁC THƯ VIỆN GOOGLE API ---
from google.auth.transport.requests import Request as GoogleAuthRequest
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.oauth2.credentials import Credentials
# --- BỘ ĐỆM CHỐNG LẶP REQUEST TỪ TELEGRAM ---
processed_update_ids = deque(maxlen=500)
# --- DICTIONARY LƯU TRẠNG THÁI NGƯỜI DÙNG ---
user_sessions = {}
from trace_handler import process_content_for_trace # <<< DÒNG MỚI: Import hàm logic từ file mới
# ==============================================================================
# --- PHẦN CẤU HÌNH CẦN THAY ĐỔI CHO MÔI TRƯỜNG HUGGING FACE ---
# ==============================================================================
# --- ĐƯỜNG DẪN TRÊN HỆ THỐNG TỆP TẠM THỜI CỦA HUGGING FACE ---
# Chúng ta sẽ sử dụng thư mục /tmp/ để lưu trữ file tạm thời.
BASE_DATA_DIR = "/tmp/audio_bot_data"
WORKING_EXCEL_PATH = os.path.join(BASE_DATA_DIR, "Input.xlsx")
AUDIO_TXT_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Input/")
AUDIO_MP3_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Sound/")
AUDIO_FINAL_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Final/")
AUDIO_VIDEO_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Video/")
YTB_TOKEN_SAVE_PATH = os.path.join(BASE_DATA_DIR, "YTB/Account/") # Thư mục chứa token sau khi tải từ Drive
TEMP_PATH = os.path.join(BASE_DATA_DIR, "Temp/")
# --- ID CỦA CÁC FILE VÀ THƯ MỤC TRÊN GOOGLE DRIVE ---
# ID file Excel chính
DRIVE_EXCEL_FILE_ID = "16a00UFwedILbo_ujvProGmgRlJZw6qDp"
# !!! QUAN TRỌNG: Bạn cần tạo các thư mục sau trên Google Drive và dán ID của chúng vào đây
DRIVE_YTB_ACCOUNT_FOLDER_ID = "1_Drudczqoaq03L5dbkVJoA1FWgJ6R2MO" # Thư mục chứa các file token .pickle của YouTube
DRIVE_AUDIO_VIDEO_FOLDER_ID = "1uIbjogmCT-xySHleVPR3senWD7IMUE71" # <-- THAY ID NÀY: Thư mục để lưu video .mp4 cuối cùng
# --- THÊM CÁC ID MỚI CHO CÁC THƯ MỤC TRUNG GIAN ---
DRIVE_AUDIO_TXT_FOLDER_ID = "1Sg9_1XcABwTtIflqBPpGjsk5Epkz-QFe" # <-- THAY ID NÀY
DRIVE_AUDIO_MP3_FOLDER_ID = "1_eE1ZRjKPZChzlDjcUKsg0s5Rnkt6B4Y" # <-- THAY ID NÀY
DRIVE_AUDIO_FINAL_FOLDER_ID = "16L1UKQuWRGdpq5sIZ5q0rea7Q5_GidPF" # <-- THAY ID NÀY
# --- LẤY BIẾN MÔI TRƯỜNG TỪ HUGGING FACE SECRETS ---
GOOGLE_APP_SCRIPT_URL = os.getenv("GOOGLE_APP_SCRIPT_URL") # URL của Google Apps Script Web App
GOOGLE_APP_SCRIPT_KEY = os.getenv("GOOGLE_APP_SCRIPT_KEY") # Khóa dùng chung với Google Apps Script
# Biến toàn cục cho Google TTS API Key, sẽ được đọc từ Excel khi khởi động
GOOGLE_TTS_API_KEY = ""
# ==============================================================================
# --- ĐỊNH NGHĨA CÁC TRẠNG THÁI & KEYBOARD (ĐÃ CHUYỂN SANG ĐỊNH DẠNG JSON) ---
# ==============================================================================
# Logic trạng thái được giữ nguyên
AUDIO_MENU_STATE = 100
AWAITING_EPISODE_COUNT_STATE = 101
AWAITING_URL_FOR_SCRAPING_STATE = 102
AWAITING_ADD_MORE_URL_CONFIRMATION_STATE = 103
AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE = 104
AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE = 105
AWAITING_PAGE_COUNT_STATE = 106
AWAITING_ONE_CLICK_YT_CONFIRM_STATE = 107
AWAITING_ONE_CLICK_YT_ACCOUNT_STATE = 108
# <<< MỚI: Thêm các trạng thái chọn giọng đọc
AWAITING_GEN_MP3_VOICE_CHOICE_STATE = 109
AWAITING_ONE_CLICK_VOICE_CHOICE_STATE = 110
AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE = 111
# <<< BLOCK CODE MỚI BẮT ĐẦU: Thêm các trạng thái cho chức năng Truy Vết