android-times-articles / process_ready_videos_step.py
aoiandroid's picture
[UPLOAD] Sync Android Times articles archive (part 8)
9c16f8c verified
Raw History Blame Contribute Delete
35.1 kB
import os
import sys
import json
import re
import shutil
import urllib.request
import subprocess
from datetime import datetime
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = SCRIPT_DIR if os.path.exists(os.path.join(SCRIPT_DIR, "en-US")) else r"C:\ComfyUI\Articles"
WORKSPACE_DIR = os.path.dirname(SCRIPT_DIR)
COMFY_INPUT_DIR = r"C:\ComfyUI\input"
COMFY_OUTPUT_DIR = r"C:\ComfyUI\output"
def extract_main_word(title):
# Replace underscores and commas with spaces to handle words correctly
title = title.replace('_', ' ').replace(',', ' ')
is_ja = any(ord(char) > 0x3000 for char in title)
# Clean title from source marks
cleaned = re.sub(r'\s*-\s*[^-\s]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', title, flags=re.IGNORECASE)
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
def is_valid(word):
if not word:
return False
return word.strip().lower() not in blacklisted
# 1. Look for quotes like 「...」
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
for q in quotes_ja:
if is_valid(q):
return q
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
for q in quotes_en:
if len(q) < 25 and is_valid(q):
return q
# 2. Known key entities list
known_keywords = [
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
]
for kw in known_keywords:
if kw.lower() in cleaned.lower() and is_valid(kw):
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
if m:
return m.group(0)
if is_ja:
# Katakana sequences
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
for k in katakana:
if is_valid(k):
return k
# Kanji sequences
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
for k in kanji:
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
return k
if kanji:
for k in kanji:
if is_valid(k):
return k
# Alphabetic words
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
for a in alpha:
if is_valid(a):
return a
else:
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
if words:
for w in words:
if w.lower() not in ["a", "an", "the", "in", "on", "at", "for", "to", "of", "and", "or", "but", "with", "by", "is", "are", "was", "were"] and is_valid(w):
return w
for w in words:
if is_valid(w):
return w
first_token = re.search(r'\w+', cleaned)
if first_token and is_valid(first_token.group(0)):
return first_token.group(0)
return ""
def safe_filename(name, max_len=40):
main_word = extract_main_word(name).strip()
cleaned = name.replace('_', ' ').replace(',', ' ')
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
if main_word:
if cleaned.lower().startswith(main_word.lower()):
final_title = cleaned
else:
final_title = f"{main_word} {cleaned}"
else:
final_title = cleaned
final_title = re.sub(r'\s+', ' ', final_title).strip()
if len(final_title) > max_len:
final_title = final_title[:max_len].strip()
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
return final_title
def get_gpu_stats():
try:
output = subprocess.check_output(
['nvidia-smi', '--query-gpu=utilization.gpu,memory.used,memory.total', '--format=csv,noheader,nounits'],
stderr=subprocess.DEVNULL
).decode().strip()
parts = output.split(',')
if len(parts) >= 3:
return {
"util": int(parts[0].strip()),
"mem_used": int(parts[1].strip()),
"mem_total": int(parts[2].strip())
}
except Exception:
pass
return None
def is_gpu_actually_busy(threshold_util=25, threshold_mem_ratio=0.96):
stats = get_gpu_stats()
if stats is None:
return False
mem_ratio = stats["mem_used"] / stats["mem_total"]
if stats["util"] > threshold_util or mem_ratio > threshold_mem_ratio:
return True
return False
def is_port_open(host, port):
import socket
try:
with socket.create_connection((host, port), timeout=1):
return True
except OSError:
return False
def get_comfyui_url():
if is_port_open("127.0.0.1", 8188):
return "http://127.0.0.1:8188"
if is_port_open("127.0.0.1", 7777):
return "http://127.0.0.1:7777"
return "http://127.0.0.1:8188"
def get_queue():
try:
url = get_comfyui_url()
req = urllib.request.Request(f"{url}/queue")
with urllib.request.urlopen(req, timeout=3) as response:
return json.loads(response.read().decode('utf-8'))
except Exception as e:
print(f"Error connecting to ComfyUI ({get_comfyui_url()}): {e}")
return None
def queue_prompt(prompt, client_id="video_generator_agent"):
p = {"prompt": prompt, "client_id": client_id}
data = json.dumps(p).encode('utf-8')
url = get_comfyui_url()
req = urllib.request.Request(f"{url}/prompt", data=data, headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req) as response:
return json.loads(response.read().decode('utf-8'))
def check_severe_assets():
avatar_exists = os.path.exists(os.path.join(COMFY_INPUT_DIR, "android_severe_upscale.png"))
voice_exists = os.path.exists(os.path.join(COMFY_INPUT_DIR, "android_severe.wav"))
return avatar_exists and voice_exists
def generate_youtube_metadata(article_path, dest_dir, safe_name, size):
# Try to find the original article title from the main markdown file
main_title = safe_name
main_md_files = [f for f in os.listdir(article_path) if f.endswith(".md") and not f.startswith("script_") and f != "watermark_scan_report.md"]
article_summary = ""
source_info = ""
if main_md_files:
main_md_path = os.path.join(article_path, main_md_files[0])
try:
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
first_line = f.readline().strip()
if first_line.startswith("#"):
main_title = first_line.lstrip("#").strip()
else:
main_title = os.path.splitext(main_md_files[0])[0]
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read().strip()
paragraphs = [p.strip() for p in content.split('\n') if p.strip()]
non_headers = [p for p in paragraphs if not p.startswith('#')]
if non_headers:
article_summary = non_headers[0]
for p in paragraphs:
if p.startswith("**Source:**"):
source_text = p.replace("**Source:**", "").strip()
match = re.search(r'\[([^\]]+)\]\(([^)]+)\)', source_text)
if match:
source_info = f"{match.group(1)} ({match.group(2)})"
else:
source_info = source_text
except Exception as e:
print(f" Warning: Could not parse markdown for metadata: {e}")
suffix = f" ({size.capitalize()} Version)"
max_title_len = 100 - len(suffix)
if len(main_title) > max_title_len:
main_title = main_title[:max_title_len-3].strip() + "..."
main_title = f"{main_title}{suffix}"
script_text = ""
script_path = os.path.join(article_path, f"script_{size}_clean.txt")
if not os.path.exists(script_path):
script_path = os.path.join(article_path, f"script_{size}.md")
if os.path.exists(script_path):
try:
with open(script_path, "r", encoding="utf-8") as f:
script_text = f.read().strip()
except Exception:
pass
if script_path.endswith('.md') and script_text:
lines = script_text.splitlines()
cleaned_lines = []
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
line = re.sub(r'\([^)]*\)', '', line)
line = re.sub(r'\[[^\]]*\]', '', line)
line = line.replace('**', '').replace('*', '').strip()
if line:
cleaned_lines.append(line)
script_text = "\n\n".join(cleaned_lines)
metadata_lines = []
metadata_lines.append("=== YOUTUBE UPLOAD METADATA ===")
metadata_lines.append(f"SUGGESTED TITLE: {main_title}")
metadata_lines.append("===============================")
metadata_lines.append("")
metadata_lines.append("=== DESCRIPTION ===")
if script_text:
metadata_lines.append(script_text[:500] + ("..." if len(script_text) > 500 else ""))
elif article_summary:
metadata_lines.append(article_summary)
else:
metadata_lines.append(f"In this video: Latest news and updates about {main_title}.")
if source_info:
metadata_lines.append(f"\nSource: {source_info}")
else:
metadata_lines.append("\nSource: The Android Times / Provided News Sources")
metadata_lines.append("")
metadata_lines.append("--- Video Transcript ---")
if script_text:
metadata_lines.append(script_text)
else:
metadata_lines.append("(Transcript not available)")
metadata_lines.append("")
metadata_lines.append("--- About The Android Times ---")
metadata_lines.append("Your daily source for Android, AI, and technology news updates.")
metadata_lines.append("Subscribe to stay updated with the latest in tech!")
metadata_lines.append("")
metadata_lines.append(f"#Android #Tech #News #{size.capitalize()}")
metadata_lines.append("")
metadata_path = os.path.join(dest_dir, "youtube_metadata.txt")
try:
with open(metadata_path, "w", encoding="utf-8") as f:
f.write("\n".join(metadata_lines))
print(f" Generated YouTube metadata: {metadata_path}")
except Exception as e:
print(f" Error generating YouTube metadata file: {e}")
def package_youtube_assets(article_path, src_video_path, safe_name, size):
try:
youtube_dest_dir = os.path.join(WORKSPACE_DIR, "Youtube", f"{safe_name}_{size}")
os.makedirs(youtube_dest_dir, exist_ok=True)
# 1. Copy article folder contents to Youtube\<safe_name>_<size>
for item in os.listdir(article_path):
s_item = os.path.join(article_path, item)
d_item = os.path.join(youtube_dest_dir, item)
if os.path.isdir(s_item):
if item not in ["__pycache__", "images", "sources"]:
shutil.copytree(s_item, d_item, dirs_exist_ok=True)
else:
shutil.copy2(s_item, d_item)
# Copy the video .mp4 there too
youtube_video_dest = os.path.join(youtube_dest_dir, f"{safe_name}_{size}.mp4")
shutil.copy2(src_video_path, youtube_video_dest)
print(f" Successfully copied video to Youtube folder: {youtube_video_dest}")
# 2. Generate YouTube Metadata
generate_youtube_metadata(article_path, youtube_dest_dir, safe_name, size)
except Exception as e:
print(f" Error packaging YouTube assets: {e}")
def get_all_article_directories():
article_paths = []
locales = ["en-US"]
for locale in locales:
locale_path = os.path.join(ROOT_DIR, locale)
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
continue
try:
categories = os.listdir(locale_path)
except OSError:
continue
for category in categories:
if category == "__pycache__":
continue
cat_path = os.path.join(locale_path, category)
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
continue
try:
articles = os.listdir(cat_path)
except OSError:
continue
for article in articles:
if article in ["__pycache__", "images", "sources"]:
continue
article_path = os.path.join(cat_path, article)
if os.path.isdir(article_path):
article_paths.append(article_path)
return article_paths
def copy_talkvideos_to_articles():
talkvideo_dir = r"C:\Android Times\newsvideo"
if not os.path.exists(talkvideo_dir):
print(f"talkvideo directory not found: {talkvideo_dir}")
return
try:
video_files = [f for f in os.listdir(talkvideo_dir) if f.lower().endswith(".mp4")]
except OSError as e:
print(f"Error listing talkvideo directory: {e}")
return
if not video_files:
print("No video files found in talkvideo directory.")
return
article_dirs = get_all_article_directories()
copied_count = 0
for video_file in video_files:
src_path = os.path.join(talkvideo_dir, video_file)
# Parse prefix and suffix
base_name = os.path.splitext(video_file)[0]
size = None
for s in ["_short", "_middle", "_long"]:
if base_name.endswith(s):
size = s[1:]
prefix = base_name[:-len(s)]
break
else:
size = "middle"
prefix = base_name
normalized_prefix = prefix.strip().lower()
matched_article_path = None
# 1. Try exact matching
for art_path in article_dirs:
folder_name = os.path.basename(art_path)
if safe_filename(folder_name).strip().lower() == normalized_prefix:
matched_article_path = art_path
break
if folder_name.strip().lower() == normalized_prefix:
matched_article_path = art_path
break
if folder_name.replace('_', ' ').strip().lower() == normalized_prefix:
matched_article_path = art_path
break
# 2. Try word-based fallback matching if no exact match found
if not matched_article_path:
words = re.findall(r'[a-zA-Z0-9]+', prefix)
ignore_words = {"and", "the", "for", "with", "from", "that", "this", "our", "you", "your", "com"}
filtered_words = [w.lower() for w in words if len(w) >= 2 and w.lower() not in ignore_words]
if filtered_words:
candidates = []
for art_path in article_dirs:
folder_name = os.path.basename(art_path).replace('_', ' ').lower()
if all(w in folder_name for w in filtered_words):
candidates.append(art_path)
if len(candidates) == 1:
matched_article_path = candidates[0]
elif len(candidates) > 1:
# Filter candidates that have .flac files
candidates_with_flac = []
for c in candidates:
flac_files = [f for f in os.listdir(c) if f.lower().endswith(".flac")]
if flac_files:
candidates_with_flac.append(c)
if len(candidates_with_flac) == 1:
matched_article_path = candidates_with_flac[0]
elif len(candidates_with_flac) > 1:
candidates_with_flac.sort(key=lambda p: len(os.path.basename(p)))
matched_article_path = candidates_with_flac[0]
else:
candidates.sort(key=lambda p: len(os.path.basename(p)))
matched_article_path = candidates[0]
if matched_article_path:
folder_name = os.path.basename(matched_article_path)
safe_name = safe_filename(folder_name)
dest_filename = f"{safe_name}_{size}.mp4"
# Copy to ComfyUI articles folder
dest_path = os.path.join(matched_article_path, dest_filename)
# Copy to Workspace articles folder
rel_path = os.path.relpath(matched_article_path, ROOT_DIR)
workspace_dest_dir = os.path.join(WORKSPACE_DIR, "Articles", rel_path)
workspace_dest_path = os.path.join(workspace_dest_dir, dest_filename)
try:
src_size = os.path.getsize(src_path)
# Check ComfyUI target
comfy_updated = False
if (not os.path.exists(dest_path)) or (os.path.getsize(dest_path) != src_size):
print(f"Saving speaker video to ComfyUI article folder:")
print(f" {src_path} -> {dest_path}")
shutil.copy2(src_path, dest_path)
comfy_updated = True
copied_count += 1
# Check Workspace target
if (not os.path.exists(workspace_dest_path)) or (os.path.getsize(workspace_dest_path) != src_size):
print(f"Saving speaker video to Workspace article folder:")
print(f" {src_path} -> {workspace_dest_path}")
os.makedirs(workspace_dest_dir, exist_ok=True)
shutil.copy2(src_path, workspace_dest_path)
if not comfy_updated: # avoid double counting
copied_count += 1
except Exception as e:
print(f" Error copying {video_file}: {e}")
print(f"Speaker video sync finished. Copied/updated {copied_count} file(s).")
def main():
print(f"=== News Video Generator Step Utility: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
# Copy speaker videos from talkvideo to corresponding article directories
copy_talkvideos_to_articles()
if not (is_port_open("127.0.0.1", 8188) or is_port_open("127.0.0.1", 7777)):
print("Error: ComfyUI server is offline (ports 8188 / 7777).")
sys.exit(1)
queue_status = get_queue()
if queue_status is None:
sys.exit(1)
running_jobs = queue_status.get("queue_running", [])
pending_jobs = queue_status.get("queue_pending", [])
running_count = len(running_jobs)
pending_count = len(pending_jobs)
print(f"ComfyUI Status - Running: {running_count}, Pending: {pending_count}")
# 1. Scan for READY_FOR_VIDEO articles
locales = ["en-US"]
ready_articles = []
target_article = None
if len(sys.argv) > 1:
for i in range(1, len(sys.argv)):
if sys.argv[i] == "--article" and i + 1 < len(sys.argv):
target_article = sys.argv[i+1]
for locale in locales:
locale_path = os.path.join(ROOT_DIR, locale)
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
continue
try:
categories = os.listdir(locale_path)
except OSError:
continue
for category in categories:
if category == "__pycache__":
continue
cat_path = os.path.join(locale_path, category)
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
continue
try:
articles = os.listdir(cat_path)
except OSError:
continue
for article in articles:
if article in ["__pycache__", "images", "sources"]:
continue
if target_article and target_article not in article:
continue
article_path = os.path.join(cat_path, article)
if not os.path.isdir(article_path):
continue
# Check evaluation status
eval_path = os.path.join(article_path, "evaluation_result.json")
if os.path.exists(eval_path):
try:
with open(eval_path, 'r', encoding='utf-8') as ef:
eval_data = ef.read()
if '"status": "READY_FOR_VIDEO"' in eval_data:
# Check tier (Only S/A tier: 1 or 2)
json_path = os.path.join(article_path, f"{article}.json")
if not os.path.exists(json_path):
continue
try:
with open(json_path, 'r', encoding='utf-8') as jf:
meta = json.load(jf)
if meta.get("tier") not in [1, 2]:
continue
except Exception as te:
print(f"Warning: Failed to read tier for {article}: {te}")
continue
safe_name = safe_filename(article)
# Migrate legacy [safe_name].mp4 to [safe_name]_middle.mp4 if it exists
legacy_video = os.path.join(article_path, f"{safe_name}.mp4")
migrated_video = os.path.join(article_path, f"{safe_name}_middle.mp4")
if os.path.exists(legacy_video) and not os.path.exists(migrated_video):
try:
shutil.move(legacy_video, migrated_video)
print(f"Migrated legacy video for {article} to _middle.mp4")
except Exception as me:
print(f"Warning: Failed to migrate legacy video: {me}")
# Find which of the sizes are missing
missing_sizes = []
for sz in ["middle", "short", "long"]:
if not os.path.exists(os.path.join(article_path, f"{safe_name}_{sz}.mp4")):
missing_sizes.append(sz)
if missing_sizes:
ready_articles.append({
"path": article_path,
"category": category,
"locale": locale,
"name": article,
"missing_sizes": missing_sizes
})
except Exception as e:
print(f"Warning: Failed to read {eval_path}: {e}")
# Prioritize Moscow Attacks and War/Military categories
def get_priority(art):
path_lower = art["path"].lower()
score = 0
if "en-us" in path_lower:
score += 10000
if "en-us" in path_lower and "moscow_attacks" in path_lower:
score += 1000
elif "moscow_attacks" in path_lower:
score += 500
elif "war_and_military" in path_lower:
score += 400
return score
ready_articles.sort(key=get_priority, reverse=True)
# 2. Check for completed videos in ComfyUI output directory and copy them
video_dir = os.path.join(COMFY_OUTPUT_DIR, "video")
if not os.path.exists(video_dir):
video_dir = os.path.join(r"C:\ComfyUI\output", "video")
copied_count = 0
if os.path.exists(video_dir):
for art in ready_articles:
safe_name = safe_filename(art["name"])
for sz in list(art["missing_sizes"]): # Use list copy to safely modify missing_sizes
try:
# ComfyUI output filenames will be prefixed with safe_name_sz
matching_files = [f for f in os.listdir(video_dir) if f.startswith(f"{safe_name}_{sz}") and f.endswith(".mp4")]
except OSError:
matching_files = []
if matching_files:
# Sort by modification time to get the latest
matching_files.sort(key=lambda f: os.path.getmtime(os.path.join(video_dir, f)), reverse=True)
latest_video = matching_files[0]
src_path = os.path.join(video_dir, latest_video)
dest_path = os.path.join(art["path"], f"{safe_name}_{sz}.mp4")
print(f"Found completed {sz} video for: {art['name']}")
print(f" Copying: {src_path} -> {dest_path}")
try:
shutil.copy2(src_path, dest_path)
print(" Successfully copied!")
package_youtube_assets(art["path"], src_path, safe_name, sz)
copied_count += 1
art["missing_sizes"].remove(sz)
except Exception as e:
print(f" Error copying file: {e}")
# Update ready list (exclude ones that have no missing sizes anymore)
if copied_count > 0:
ready_articles = [art for art in ready_articles if art["missing_sizes"]]
# Run sync script
copy_script = os.path.join(ROOT_DIR, "copy_passed_articles.py")
if os.path.exists(copy_script):
print("\nRunning copy_passed_articles.py to sync to workspace...")
try:
import subprocess
subprocess.run(["python", copy_script], check=True)
print("Sync completed successfully.")
except Exception as e:
print(f"Warning: Failed to sync: {e}")
# 3. Submit next job if ComfyUI is idle
if running_count == 0 and pending_count == 0:
if ready_articles:
# Check GPU utilization
if is_gpu_actually_busy(threshold_util=25):
print("ComfyUI queue is empty, but GPU is busy (possibly running TTS or other tasks). Suspending video generation job submission.")
sys.exit(0)
next_art = ready_articles[0]
# Select the highest priority missing size
script_type = next_art["missing_sizes"][0]
print(f"\nSubmitting next video generation job for: {next_art['name']} (Size: {script_type})")
# Find script and determine the matched script type
script_path = os.path.join(next_art["path"], f"script_{script_type}_clean.txt")
if not os.path.exists(script_path):
script_path = os.path.join(next_art["path"], f"script_{script_type}.md")
if not os.path.exists(script_path):
print(f" Error: No script file found for {script_type} in {next_art['path']}. Skipping.")
sys.exit(1)
try:
with open(script_path, 'r', encoding='utf-8') as f:
script_text = f.read().strip()
except Exception as e:
print(f" Error: Failed to read script file {script_path}: {e}")
sys.exit(1)
# Clean script text if md
if script_path.endswith('.md'):
lines = script_text.splitlines()
cleaned_lines = []
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
line = re.sub(r'\([^)]*\)', '', line)
line = re.sub(r'\[[^\]]*\]', '', line)
line = line.replace('**', '').replace('*', '').strip()
if line:
cleaned_lines.append(line)
script_text = "\n\n".join(cleaned_lines)
if not script_text:
print(" Error: Cleaned script text is empty. Skipping.")
sys.exit(1)
# Determine severity
cat_lower = str(next_art["category"]).lower()
is_severe = "military" in cat_lower or "conflict" in cat_lower or "severe" in cat_lower or "attack" in cat_lower
use_severe_workflow = False
if is_severe:
if check_severe_assets():
use_severe_workflow = True
print(" Using severe category settings.")
else:
print(" Severe assets missing in ComfyUI/input. Falling back to normal settings.")
workflow_filename = "flat_prompt_severe.json" if use_severe_workflow else "flat_prompt.json"
workflow_path = os.path.join(WORKSPACE_DIR, workflow_filename)
if not os.path.exists(workflow_path):
workflow_path = os.path.join(ROOT_DIR, workflow_filename)
if not os.path.exists(workflow_path):
print(f" Error: Workflow JSON not found at {workflow_path}.")
sys.exit(1)
try:
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow = json.load(f)
except Exception as e:
print(f" Error: Failed to load workflow JSON {workflow_path}: {e}")
sys.exit(1)
workflow["42"]["inputs"]["text"] = script_text
# Find pre-generated voiceover audio in the article directory matching the script type
audio_files = [f for f in os.listdir(next_art["path"]) if f.lower().endswith(('.flac', '.wav', '.mp3'))]
if audio_files:
# Try to find a file matching the specific script type (short, long, or middle/standard)
audio_file = None
if script_type == "short":
matched = [f for f in audio_files if "_short_" in f.lower()]
if matched: audio_file = matched[0]
elif script_type == "long":
matched = [f for f in audio_files if "_long_" in f.lower()]
if matched: audio_file = matched[0]
else: # middle
matched = [f for f in audio_files if "_indextts" in f.lower() and "_short_" not in f.lower() and "_long_" not in f.lower()]
if matched: audio_file = matched[0]
# Fallback to any flac or audio file if specific match not found
if not audio_file:
main_audio = [f for f in audio_files if f.lower().endswith('.flac')]
if not main_audio:
main_audio = audio_files
audio_file = main_audio[0]
src_audio_path = os.path.join(next_art["path"], audio_file)
dest_audio_name = f"temp_ready_audio{os.path.splitext(audio_file)[1]}"
dest_audio_path = os.path.join(COMFY_INPUT_DIR, dest_audio_name)
print(f" Found pre-generated voiceover audio: {audio_file} (matched to {script_type} script)")
print(f" Copying: {src_audio_path} -> {dest_audio_path}")
try:
shutil.copy2(src_audio_path, dest_audio_path)
if "66_73" in workflow:
workflow["66_73"]["inputs"]["audio"] = dest_audio_name
print(f" Updated LoadAudio node to load: {dest_audio_name}")
elif "66:73" in workflow:
workflow["66:73"]["inputs"]["audio"] = dest_audio_name
print(f" Updated LoadAudio node to load: {dest_audio_name}")
else:
print(" Warning: LoadAudio node 66_73 (or 66:73) not found in workflow.")
except Exception as copy_err:
print(f" Warning: Failed to copy voiceover audio: {copy_err}")
else:
print(" Warning: No pre-generated voiceover audio found in article directory.")
safe_name = safe_filename(next_art["name"])
# Support both SaveVideo node ID 78 and 97
save_video_id = None
if "78" in workflow:
save_video_id = "78"
elif "97" in workflow:
save_video_id = "97"
if save_video_id:
workflow[save_video_id]["inputs"]["filename_prefix"] = f"video/{safe_name}_{script_type}"
print(f" Updated SaveVideo node {save_video_id} filename_prefix.")
else:
print(" Warning: SaveVideo node 78 or 97 not found in workflow.")
try:
res = queue_prompt(workflow)
prompt_id = res.get("prompt_id")
print(f" Success! Job queued in ComfyUI. Prompt ID: {prompt_id}")
except Exception as e:
print(f" Error submitting prompt to ComfyUI: {e}")
sys.exit(1)
else:
print("No articles are ready for video generation.")
else:
# Check if the running job has our client ID
running_prompts = [x[1] for x in running_jobs]
print(f"Active Job in ComfyUI: {running_prompts}")
if __name__ == "__main__":
main()