[UPLOAD] Sync Android Times articles archive (part 8)
Browse files- migrate_videos_to_articles.py +155 -0
- news_collection_and_script_generation/README.md +14 -0
- news_collection_and_script_generation/auto_tts_on_idle.py +534 -0
- news_collection_and_script_generation/collect_news_service.py +524 -0
- news_collection_and_script_generation/copy_passed_articles.py +196 -0
- news_collection_and_script_generation/create_perplexity_article.py +99 -0
- news_collection_and_script_generation/cron_processor.py +62 -0
- news_collection_and_script_generation/evaluate_for_tts.py +273 -0
- news_collection_and_script_generation/finalize_articles.py +561 -0
- news_collection_and_script_generation/generate_scripts_all.py +349 -0
- news_collection_and_script_generation/generator_task_config.xml +48 -0
- news_collection_and_script_generation/quality_gate_articles.py +410 -0
- news_collection_and_script_generation/run_pipeline_safely.ps1 +79 -0
- news_collection_and_script_generation/run_scripts_safely.ps1 +93 -0
- news_collection_and_script_generation/synthesize_articles_litert.py +194 -0
- news_collection_and_script_generation/synthesize_articles_raw.py +151 -0
- news_collection_and_script_generation/task_config.xml +48 -0
- news_collection_and_script_generation/tts_articles.py +541 -0
- process_broll_watermarks.py +84 -0
- process_ready_videos_step.py +797 -0
- quality_gate_articles.py +410 -0
- quality_gate_broll.py +535 -0
- quality_gate_newsvideo.py +414 -0
- quality_gate_youtube.py +830 -0
- recover_missing_images.py +360 -0
- run_generator_silent.vbs +3 -0
- run_pipeline_safely.ps1 +79 -0
- run_scripts_safely.ps1 +93 -0
- run_silent.vbs +3 -0
- run_tts_silent.vbs +3 -0
- run_video_watcher.ps1 +24 -0
- script_long.json +5 -0
- script_long.md +7 -0
- script_long.rag_ingested +1 -0
migrate_videos_to_articles.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import re
|
| 4 |
+
import shutil
|
| 5 |
+
|
| 6 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 7 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 8 |
+
|
| 9 |
+
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
+
ARTICLES_DIR = SCRIPT_DIR
|
| 11 |
+
NEWSVIDEO_DIR = r"C:\Android Times\newsvideo"
|
| 12 |
+
MEDIA_BUNDLE_DIR = r"C:\Android Times\media_bundle\news_videos"
|
| 13 |
+
|
| 14 |
+
def extract_main_word(title):
|
| 15 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 16 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 17 |
+
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)
|
| 18 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 19 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 20 |
+
def is_valid(w): return w and w.strip().lower() not in blacklisted
|
| 21 |
+
|
| 22 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 23 |
+
for q in quotes_ja:
|
| 24 |
+
if is_valid(q): return q
|
| 25 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 26 |
+
for q in quotes_en:
|
| 27 |
+
if len(q) < 25 and is_valid(q): return q
|
| 28 |
+
|
| 29 |
+
known_keywords = ["OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk", "大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"]
|
| 30 |
+
for kw in known_keywords:
|
| 31 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 32 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 33 |
+
if m: return m.group(0)
|
| 34 |
+
|
| 35 |
+
if is_ja:
|
| 36 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 37 |
+
for k in katakana:
|
| 38 |
+
if is_valid(k): return k
|
| 39 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 40 |
+
for k in kanji:
|
| 41 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k): return k
|
| 42 |
+
if kanji:
|
| 43 |
+
for k in kanji:
|
| 44 |
+
if is_valid(k): return k
|
| 45 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 46 |
+
for a in alpha:
|
| 47 |
+
if is_valid(a): return a
|
| 48 |
+
else:
|
| 49 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 50 |
+
if words:
|
| 51 |
+
for w in words:
|
| 52 |
+
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):
|
| 53 |
+
return w
|
| 54 |
+
for w in words:
|
| 55 |
+
if is_valid(w): return w
|
| 56 |
+
first_token = re.search(r'\w+', cleaned)
|
| 57 |
+
if first_token and is_valid(first_token.group(0)): return first_token.group(0)
|
| 58 |
+
return ""
|
| 59 |
+
|
| 60 |
+
def safe_filename(name, max_len=40):
|
| 61 |
+
main_word = extract_main_word(name).strip()
|
| 62 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 63 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
|
| 64 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 65 |
+
if main_word:
|
| 66 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 67 |
+
final_title = cleaned
|
| 68 |
+
else:
|
| 69 |
+
final_title = f"{main_word} {cleaned}"
|
| 70 |
+
else:
|
| 71 |
+
final_title = cleaned
|
| 72 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 73 |
+
if len(final_title) > max_len:
|
| 74 |
+
final_title = final_title[:max_len].strip()
|
| 75 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 76 |
+
return final_title
|
| 77 |
+
|
| 78 |
+
def find_all_article_dirs(base_dir):
|
| 79 |
+
article_dirs = []
|
| 80 |
+
for root, dirs, files in os.walk(base_dir):
|
| 81 |
+
if any(f.endswith('.md') for f in files) or any(f.endswith('.json') for f in files):
|
| 82 |
+
if root != base_dir and os.path.basename(root) not in ['sources', 'images', '__pycache__', 'temp']:
|
| 83 |
+
article_dirs.append(root)
|
| 84 |
+
return article_dirs
|
| 85 |
+
|
| 86 |
+
def migrate_videos():
|
| 87 |
+
print("=== Starting Video Migration to Article Directories ===")
|
| 88 |
+
article_dirs = find_all_article_dirs(ARTICLES_DIR)
|
| 89 |
+
print(f"Discovered {len(article_dirs)} article directories.")
|
| 90 |
+
|
| 91 |
+
safe_to_dir = {}
|
| 92 |
+
folder_to_dir = {}
|
| 93 |
+
for adir in article_dirs:
|
| 94 |
+
fname = os.path.basename(adir)
|
| 95 |
+
sname = safe_filename(fname)
|
| 96 |
+
safe_to_dir[sname.lower()] = adir
|
| 97 |
+
folder_to_dir[fname.lower()] = adir
|
| 98 |
+
|
| 99 |
+
COMFY_VIDEO_DIR = r"C:\ComfyUI\output\video"
|
| 100 |
+
source_dirs = [NEWSVIDEO_DIR, MEDIA_BUNDLE_DIR, COMFY_VIDEO_DIR]
|
| 101 |
+
migrated_count = 0
|
| 102 |
+
|
| 103 |
+
for sdir in source_dirs:
|
| 104 |
+
if not os.path.exists(sdir):
|
| 105 |
+
continue
|
| 106 |
+
print(f"\nScanning source directory: {sdir}")
|
| 107 |
+
for video_file in os.listdir(sdir):
|
| 108 |
+
if not video_file.lower().endswith('.mp4'):
|
| 109 |
+
continue
|
| 110 |
+
src_path = os.path.join(sdir, video_file)
|
| 111 |
+
base_name = os.path.splitext(video_file)[0]
|
| 112 |
+
# Strip ComfyUI counter suffix like _00001_
|
| 113 |
+
base_name = re.sub(r'_\d{5}_$', '', base_name)
|
| 114 |
+
|
| 115 |
+
size = "middle"
|
| 116 |
+
prefix = base_name
|
| 117 |
+
for s in ["_short", "_middle", "_long"]:
|
| 118 |
+
if base_name.endswith(s):
|
| 119 |
+
size = s[1:]
|
| 120 |
+
prefix = base_name[:-len(s)]
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
norm_prefix = prefix.strip().lower()
|
| 124 |
+
target_dir = None
|
| 125 |
+
|
| 126 |
+
if norm_prefix in folder_to_dir:
|
| 127 |
+
target_dir = folder_to_dir[norm_prefix]
|
| 128 |
+
elif norm_prefix in safe_to_dir:
|
| 129 |
+
target_dir = safe_to_dir[norm_prefix]
|
| 130 |
+
else:
|
| 131 |
+
words = [w.lower() for w in re.findall(r'[a-zA-Z0-9]+', prefix) if len(w) >= 3]
|
| 132 |
+
if words:
|
| 133 |
+
for adir in article_dirs:
|
| 134 |
+
aname = os.path.basename(adir).lower()
|
| 135 |
+
if all(w in aname for w in words):
|
| 136 |
+
target_dir = adir
|
| 137 |
+
break
|
| 138 |
+
|
| 139 |
+
if target_dir:
|
| 140 |
+
dest_file_name = f"{safe_filename(os.path.basename(target_dir))}_{size}.mp4"
|
| 141 |
+
dest_path = os.path.join(target_dir, dest_file_name)
|
| 142 |
+
|
| 143 |
+
if not os.path.exists(dest_path) or os.path.getsize(dest_path) != os.path.getsize(src_path):
|
| 144 |
+
shutil.copy2(src_path, dest_path)
|
| 145 |
+
print(f" [MIGRATED] {video_file} -> {os.path.relpath(dest_path, ARTICLES_DIR)}")
|
| 146 |
+
migrated_count += 1
|
| 147 |
+
else:
|
| 148 |
+
print(f" [EXISTS] {os.path.relpath(dest_path, ARTICLES_DIR)}")
|
| 149 |
+
else:
|
| 150 |
+
print(f" [UNMATCHED] {video_file}")
|
| 151 |
+
|
| 152 |
+
print(f"\n=== Migration Complete: {migrated_count} video(s) copied/updated to article folders. ===")
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
migrate_videos()
|
news_collection_and_script_generation/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# News Collection & Script Generation Toolkit
|
| 2 |
+
|
| 3 |
+
This folder contains all essential Python and PowerShell scripts used for automated news collection, quality filtering, synthesis, article finalization, and multi-format script generation.
|
| 4 |
+
|
| 5 |
+
## Included Scripts:
|
| 6 |
+
- **collect_news_service.py**: Automated news collection service and feed ingestion.
|
| 7 |
+
- **create_perplexity_article.py**: Perplexity-based article generation.
|
| 8 |
+
- **synthesize_articles_litert.py / synthesize_articles_raw.py**: Article text synthesis engine using LiteRT / LLM.
|
| 9 |
+
- **quality_gate_articles.py**: Article quality gate, duplicate detection, and Tier rating.
|
| 10 |
+
- **finalize_articles.py**: Finalization of raw articles into structured JSON/Markdown.
|
| 11 |
+
- **generate_scripts_all.py**: Batch generation of 3-length scripts (short, middle, long) and clean TTS text files.
|
| 12 |
+
- **evaluate_for_tts.py / tts_articles.py / auto_tts_on_idle.py**: TTS evaluation and automated synthesis pipelines.
|
| 13 |
+
- **copy_passed_articles.py / cron_processor.py**: File routing and cron scheduling utilities.
|
| 14 |
+
- **run_pipeline_safely.ps1 / run_scripts_safely.ps1**: Safe execution launchers for PowerShell environment.
|
news_collection_and_script_generation/auto_tts_on_idle.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import urllib.request
|
| 6 |
+
import time
|
| 7 |
+
import uuid
|
| 8 |
+
import subprocess
|
| 9 |
+
import argparse
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows
|
| 13 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 14 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 15 |
+
|
| 16 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 17 |
+
DEFAULT_WORKFLOW = r"C:\ComfyUI\workflows\05_Audio_&_TTS\Text to Speech.json"
|
| 18 |
+
SERVER_URL = "http://127.0.0.1:7777"
|
| 19 |
+
|
| 20 |
+
# Add articles dir to python path
|
| 21 |
+
sys.path.append(ROOT_DIR)
|
| 22 |
+
try:
|
| 23 |
+
import tts_articles
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
print(f"Failed to import tts_articles.py: {e}")
|
| 26 |
+
sys.exit(1)
|
| 27 |
+
|
| 28 |
+
def get_gpu_stats():
|
| 29 |
+
try:
|
| 30 |
+
output = subprocess.check_output(
|
| 31 |
+
['nvidia-smi', '--query-gpu=utilization.gpu,memory.used,memory.total', '--format=csv,noheader,nounits'],
|
| 32 |
+
stderr=subprocess.DEVNULL
|
| 33 |
+
).decode().strip()
|
| 34 |
+
parts = output.split(',')
|
| 35 |
+
if len(parts) >= 3:
|
| 36 |
+
return {
|
| 37 |
+
"util": int(parts[0].strip()),
|
| 38 |
+
"mem_used": int(parts[1].strip()),
|
| 39 |
+
"mem_total": int(parts[2].strip())
|
| 40 |
+
}
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
def is_comfyui_queue_empty():
|
| 46 |
+
try:
|
| 47 |
+
req = urllib.request.Request(f"{SERVER_URL}/queue")
|
| 48 |
+
with urllib.request.urlopen(req, timeout=3) as response:
|
| 49 |
+
queue_status = json.loads(response.read().decode('utf-8'))
|
| 50 |
+
running = queue_status.get("queue_running", [])
|
| 51 |
+
pending = queue_status.get("queue_pending", [])
|
| 52 |
+
return len(running) == 0 and len(pending) == 0
|
| 53 |
+
except Exception:
|
| 54 |
+
# If we can't connect, assume not empty to be safe
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
def has_ready_video_articles():
|
| 58 |
+
# Scan all articles to check if any have READY_FOR_VIDEO status
|
| 59 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 60 |
+
for locale in locales:
|
| 61 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 62 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 63 |
+
continue
|
| 64 |
+
try:
|
| 65 |
+
categories = os.listdir(locale_path)
|
| 66 |
+
except OSError:
|
| 67 |
+
continue
|
| 68 |
+
for category in categories:
|
| 69 |
+
if category == "__pycache__":
|
| 70 |
+
continue
|
| 71 |
+
cat_path = os.path.join(locale_path, category)
|
| 72 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 73 |
+
continue
|
| 74 |
+
try:
|
| 75 |
+
articles = os.listdir(cat_path)
|
| 76 |
+
except OSError:
|
| 77 |
+
continue
|
| 78 |
+
for article in articles:
|
| 79 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 80 |
+
continue
|
| 81 |
+
article_path = os.path.join(cat_path, article)
|
| 82 |
+
if not os.path.isdir(article_path):
|
| 83 |
+
continue
|
| 84 |
+
eval_path = os.path.join(article_path, "evaluation_result.json")
|
| 85 |
+
if os.path.exists(eval_path):
|
| 86 |
+
try:
|
| 87 |
+
with open(eval_path, 'r', encoding='utf-8') as ef:
|
| 88 |
+
eval_data = ef.read()
|
| 89 |
+
if '"status": "READY_FOR_VIDEO"' in eval_data:
|
| 90 |
+
return True
|
| 91 |
+
except Exception:
|
| 92 |
+
pass
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
def is_system_idle_for_spot_tts(threshold_util=25, threshold_mem_ratio=0.96):
|
| 96 |
+
# 1. Check GPU utilization
|
| 97 |
+
stats = get_gpu_stats()
|
| 98 |
+
if stats is None:
|
| 99 |
+
return False, "GPU stats unavailable"
|
| 100 |
+
mem_ratio = stats["mem_used"] / stats["mem_total"]
|
| 101 |
+
if stats["util"] > threshold_util or mem_ratio > threshold_mem_ratio:
|
| 102 |
+
return False, f"GPU busy (Util: {stats['util']}%, Mem: {stats['mem_used']}/{stats['mem_total']}MB)"
|
| 103 |
+
|
| 104 |
+
# 2. Check ComfyUI queue status
|
| 105 |
+
if not is_comfyui_queue_empty():
|
| 106 |
+
return False, "ComfyUI queue has active/pending jobs"
|
| 107 |
+
|
| 108 |
+
return True, "System is idle and ready for spot TTS"
|
| 109 |
+
|
| 110 |
+
def is_gpu_idle_quick(threshold_util=25, threshold_mem_ratio=0.96):
|
| 111 |
+
is_idle, _ = is_system_idle_for_spot_tts(threshold_util, threshold_mem_ratio)
|
| 112 |
+
return is_idle
|
| 113 |
+
|
| 114 |
+
def is_gpu_actually_busy(threshold_util=25, threshold_mem_ratio=0.96, checks=1, interval=1):
|
| 115 |
+
for _ in range(checks):
|
| 116 |
+
if is_gpu_idle_quick(threshold_util, threshold_mem_ratio):
|
| 117 |
+
return False
|
| 118 |
+
if checks > 1:
|
| 119 |
+
time.sleep(interval)
|
| 120 |
+
return True
|
| 121 |
+
|
| 122 |
+
def wait_until_gpu_idle(threshold_util=25, threshold_mem_ratio=0.96, duration=300, interval=5):
|
| 123 |
+
print(f"Waiting for system to be idle (GPU util <= {threshold_util}%, empty queue, no ready videos) for {duration} seconds...")
|
| 124 |
+
consecutive_idle = 0
|
| 125 |
+
required_consecutive = max(1, duration // interval)
|
| 126 |
+
while consecutive_idle < required_consecutive:
|
| 127 |
+
is_idle, reason = is_system_idle_for_spot_tts(threshold_util, threshold_mem_ratio)
|
| 128 |
+
if is_idle:
|
| 129 |
+
consecutive_idle += 1
|
| 130 |
+
print(f"\rSystem is idle ({consecutive_idle * interval}/{duration}s) - {reason}", end="", flush=True)
|
| 131 |
+
else:
|
| 132 |
+
if consecutive_idle > 0:
|
| 133 |
+
print(f"\nSystem became busy: {reason}. Resetting timer.")
|
| 134 |
+
consecutive_idle = 0
|
| 135 |
+
print(f"\rSystem busy - {reason}", end="", flush=True)
|
| 136 |
+
time.sleep(interval)
|
| 137 |
+
print("\nSystem is idle and ready.")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_script_file(article_dir, length):
|
| 141 |
+
# Try clean txt first
|
| 142 |
+
clean_txt = os.path.join(article_dir, f"script_{length}_clean.txt")
|
| 143 |
+
if os.path.exists(clean_txt):
|
| 144 |
+
return clean_txt
|
| 145 |
+
# Fallback to md
|
| 146 |
+
md_file = os.path.join(article_dir, f"script_{length}.md")
|
| 147 |
+
if os.path.exists(md_file):
|
| 148 |
+
return md_file
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
def run_tts_task(task, api_prompt_template, comfy_output_dir):
|
| 152 |
+
import numpy as np
|
| 153 |
+
import librosa
|
| 154 |
+
import soundfile as sf
|
| 155 |
+
|
| 156 |
+
article_dir = task["article_dir"]
|
| 157 |
+
script_name = task["script_name"]
|
| 158 |
+
output_filename = task["output_filename"]
|
| 159 |
+
|
| 160 |
+
script_path = os.path.join(article_dir, script_name)
|
| 161 |
+
print(f"\nProcessing TTS for {os.path.basename(article_dir)} ({script_name}) -> {output_filename}...")
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
script_text = tts_articles.clean_script_text(script_path)
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"Error reading/cleaning script {script_path}: {e}")
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
segments = tts_articles.split_into_segments(script_text)
|
| 170 |
+
if not segments:
|
| 171 |
+
print(f"Error: Script {script_name} is empty.")
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
client_id = str(uuid.uuid4())
|
| 175 |
+
text_input_node_id = None
|
| 176 |
+
save_audio_node_id = None
|
| 177 |
+
index_tts_node_id = None
|
| 178 |
+
emotion_text_node_id = None
|
| 179 |
+
|
| 180 |
+
for node_id, node in api_prompt_template.items():
|
| 181 |
+
if node["class_type"] == "TextInput_":
|
| 182 |
+
text_input_node_id = node_id
|
| 183 |
+
elif node["class_type"] == "SaveAudio":
|
| 184 |
+
save_audio_node_id = node_id
|
| 185 |
+
elif node["class_type"] in ["IndexTTSRun", "easy indexTTSGenerate", "IndexTTS2EmotionText"]:
|
| 186 |
+
index_tts_node_id = node_id
|
| 187 |
+
elif node["class_type"] == "easy indexTTSEmotionText":
|
| 188 |
+
emotion_text_node_id = node_id
|
| 189 |
+
|
| 190 |
+
if not text_input_node_id or not save_audio_node_id:
|
| 191 |
+
print("Error: Required nodes not found in workflow template.")
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
segment_failed = False
|
| 195 |
+
|
| 196 |
+
# 1. Setup caching variables
|
| 197 |
+
temp_prefix = output_filename.replace(".flac", "") + "_part_"
|
| 198 |
+
|
| 199 |
+
# 2. Check if cache is valid.
|
| 200 |
+
# If the script file has been modified since the oldest part file was created, we invalidate the cache.
|
| 201 |
+
existing_parts = {}
|
| 202 |
+
for s_idx in range(len(segments)):
|
| 203 |
+
part_path = os.path.join(article_dir, f"{temp_prefix}{s_idx}.flac")
|
| 204 |
+
if os.path.exists(part_path):
|
| 205 |
+
existing_parts[s_idx] = part_path
|
| 206 |
+
|
| 207 |
+
if existing_parts:
|
| 208 |
+
script_mtime = os.path.getmtime(script_path)
|
| 209 |
+
oldest_part_mtime = min(os.path.getmtime(p) for p in existing_parts.values())
|
| 210 |
+
if script_mtime > oldest_part_mtime:
|
| 211 |
+
print(" Script file has been modified since the last run. Invalidating cache...")
|
| 212 |
+
for p in existing_parts.values():
|
| 213 |
+
try:
|
| 214 |
+
os.remove(p)
|
| 215 |
+
except:
|
| 216 |
+
pass
|
| 217 |
+
existing_parts = {}
|
| 218 |
+
|
| 219 |
+
for s_idx, segment in enumerate(segments):
|
| 220 |
+
is_last = (s_idx == len(segments) - 1)
|
| 221 |
+
part_path = os.path.join(article_dir, f"{temp_prefix}{s_idx}.flac")
|
| 222 |
+
|
| 223 |
+
# Check if this segment is already cached
|
| 224 |
+
if os.path.exists(part_path):
|
| 225 |
+
print(f" Segment {s_idx+1}/{len(segments)} already cached. Skipping generation...")
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
speed_factor = 1.0 # Force 1.0 to bypass time_stretch and avoid echo
|
| 229 |
+
emphasized_segment = segment
|
| 230 |
+
emotion_desc = tts_articles.get_emotion_description(segment)
|
| 231 |
+
|
| 232 |
+
# Check GPU/system status before queuing this segment. If busy, wait until idle.
|
| 233 |
+
if is_gpu_actually_busy(threshold_util=25):
|
| 234 |
+
print(f"\nSystem is busy before segment {s_idx+1}/{len(segments)}. Pausing execution...")
|
| 235 |
+
wait_until_gpu_idle(threshold_util=25, duration=60, interval=10)
|
| 236 |
+
|
| 237 |
+
print(f" Segment {s_idx+1}/{len(segments)}: '{segment[:60]}...'")
|
| 238 |
+
|
| 239 |
+
prompt = json.loads(json.dumps(api_prompt_template))
|
| 240 |
+
prompt[text_input_node_id]["inputs"]["text"] = emphasized_segment
|
| 241 |
+
|
| 242 |
+
is_japanese = "ja-jp" in article_dir.lower()
|
| 243 |
+
if is_japanese:
|
| 244 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 245 |
+
prompt[index_tts_node_id]["inputs"]["version"] = "v2.0-jp"
|
| 246 |
+
elif "105" in prompt:
|
| 247 |
+
prompt["105"]["inputs"]["version"] = "v2.0-jp"
|
| 248 |
+
|
| 249 |
+
if emotion_text_node_id:
|
| 250 |
+
prompt[emotion_text_node_id]["inputs"]["description"] = emotion_desc
|
| 251 |
+
elif index_tts_node_id and prompt[index_tts_node_id]["class_type"] == "IndexTTS2EmotionText":
|
| 252 |
+
prompt[index_tts_node_id]["inputs"]["emo_text"] = emotion_desc
|
| 253 |
+
prompt[index_tts_node_id]["inputs"]["use_emo_text"] = True
|
| 254 |
+
|
| 255 |
+
prompt_id = str(uuid.uuid4())
|
| 256 |
+
filename_prefix = f"audio/article_tts_{prompt_id}"
|
| 257 |
+
prompt[save_audio_node_id]["inputs"]["filename_prefix"] = filename_prefix
|
| 258 |
+
|
| 259 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 260 |
+
if prompt[index_tts_node_id]["class_type"] != "IndexTTS2EmotionText":
|
| 261 |
+
prompt[index_tts_node_id]["inputs"]["unload_model"] = is_last
|
| 262 |
+
elif "105" in prompt:
|
| 263 |
+
if prompt["105"]["class_type"] not in ["IndexTTS2ModelLoader", "IndexTTS2EmotionText"]:
|
| 264 |
+
prompt["105"]["inputs"]["unload_model"] = is_last
|
| 265 |
+
|
| 266 |
+
# Queue prompt
|
| 267 |
+
try:
|
| 268 |
+
resp = tts_articles.queue_prompt(SERVER_URL, prompt, prompt_id, client_id)
|
| 269 |
+
except Exception as e:
|
| 270 |
+
print(f" Error: Failed to queue prompt: {e}")
|
| 271 |
+
segment_failed = True
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
# Wait for completion
|
| 275 |
+
completed = False
|
| 276 |
+
start_time = time.time()
|
| 277 |
+
while time.time() - start_time < 1800:
|
| 278 |
+
try:
|
| 279 |
+
history = tts_articles.get_history(SERVER_URL, prompt_id)
|
| 280 |
+
if prompt_id in history:
|
| 281 |
+
completed = True
|
| 282 |
+
break
|
| 283 |
+
except:
|
| 284 |
+
pass
|
| 285 |
+
time.sleep(0.5)
|
| 286 |
+
|
| 287 |
+
if not completed:
|
| 288 |
+
print(" Error: TTS timed out.")
|
| 289 |
+
segment_failed = True
|
| 290 |
+
break
|
| 291 |
+
|
| 292 |
+
history_entry = history[prompt_id]
|
| 293 |
+
outputs = history_entry.get("outputs", {})
|
| 294 |
+
|
| 295 |
+
if save_audio_node_id not in outputs or "audio" not in outputs[save_audio_node_id]:
|
| 296 |
+
print(" Error: SaveAudio output not found.")
|
| 297 |
+
segment_failed = True
|
| 298 |
+
break
|
| 299 |
+
|
| 300 |
+
audio_outputs = outputs[save_audio_node_id]["audio"]
|
| 301 |
+
if not audio_outputs:
|
| 302 |
+
print(" Error: No audio files returned.")
|
| 303 |
+
segment_failed = True
|
| 304 |
+
break
|
| 305 |
+
|
| 306 |
+
audio_info = audio_outputs[0]
|
| 307 |
+
gen_filename = audio_info["filename"]
|
| 308 |
+
gen_subfolder = audio_info["subfolder"]
|
| 309 |
+
|
| 310 |
+
src_path = os.path.join(comfy_output_dir, gen_subfolder, gen_filename)
|
| 311 |
+
if not os.path.exists(src_path):
|
| 312 |
+
src_path = os.path.join(r"C:\ComfyUI\output", gen_subfolder, gen_filename)
|
| 313 |
+
|
| 314 |
+
if not os.path.exists(src_path):
|
| 315 |
+
print(f" Error: Generated audio file not found at: {src_path}")
|
| 316 |
+
segment_failed = True
|
| 317 |
+
break
|
| 318 |
+
|
| 319 |
+
try:
|
| 320 |
+
# Move the segment to the cache file directly
|
| 321 |
+
import shutil
|
| 322 |
+
shutil.move(src_path, part_path)
|
| 323 |
+
print(f" Saved segment to cache: {part_path}")
|
| 324 |
+
except Exception as mv_err:
|
| 325 |
+
print(f" Error caching generated audio segment: {mv_err}")
|
| 326 |
+
segment_failed = True
|
| 327 |
+
break
|
| 328 |
+
|
| 329 |
+
if segment_failed:
|
| 330 |
+
print("Task failed.")
|
| 331 |
+
return False
|
| 332 |
+
|
| 333 |
+
# 3. Concatenation Phase
|
| 334 |
+
dest_path = os.path.join(article_dir, output_filename)
|
| 335 |
+
try:
|
| 336 |
+
print(f"Concatenating {len(segments)} segments...")
|
| 337 |
+
audio_segments = []
|
| 338 |
+
sr = 24000
|
| 339 |
+
for s_idx, segment in enumerate(segments):
|
| 340 |
+
part_path = os.path.join(article_dir, f"{temp_prefix}{s_idx}.flac")
|
| 341 |
+
y, file_sr = librosa.load(part_path, sr=None)
|
| 342 |
+
sr = file_sr
|
| 343 |
+
audio_segments.append(y)
|
| 344 |
+
|
| 345 |
+
pause_duration = tts_articles.get_pause_duration(segment)
|
| 346 |
+
if pause_duration > 0 and s_idx < len(segments) - 1:
|
| 347 |
+
silence = np.zeros(int(sr * pause_duration))
|
| 348 |
+
audio_segments.append(silence)
|
| 349 |
+
|
| 350 |
+
final_audio = np.concatenate(audio_segments)
|
| 351 |
+
max_val = np.max(np.abs(final_audio))
|
| 352 |
+
if max_val > 0.001:
|
| 353 |
+
final_audio = final_audio / max_val * 0.9
|
| 354 |
+
sf.write(dest_path, final_audio, sr, format='FLAC')
|
| 355 |
+
print(f"Saved audio to: {dest_path}")
|
| 356 |
+
|
| 357 |
+
# Clean up temp part files
|
| 358 |
+
for s_idx in range(len(segments)):
|
| 359 |
+
part_path = os.path.join(article_dir, f"{temp_prefix}{s_idx}.flac")
|
| 360 |
+
try:
|
| 361 |
+
os.remove(part_path)
|
| 362 |
+
except Exception:
|
| 363 |
+
pass
|
| 364 |
+
return True
|
| 365 |
+
except Exception as save_err:
|
| 366 |
+
print(f"Error saving final audio: {save_err}")
|
| 367 |
+
return False
|
| 368 |
+
|
| 369 |
+
script_gen_process = None
|
| 370 |
+
|
| 371 |
+
def scan_and_run(long_only=False):
|
| 372 |
+
# 1. Background script generation has been delegated to the coordinated sequential pipeline loop.
|
| 373 |
+
|
| 374 |
+
# 2. Convert default workflow to API prompt template
|
| 375 |
+
try:
|
| 376 |
+
api_prompt_template = tts_articles.convert_ui_to_api(DEFAULT_WORKFLOW, SERVER_URL)
|
| 377 |
+
except Exception as e:
|
| 378 |
+
print(f"Failed to load ComfyUI workflow: {e}. Is ComfyUI server running?")
|
| 379 |
+
return False
|
| 380 |
+
|
| 381 |
+
comfy_output_dir = os.path.abspath(os.path.join(os.path.dirname(DEFAULT_WORKFLOW), "..", "output"))
|
| 382 |
+
|
| 383 |
+
# 3. Scan for articles requiring TTS
|
| 384 |
+
locales = ["en-US"]
|
| 385 |
+
article_dirs = []
|
| 386 |
+
|
| 387 |
+
for locale in locales:
|
| 388 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 389 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 390 |
+
continue
|
| 391 |
+
|
| 392 |
+
categories = os.listdir(locale_path)
|
| 393 |
+
for category in categories:
|
| 394 |
+
if category in ["__pycache__"]:
|
| 395 |
+
continue
|
| 396 |
+
cat_path = os.path.join(locale_path, category)
|
| 397 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 398 |
+
continue
|
| 399 |
+
|
| 400 |
+
articles = os.listdir(cat_path)
|
| 401 |
+
for article in articles:
|
| 402 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 403 |
+
continue
|
| 404 |
+
article_path = os.path.join(cat_path, article)
|
| 405 |
+
if os.path.isdir(article_path):
|
| 406 |
+
# Check if it has a main markdown file
|
| 407 |
+
md_files = [f for f in os.listdir(article_path) if f.endswith(".md")]
|
| 408 |
+
if md_files:
|
| 409 |
+
article_dirs.append(article_path)
|
| 410 |
+
|
| 411 |
+
# Sort article directories by modification time (newest first)
|
| 412 |
+
article_dirs.sort(key=lambda x: os.path.getmtime(x), reverse=True)
|
| 413 |
+
|
| 414 |
+
# 4. Filter missing TTS audio tasks
|
| 415 |
+
pending_tasks = []
|
| 416 |
+
for article_dir in article_dirs:
|
| 417 |
+
article_name = os.path.basename(article_dir)
|
| 418 |
+
|
| 419 |
+
# Only process S (tier 1) and A (tier 2) articles
|
| 420 |
+
json_path = os.path.join(article_dir, f"{article_name}.json")
|
| 421 |
+
if not os.path.exists(json_path):
|
| 422 |
+
continue
|
| 423 |
+
try:
|
| 424 |
+
with open(json_path, 'r', encoding='utf-8') as jf:
|
| 425 |
+
meta = json.load(jf)
|
| 426 |
+
if meta.get("tier") not in [1, 2]:
|
| 427 |
+
continue
|
| 428 |
+
except Exception as e:
|
| 429 |
+
print(f"Error checking tier for {article_name}: {e}")
|
| 430 |
+
continue
|
| 431 |
+
|
| 432 |
+
if long_only:
|
| 433 |
+
lengths_info = [
|
| 434 |
+
{"len": "long", "suffix": "_long_indextts1.5.flac"}
|
| 435 |
+
]
|
| 436 |
+
else:
|
| 437 |
+
lengths_info = [
|
| 438 |
+
{"len": "short", "suffix": "_short_indextts1.5.flac"},
|
| 439 |
+
{"len": "middle", "suffix": "_indextts1.5.flac"},
|
| 440 |
+
{"len": "long", "suffix": "_long_indextts1.5.flac"}
|
| 441 |
+
]
|
| 442 |
+
|
| 443 |
+
for info in lengths_info:
|
| 444 |
+
target_filename = f"{article_name}{info['suffix']}"
|
| 445 |
+
target_path = os.path.join(article_dir, target_filename)
|
| 446 |
+
|
| 447 |
+
if not os.path.exists(target_path):
|
| 448 |
+
script_file = get_script_file(article_dir, info["len"])
|
| 449 |
+
if script_file:
|
| 450 |
+
pending_tasks.append({
|
| 451 |
+
"article_dir": article_dir,
|
| 452 |
+
"script_name": os.path.basename(script_file),
|
| 453 |
+
"output_filename": target_filename
|
| 454 |
+
})
|
| 455 |
+
|
| 456 |
+
if not pending_tasks:
|
| 457 |
+
print("No pending TTS tasks found.")
|
| 458 |
+
return True
|
| 459 |
+
|
| 460 |
+
def get_priority_score(article_dir):
|
| 461 |
+
path_lower = article_dir.lower()
|
| 462 |
+
score = 0
|
| 463 |
+
if "en-us" in path_lower:
|
| 464 |
+
score += 10000
|
| 465 |
+
if "en-us" in path_lower and "moscow_attacks" in path_lower:
|
| 466 |
+
score += 1000
|
| 467 |
+
elif "moscow_attacks" in path_lower:
|
| 468 |
+
score += 500
|
| 469 |
+
elif "war_and_military" in path_lower:
|
| 470 |
+
score += 400
|
| 471 |
+
|
| 472 |
+
# War-related keywords in English and Japanese
|
| 473 |
+
war_keywords = [
|
| 474 |
+
"war", "military", "conflict", "attack", "bombing", "invasion",
|
| 475 |
+
"soldier", "battle", "clash", "defense", "missile", "drone",
|
| 476 |
+
"bomb", "strike", "shelling", "army", "troop", "nato", "putin",
|
| 477 |
+
"ukraine", "russia", "kremlin", "pentagon", "blasts",
|
| 478 |
+
"戦争", "軍事", "衝突", "攻撃", "爆撃", "侵攻", "兵士", "戦闘",
|
| 479 |
+
"ミサイル", "ドローン", "爆発", "ウクライナ", "ロシア", "プーチン"
|
| 480 |
+
]
|
| 481 |
+
if any(kw in path_lower for kw in war_keywords):
|
| 482 |
+
score += 200
|
| 483 |
+
return score
|
| 484 |
+
|
| 485 |
+
# Sort pending tasks by priority score descending
|
| 486 |
+
pending_tasks.sort(key=lambda t: get_priority_score(t["article_dir"]), reverse=True)
|
| 487 |
+
|
| 488 |
+
print(f"Found {len(pending_tasks)} pending TTS tasks.")
|
| 489 |
+
|
| 490 |
+
# 5. Wait for 60 seconds of system idle time before starting TTS generation
|
| 491 |
+
print("\nWaiting for system to be idle for at least 60 seconds before starting TTS generation...")
|
| 492 |
+
wait_until_gpu_idle(threshold_util=25, duration=60, interval=10)
|
| 493 |
+
|
| 494 |
+
# Process pending tasks
|
| 495 |
+
for task in pending_tasks:
|
| 496 |
+
# Check GPU status before each task
|
| 497 |
+
if is_gpu_actually_busy(threshold_util=25):
|
| 498 |
+
print("\nGPU is busy before starting task. Waiting...")
|
| 499 |
+
wait_until_gpu_idle(threshold_util=25, duration=60, interval=60)
|
| 500 |
+
|
| 501 |
+
success = run_tts_task(task, api_prompt_template, comfy_output_dir)
|
| 502 |
+
if not success:
|
| 503 |
+
print(f"Task failed for {task['output_filename']}. Will retry in next scan.")
|
| 504 |
+
|
| 505 |
+
return True
|
| 506 |
+
|
| 507 |
+
def main():
|
| 508 |
+
parser = argparse.ArgumentParser(description="Auto TTS Daemon on GPU Idle")
|
| 509 |
+
parser.add_argument("--all-lengths", action="store_true", help="Process all script lengths instead of only long")
|
| 510 |
+
args = parser.parse_args()
|
| 511 |
+
|
| 512 |
+
long_only = not args.all_lengths
|
| 513 |
+
|
| 514 |
+
print("==================================================")
|
| 515 |
+
print(" Auto TTS Daemon on GPU Idle Started")
|
| 516 |
+
if long_only:
|
| 517 |
+
print(" MODE: Long Only TTS Generation (Spot Mode)")
|
| 518 |
+
else:
|
| 519 |
+
print(" MODE: All Script Lengths Generation")
|
| 520 |
+
print(" Polling interval: 60 seconds when idle")
|
| 521 |
+
print(" GPU idle threshold: 25% utilization")
|
| 522 |
+
print(" System check includes ComfyUI queue status")
|
| 523 |
+
print("==================================================")
|
| 524 |
+
|
| 525 |
+
while True:
|
| 526 |
+
try:
|
| 527 |
+
scan_and_run(long_only=long_only)
|
| 528 |
+
except Exception as e:
|
| 529 |
+
print(f"Error in auto TTS loop: {e}")
|
| 530 |
+
# Sleep for 60 seconds before scanning again (faster check)
|
| 531 |
+
time.sleep(60)
|
| 532 |
+
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
main()
|
news_collection_and_script_generation/collect_news_service.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import urllib.request
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import xml.etree.ElementTree as ET
|
| 7 |
+
import time
|
| 8 |
+
import sys
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import requests
|
| 11 |
+
try:
|
| 12 |
+
from curl_cffi import requests as requests_cffi
|
| 13 |
+
HAS_CURL_CFFI = True
|
| 14 |
+
except ImportError:
|
| 15 |
+
HAS_CURL_CFFI = False
|
| 16 |
+
from bs4 import BeautifulSoup
|
| 17 |
+
from googlenewsdecoder import new_decoderv1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 21 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 25 |
+
HISTORY_FILE = os.path.join(ROOT_DIR, "history.json")
|
| 26 |
+
PENDING_FILE = os.path.join(ROOT_DIR, "pending.json")
|
| 27 |
+
|
| 28 |
+
CATEGORIES = {
|
| 29 |
+
"Business": [
|
| 30 |
+
"https://news.google.com/rss/headlines/section/topic/BUSINESS?hl=en-US&gl=US&ceid=US:en"
|
| 31 |
+
],
|
| 32 |
+
"World_Affairs": [
|
| 33 |
+
"https://news.google.com/rss/headlines/section/topic/WORLD?hl=en-US&gl=US&ceid=US:en",
|
| 34 |
+
"https://news.google.com/rss/search?q=Moscow+attack+OR+Moscow+drone+OR+Ukraine+Moscow&hl=en-US&gl=US&ceid=US:en",
|
| 35 |
+
"https://news.google.com/rss/search?q=war+conflict+geopolitics+security+military&hl=en-US&gl=US&ceid=US:en",
|
| 36 |
+
"https://news.google.com/rss/headlines/section/topic/POLITICS?hl=en-US&gl=US&ceid=US:en",
|
| 37 |
+
"https://news.google.com/rss/search?q=site:themoscowtimes.com+OR+site:meduza.io+OR+site:kyivindependent.com+OR+site:pravda.com.ua+OR+site:novayagazeta.eu+OR+site:zona.media&hl=en-US&gl=US&ceid=US:en",
|
| 38 |
+
"https://meduza.io/rss/en/all",
|
| 39 |
+
"https://euromaidanpress.com/feed/"
|
| 40 |
+
],
|
| 41 |
+
|
| 42 |
+
"Animals": [
|
| 43 |
+
"https://news.google.com/rss/search?q=animals+wildlife+zoo&hl=en-US&gl=US&ceid=US:en"
|
| 44 |
+
],
|
| 45 |
+
"General": [
|
| 46 |
+
"https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en"
|
| 47 |
+
]
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# Priority limits
|
| 51 |
+
CATEGORY_LIMITS = {
|
| 52 |
+
"Business": 5,
|
| 53 |
+
"World_Affairs": 15,
|
| 54 |
+
"Animals": 5,
|
| 55 |
+
"General": 5
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
def load_history():
|
| 59 |
+
if os.path.exists(HISTORY_FILE):
|
| 60 |
+
try:
|
| 61 |
+
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
|
| 62 |
+
return json.load(f)
|
| 63 |
+
except Exception as e:
|
| 64 |
+
print(f"Failed to load history: {e}")
|
| 65 |
+
return {}
|
| 66 |
+
return {}
|
| 67 |
+
|
| 68 |
+
def save_history(history):
|
| 69 |
+
try:
|
| 70 |
+
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
|
| 71 |
+
json.dump(history, f, indent=4, ensure_ascii=False)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Failed to save history: {e}")
|
| 74 |
+
|
| 75 |
+
def load_pending():
|
| 76 |
+
if os.path.exists(PENDING_FILE):
|
| 77 |
+
try:
|
| 78 |
+
with open(PENDING_FILE, 'r', encoding='utf-8') as f:
|
| 79 |
+
return json.load(f)
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"Failed to load pending queue: {e}")
|
| 82 |
+
return []
|
| 83 |
+
return []
|
| 84 |
+
|
| 85 |
+
def save_pending(pending):
|
| 86 |
+
try:
|
| 87 |
+
with open(PENDING_FILE, 'w', encoding='utf-8') as f:
|
| 88 |
+
json.dump(pending, f, indent=4, ensure_ascii=False)
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"Failed to save pending queue: {e}")
|
| 91 |
+
|
| 92 |
+
def extract_main_word(title):
|
| 93 |
+
# Replace underscores and commas with spaces to handle words correctly
|
| 94 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 95 |
+
|
| 96 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 97 |
+
|
| 98 |
+
# Clean title from source marks
|
| 99 |
+
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)
|
| 100 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 101 |
+
|
| 102 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 103 |
+
|
| 104 |
+
def is_valid(word):
|
| 105 |
+
if not word:
|
| 106 |
+
return False
|
| 107 |
+
return word.strip().lower() not in blacklisted
|
| 108 |
+
|
| 109 |
+
# 1. Look for quotes like 「...」
|
| 110 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 111 |
+
for q in quotes_ja:
|
| 112 |
+
if is_valid(q):
|
| 113 |
+
return q
|
| 114 |
+
|
| 115 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 116 |
+
for q in quotes_en:
|
| 117 |
+
if len(q) < 25 and is_valid(q):
|
| 118 |
+
return q
|
| 119 |
+
|
| 120 |
+
# 2. Known key entities list
|
| 121 |
+
known_keywords = [
|
| 122 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 123 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 124 |
+
]
|
| 125 |
+
for kw in known_keywords:
|
| 126 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 127 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 128 |
+
if m:
|
| 129 |
+
return m.group(0)
|
| 130 |
+
|
| 131 |
+
if is_ja:
|
| 132 |
+
# Katakana sequences
|
| 133 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 134 |
+
for k in katakana:
|
| 135 |
+
if is_valid(k):
|
| 136 |
+
return k
|
| 137 |
+
# Kanji sequences
|
| 138 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 139 |
+
for k in kanji:
|
| 140 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 141 |
+
return k
|
| 142 |
+
if kanji:
|
| 143 |
+
for k in kanji:
|
| 144 |
+
if is_valid(k):
|
| 145 |
+
return k
|
| 146 |
+
# Alphabetic words
|
| 147 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 148 |
+
for a in alpha:
|
| 149 |
+
if is_valid(a):
|
| 150 |
+
return a
|
| 151 |
+
else:
|
| 152 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 153 |
+
if words:
|
| 154 |
+
for w in words:
|
| 155 |
+
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):
|
| 156 |
+
return w
|
| 157 |
+
for w in words:
|
| 158 |
+
if is_valid(w):
|
| 159 |
+
return w
|
| 160 |
+
|
| 161 |
+
first_token = re.search(r'\w+', cleaned)
|
| 162 |
+
if first_token and is_valid(first_token.group(0)):
|
| 163 |
+
return first_token.group(0)
|
| 164 |
+
|
| 165 |
+
return ""
|
| 166 |
+
|
| 167 |
+
def safe_filename(name, max_len=40):
|
| 168 |
+
main_word = extract_main_word(name).strip()
|
| 169 |
+
|
| 170 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 171 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
|
| 172 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 173 |
+
|
| 174 |
+
if main_word:
|
| 175 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 176 |
+
final_title = cleaned
|
| 177 |
+
else:
|
| 178 |
+
final_title = f"{main_word} {cleaned}"
|
| 179 |
+
else:
|
| 180 |
+
final_title = cleaned
|
| 181 |
+
|
| 182 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 183 |
+
|
| 184 |
+
if len(final_title) > max_len:
|
| 185 |
+
final_title = final_title[:max_len].strip()
|
| 186 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 187 |
+
|
| 188 |
+
return final_title
|
| 189 |
+
|
| 190 |
+
def normalize_title(title):
|
| 191 |
+
if not title:
|
| 192 |
+
return ""
|
| 193 |
+
# Normalize title by converting to lowercase and stripping all non-alphanumeric characters
|
| 194 |
+
title = title.lower()
|
| 195 |
+
title = re.sub(r'[^a-z0-9]', '', title)
|
| 196 |
+
return title
|
| 197 |
+
|
| 198 |
+
def extract_text_from_html(html_content):
|
| 199 |
+
try:
|
| 200 |
+
soup = BeautifulSoup(html_content, 'html.parser')
|
| 201 |
+
# Remove unwanted tags
|
| 202 |
+
for tag in soup(['script', 'style', 'head', 'title', 'meta', 'link', 'header', 'footer', 'nav']):
|
| 203 |
+
tag.decompose()
|
| 204 |
+
# Extract text and clean up whitespace
|
| 205 |
+
text = soup.get_text()
|
| 206 |
+
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
| 207 |
+
return '\n'.join(lines)
|
| 208 |
+
except Exception as e:
|
| 209 |
+
print(f"BeautifulSoup error: {e}, falling back to regex")
|
| 210 |
+
# Fallback regex
|
| 211 |
+
text = re.sub(r'<(script|style|head|title|meta|link|header|footer|nav).*?>.*?</\1>', '', html_content, flags=re.DOTALL | re.IGNORECASE)
|
| 212 |
+
text = re.sub(r'<[^>]*>', ' ', text)
|
| 213 |
+
lines = []
|
| 214 |
+
for line in text.splitlines():
|
| 215 |
+
line = line.strip()
|
| 216 |
+
if line:
|
| 217 |
+
lines.append(line)
|
| 218 |
+
return '\n'.join(lines)
|
| 219 |
+
|
| 220 |
+
def download_as_text(url, dest_path):
|
| 221 |
+
print(f"Downloading & extracting text: {url} -> {dest_path}")
|
| 222 |
+
|
| 223 |
+
# Decode Google News URL to get original source URL
|
| 224 |
+
decoded_url = url
|
| 225 |
+
try:
|
| 226 |
+
res = new_decoderv1(url, interval=1)
|
| 227 |
+
if res.get("status"):
|
| 228 |
+
decoded_url = res["decoded_url"]
|
| 229 |
+
print(f"Decoded Google News URL: {decoded_url}")
|
| 230 |
+
except Exception as e:
|
| 231 |
+
print(f"Failed to decode Google News URL {url}: {e}")
|
| 232 |
+
|
| 233 |
+
headers = {
|
| 234 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 235 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
|
| 236 |
+
"Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
|
| 237 |
+
"Referer": "https://news.google.com/",
|
| 238 |
+
"Connection": "keep-alive"
|
| 239 |
+
}
|
| 240 |
+
try:
|
| 241 |
+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
|
| 242 |
+
if HAS_CURL_CFFI:
|
| 243 |
+
response = requests_cffi.get(decoded_url, headers=headers, impersonate="chrome120", timeout=30)
|
| 244 |
+
else:
|
| 245 |
+
response = requests.get(decoded_url, headers=headers, timeout=30)
|
| 246 |
+
response.raise_for_status()
|
| 247 |
+
|
| 248 |
+
html_text = response.text
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# Extract plain text
|
| 252 |
+
plain_text = extract_text_from_html(html_text)
|
| 253 |
+
|
| 254 |
+
# Check if extracted text contains API refusal/failure patterns
|
| 255 |
+
refusal_patterns = [
|
| 256 |
+
r"i apologize, but i (cannot|can't)",
|
| 257 |
+
r"i am unable to (fetch|browse|access)",
|
| 258 |
+
r"i (cannot|can't) (fetch|browse|access) (live|real-time|the web|current)",
|
| 259 |
+
r"i do not have access to (live|real-time|current)",
|
| 260 |
+
r"sign up and repeat your request",
|
| 261 |
+
r"perplexity\.com/hub/legal/privacy-policy",
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
plain_text_lower = plain_text.lower()
|
| 265 |
+
is_refusal = False
|
| 266 |
+
for pattern in refusal_patterns:
|
| 267 |
+
if re.search(pattern, plain_text_lower):
|
| 268 |
+
is_refusal = True
|
| 269 |
+
print(f"Refusal detected in content with pattern: {pattern}")
|
| 270 |
+
break
|
| 271 |
+
|
| 272 |
+
if is_refusal:
|
| 273 |
+
print(f"Extracted content contains API refusal/error message. Rejecting.")
|
| 274 |
+
return False
|
| 275 |
+
|
| 276 |
+
# Check if extracted text is empty or too short
|
| 277 |
+
if not plain_text.strip():
|
| 278 |
+
plain_text = "[Failed to extract meaningful text from HTML. This is a fallback.]"
|
| 279 |
+
|
| 280 |
+
with open(dest_path, 'w', encoding='utf-8') as f:
|
| 281 |
+
f.write(plain_text)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# Verify it is not 0 bytes
|
| 285 |
+
if os.path.exists(dest_path) and os.path.getsize(dest_path) > 0:
|
| 286 |
+
print(f"Text extraction success: {dest_path} ({os.path.getsize(dest_path)} bytes)")
|
| 287 |
+
return True
|
| 288 |
+
else:
|
| 289 |
+
print(f"Extracted file is empty: {dest_path}")
|
| 290 |
+
if os.path.exists(dest_path):
|
| 291 |
+
os.remove(dest_path)
|
| 292 |
+
return False
|
| 293 |
+
except Exception as e:
|
| 294 |
+
print(f"Failed to download and extract text from {decoded_url}: {e}")
|
| 295 |
+
return False
|
| 296 |
+
|
| 297 |
+
def fetch_rss(url, limit=10):
|
| 298 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
| 299 |
+
try:
|
| 300 |
+
with urllib.request.urlopen(req, timeout=15) as response:
|
| 301 |
+
xml_data = response.read()
|
| 302 |
+
root = ET.fromstring(xml_data)
|
| 303 |
+
items = []
|
| 304 |
+
for item in root.findall('.//item')[:limit * 2]:
|
| 305 |
+
title = item.find('title').text if item.find('title') is not None else ""
|
| 306 |
+
link = item.find('link').text if item.find('link') is not None else ""
|
| 307 |
+
pub_date = item.find('pubDate').text if item.find('pubDate') is not None else ""
|
| 308 |
+
desc_elem = item.find('description')
|
| 309 |
+
desc = desc_elem.text if desc_elem is not None else ""
|
| 310 |
+
desc = re.sub(r'<[^>]*>', '', desc)
|
| 311 |
+
items.append({
|
| 312 |
+
"title": title,
|
| 313 |
+
"link": link,
|
| 314 |
+
"pub_date": pub_date,
|
| 315 |
+
"description": desc
|
| 316 |
+
})
|
| 317 |
+
return items
|
| 318 |
+
except Exception as e:
|
| 319 |
+
print(f"Failed to fetch RSS {url}: {e}")
|
| 320 |
+
return []
|
| 321 |
+
|
| 322 |
+
def prioritize_items(items):
|
| 323 |
+
priority_keywords = [
|
| 324 |
+
# Specific high-priority targets & events
|
| 325 |
+
"moscow", "refinery", "kapotnya", "kremlin", "drone strike",
|
| 326 |
+
"モスクワ", "製油所", "ドローン",
|
| 327 |
+
|
| 328 |
+
# Geopolitical Regions & Countries (English & Japanese)
|
| 329 |
+
"iran", "america", "united states", "us", "china", "russia", "ukraine",
|
| 330 |
+
"イラン", "アメリカ", "米国", "中国", "ロシア", "ウクライナ",
|
| 331 |
+
|
| 332 |
+
# General War & Conflict (English)
|
| 333 |
+
"war", "conflict", "military", "strike", "attack", "offensive",
|
| 334 |
+
"missile", "explosion", "shelling", "invasion", "casualty",
|
| 335 |
+
"casualties", "ceasefire", "truce", "defense", "defence",
|
| 336 |
+
"air strike", "bombing", "nato", "troops", "forces", "combat",
|
| 337 |
+
|
| 338 |
+
# General War & Conflict (Japanese)
|
| 339 |
+
"戦争", "紛争", "軍事", "攻撃", "空爆", "ミサイル", "爆発",
|
| 340 |
+
"砲撃", "侵攻", "防衛", "戦闘", "部隊", "停戦", "被弾"
|
| 341 |
+
]
|
| 342 |
+
|
| 343 |
+
def get_priority(item):
|
| 344 |
+
text = (item.get("title", "") + " " + item.get("description", "")).lower()
|
| 345 |
+
if any(kw in text for kw in priority_keywords):
|
| 346 |
+
return 0 # High priority (sorted to the front)
|
| 347 |
+
return 1 # Normal priority
|
| 348 |
+
return sorted(items, key=get_priority)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def main():
|
| 353 |
+
print(f"Starting background news collection at {datetime.now().isoformat()}")
|
| 354 |
+
history = load_history()
|
| 355 |
+
pending = load_pending()
|
| 356 |
+
|
| 357 |
+
# Create a set of already fetched/scheduled URLs and normalized titles to avoid duplicates
|
| 358 |
+
existing_urls = set(history.keys())
|
| 359 |
+
existing_titles = set()
|
| 360 |
+
|
| 361 |
+
for url, info in history.items():
|
| 362 |
+
if isinstance(info, dict) and 'title' in info:
|
| 363 |
+
existing_titles.add(normalize_title(info['title']))
|
| 364 |
+
|
| 365 |
+
for item in pending:
|
| 366 |
+
existing_urls.add(item['link'])
|
| 367 |
+
if 'title' in item:
|
| 368 |
+
existing_titles.add(normalize_title(item['title']))
|
| 369 |
+
|
| 370 |
+
new_items_added = 0
|
| 371 |
+
|
| 372 |
+
for category, urls in CATEGORIES.items():
|
| 373 |
+
print(f"\nProcessing category: {category}")
|
| 374 |
+
limit = CATEGORY_LIMITS.get(category, 10)
|
| 375 |
+
|
| 376 |
+
raw_items = []
|
| 377 |
+
for url in urls:
|
| 378 |
+
raw_items.extend(fetch_rss(url, limit=limit))
|
| 379 |
+
|
| 380 |
+
if not raw_items:
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
# Remove duplicate links within raw_items
|
| 384 |
+
seen_links = set()
|
| 385 |
+
unique_items = []
|
| 386 |
+
for item in raw_items:
|
| 387 |
+
link = item['link']
|
| 388 |
+
if link not in seen_links:
|
| 389 |
+
seen_links.add(link)
|
| 390 |
+
unique_items.append(item)
|
| 391 |
+
|
| 392 |
+
# Filter new items (not in history or pending)
|
| 393 |
+
new_items = []
|
| 394 |
+
for item in unique_items:
|
| 395 |
+
norm_title = normalize_title(item['title'])
|
| 396 |
+
if item['link'] not in existing_urls and norm_title not in existing_titles:
|
| 397 |
+
new_items.append(item)
|
| 398 |
+
|
| 399 |
+
# Prioritize important topics (e.g. Moscow attacks)
|
| 400 |
+
new_items = prioritize_items(new_items)
|
| 401 |
+
|
| 402 |
+
# Limit processing items
|
| 403 |
+
new_items = new_items[:limit]
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
if not new_items:
|
| 407 |
+
print(f"No new articles to collect for category: {category}")
|
| 408 |
+
continue
|
| 409 |
+
|
| 410 |
+
# Directory paths
|
| 411 |
+
temp_sources_dir = os.path.join(ROOT_DIR, "temp_sources")
|
| 412 |
+
os.makedirs(temp_sources_dir, exist_ok=True)
|
| 413 |
+
|
| 414 |
+
print(f"Found {len(new_items)} new items for {category}. Downloading source text...")
|
| 415 |
+
for item in new_items:
|
| 416 |
+
safe_title = safe_filename(item['title'])
|
| 417 |
+
source_filename = f"{safe_title}_source.txt"
|
| 418 |
+
source_path = os.path.join(temp_sources_dir, source_filename)
|
| 419 |
+
|
| 420 |
+
# Download and extract text
|
| 421 |
+
if download_as_text(item['link'], source_path):
|
| 422 |
+
# Add to pending list
|
| 423 |
+
pending.append({
|
| 424 |
+
"category": category,
|
| 425 |
+
"title": item['title'],
|
| 426 |
+
"link": item['link'],
|
| 427 |
+
"pub_date": item['pub_date'],
|
| 428 |
+
"description": item['description'],
|
| 429 |
+
"source_file": source_path
|
| 430 |
+
})
|
| 431 |
+
existing_urls.add(item['link'])
|
| 432 |
+
existing_titles.add(normalize_title(item['title']))
|
| 433 |
+
new_items_added += 1
|
| 434 |
+
else:
|
| 435 |
+
print(f"Skipping '{item['title']}' due to download failure.")
|
| 436 |
+
|
| 437 |
+
if new_items_added > 0:
|
| 438 |
+
save_pending(pending)
|
| 439 |
+
print(f"Collection finished. Added {new_items_added} new items to pending queue.")
|
| 440 |
+
else:
|
| 441 |
+
print("Collection finished. No new items added.")
|
| 442 |
+
|
| 443 |
+
# Phase 2: Run news compilation with LiteRT-LM (Gemma-4)
|
| 444 |
+
try:
|
| 445 |
+
print("\n=== PHASE 2: LiteRT-LM News Compilation (Gemma-4) ===")
|
| 446 |
+
import subprocess
|
| 447 |
+
cmd = [sys.executable, os.path.join(ROOT_DIR, "synthesize_articles_litert.py")]
|
| 448 |
+
res = subprocess.run(cmd, capture_output=False, text=True)
|
| 449 |
+
if res.returncode != 0:
|
| 450 |
+
raise RuntimeError(f"LiteRT-LM compilation subprocess exited with code {res.returncode}")
|
| 451 |
+
except Exception as e:
|
| 452 |
+
print(f"Failed to run LiteRT-LM compilation phase: {e}. Falling back to Raw News Compilation.")
|
| 453 |
+
try:
|
| 454 |
+
import synthesize_articles_raw
|
| 455 |
+
synthesize_articles_raw.main()
|
| 456 |
+
except Exception as fallback_err:
|
| 457 |
+
print(f"Failed to run fallback Raw compilation phase: {fallback_err}")
|
| 458 |
+
|
| 459 |
+
# Phase 2.5: Article Quality Gate (Proofreading)
|
| 460 |
+
try:
|
| 461 |
+
print("\n=== PHASE 2.5: Article Quality Gate (Proofreading) ===")
|
| 462 |
+
cmd = [sys.executable, os.path.join(ROOT_DIR, "quality_gate_articles.py")]
|
| 463 |
+
res = subprocess.run(cmd, capture_output=False, text=True)
|
| 464 |
+
if res.returncode != 0:
|
| 465 |
+
print(f"Quality gate subprocess exited with code {res.returncode}")
|
| 466 |
+
except Exception as e:
|
| 467 |
+
print(f"Failed to run Quality Gate phase: {e}. Skipping proofreading.")
|
| 468 |
+
|
| 469 |
+
# Phase 3: Run article finalization (assets download, embeds, history updates)
|
| 470 |
+
finalized_dirs = []
|
| 471 |
+
try:
|
| 472 |
+
print("\n=== PHASE 3: Article Finalization ===")
|
| 473 |
+
import finalize_articles
|
| 474 |
+
finalized_dirs = finalize_articles.main()
|
| 475 |
+
except Exception as e:
|
| 476 |
+
print(f"Failed to run finalization phase: {e}")
|
| 477 |
+
|
| 478 |
+
# Phase 3.5: LiteRT-LM News Script Generation (en-US)
|
| 479 |
+
try:
|
| 480 |
+
print("\n=== PHASE 3.5: LiteRT-LM News Script Generation ===")
|
| 481 |
+
import subprocess
|
| 482 |
+
cmd = [sys.executable, os.path.join(ROOT_DIR, "generate_scripts_all.py"), "--locale", "en-US", "--limit", "5", "--gpu"]
|
| 483 |
+
res = subprocess.run(cmd, capture_output=False, text=True)
|
| 484 |
+
if res.returncode != 0:
|
| 485 |
+
print(f"Script generation subprocess exited with code {res.returncode}")
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print(f"Failed to run Script Generation phase: {e}")
|
| 488 |
+
|
| 489 |
+
# Phase 3.8: Automatically generate B-roll for newly finalized articles
|
| 490 |
+
if finalized_dirs:
|
| 491 |
+
try:
|
| 492 |
+
print("\n=== PHASE 3.8: Automatic B-roll Collection ===")
|
| 493 |
+
import subprocess
|
| 494 |
+
for art_dir in finalized_dirs:
|
| 495 |
+
print(f"Running B-roll collection for: {art_dir}")
|
| 496 |
+
broll_cmd = [sys.executable, os.path.join(ROOT_DIR, "collect_broll_agent.py"), "--article-dir", art_dir]
|
| 497 |
+
subprocess.run(broll_cmd, check=True)
|
| 498 |
+
except Exception as e:
|
| 499 |
+
print(f"Failed to run automatic B-roll collection phase: {e}")
|
| 500 |
+
|
| 501 |
+
# Phase 4: Automatically generate thumbnails for newly finalized articles
|
| 502 |
+
try:
|
| 503 |
+
print("\n=== PHASE 4: Automatic Thumbnail Generation ===")
|
| 504 |
+
sys.path.append(r"C:\VideoGemma\scripts")
|
| 505 |
+
import run_all_batches_fast
|
| 506 |
+
run_all_batches_fast.main()
|
| 507 |
+
except Exception as e:
|
| 508 |
+
print(f"Failed to run automatic thumbnail generation phase: {e}")
|
| 509 |
+
|
| 510 |
+
# Phase 5: Automatically backfill missing B-rolls for older articles (15 per run)
|
| 511 |
+
try:
|
| 512 |
+
print("\n=== PHASE 5: Automatic B-roll Backfill ===")
|
| 513 |
+
backfill_script = r"C:\Roaming\scratch\batch_generate_brolls.py"
|
| 514 |
+
if os.path.exists(backfill_script):
|
| 515 |
+
broll_cmd = [sys.executable, backfill_script, "--limit", "15"]
|
| 516 |
+
subprocess.run(broll_cmd, check=True)
|
| 517 |
+
else:
|
| 518 |
+
print(f"Backfill script not found at: {backfill_script}")
|
| 519 |
+
except Exception as e:
|
| 520 |
+
print(f"Failed to run B-roll backfill phase: {e}")
|
| 521 |
+
|
| 522 |
+
if __name__ == "__main__":
|
| 523 |
+
main()
|
| 524 |
+
|
news_collection_and_script_generation/copy_passed_articles.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import re
|
| 4 |
+
import shutil
|
| 5 |
+
import argparse
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
# Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows
|
| 10 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 11 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 12 |
+
|
| 13 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 14 |
+
DEST_DIR = r"C:\Users\eggof\Desktop\Android Times\Articles"
|
| 15 |
+
|
| 16 |
+
def check_article_gate(article_dir):
|
| 17 |
+
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md") and not f.startswith("script_") and f != "watermark_scan_report.md"]
|
| 18 |
+
if not md_files:
|
| 19 |
+
return False, "Main article markdown file not found."
|
| 20 |
+
|
| 21 |
+
main_md_path = os.path.join(article_dir, md_files[0])
|
| 22 |
+
try:
|
| 23 |
+
with open(main_md_path, "r", encoding="utf-8") as f:
|
| 24 |
+
content = f.read().strip()
|
| 25 |
+
except Exception as e:
|
| 26 |
+
return False, f"Failed to read article markdown: {e}"
|
| 27 |
+
|
| 28 |
+
if len(content) < 150:
|
| 29 |
+
return False, f"Article content is too short ({len(content)} chars)."
|
| 30 |
+
|
| 31 |
+
error_patterns = [
|
| 32 |
+
r"403\s+forbidden",
|
| 33 |
+
r"access\s+denied",
|
| 34 |
+
r"enable\s+javascript",
|
| 35 |
+
r"please\s+enable\s+cookies",
|
| 36 |
+
r"cloudflare",
|
| 37 |
+
r"captcha",
|
| 38 |
+
r"are\s+you\s+a\s+robot"
|
| 39 |
+
]
|
| 40 |
+
for pattern in error_patterns:
|
| 41 |
+
if re.search(pattern, content, re.IGNORECASE):
|
| 42 |
+
return False, f"Article content contains error pattern: '{pattern}'"
|
| 43 |
+
|
| 44 |
+
return True, "Pass"
|
| 45 |
+
|
| 46 |
+
def check_script_gate(article_dir):
|
| 47 |
+
lengths = ["short", "middle", "long"]
|
| 48 |
+
for length in lengths:
|
| 49 |
+
script_md = os.path.join(article_dir, f"script_{length}.md")
|
| 50 |
+
script_txt = os.path.join(article_dir, f"script_{length}_clean.txt")
|
| 51 |
+
|
| 52 |
+
if not os.path.exists(script_md) or not os.path.exists(script_txt):
|
| 53 |
+
return False, f"Missing script files for length: {length}"
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
with open(script_md, "r", encoding="utf-8") as f:
|
| 57 |
+
md_content = f.read().strip()
|
| 58 |
+
with open(script_txt, "r", encoding="utf-8") as f:
|
| 59 |
+
txt_content = f.read().strip()
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return False, f"Failed to read script files: {e}"
|
| 62 |
+
|
| 63 |
+
if not md_content or not txt_content:
|
| 64 |
+
return False, f"Script content is empty for length: {length}"
|
| 65 |
+
|
| 66 |
+
# Check for speaker labels or dialogue indicators in the text
|
| 67 |
+
forbidden_labels = [r'\bAnchor\b:', r'\bReporter\b:', r'\bCorrespondent\b:', r'\bPresenter\b:', r'\bNarrator\b:', r'\bHost\b:', r'\bVoiceover\b:']
|
| 68 |
+
for pattern in forbidden_labels:
|
| 69 |
+
if re.search(pattern, txt_content, re.IGNORECASE) or re.search(pattern, md_content, re.IGNORECASE):
|
| 70 |
+
return False, f"Script contains forbidden speaker label matching: '{pattern}'"
|
| 71 |
+
|
| 72 |
+
# Check for parenthetical directions like "(laughing)", "[music]"
|
| 73 |
+
if re.search(r'\([^)]+\)', txt_content) or re.search(r'\[[^\]]+\]', txt_content):
|
| 74 |
+
return False, f"Clean script contains parenthetical directions or annotations."
|
| 75 |
+
|
| 76 |
+
return True, "Pass"
|
| 77 |
+
|
| 78 |
+
def check_thumbnail_gate(article_dir):
|
| 79 |
+
thumb_path = os.path.join(article_dir, "thumbnail.png")
|
| 80 |
+
if not os.path.exists(thumb_path):
|
| 81 |
+
return False, "thumbnail.png not found."
|
| 82 |
+
try:
|
| 83 |
+
with Image.open(thumb_path) as img:
|
| 84 |
+
img.verify()
|
| 85 |
+
return True, "Pass"
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return False, f"Thumbnail is corrupted: {e}"
|
| 88 |
+
|
| 89 |
+
def sync_directory(src, dest):
|
| 90 |
+
os.makedirs(dest, exist_ok=True)
|
| 91 |
+
copied_files = 0
|
| 92 |
+
for item in os.listdir(src):
|
| 93 |
+
s_item = os.path.join(src, item)
|
| 94 |
+
d_item = os.path.join(dest, item)
|
| 95 |
+
if os.path.isdir(s_item):
|
| 96 |
+
if item in ["__pycache__"]:
|
| 97 |
+
continue
|
| 98 |
+
copied_files += sync_directory(s_item, d_item)
|
| 99 |
+
else:
|
| 100 |
+
# Copy file if newer, modified size, or missing
|
| 101 |
+
if not os.path.exists(d_item) or os.path.getsize(s_item) != os.path.getsize(d_item) or os.path.getmtime(s_item) > os.path.getmtime(d_item):
|
| 102 |
+
try:
|
| 103 |
+
shutil.copy2(s_item, d_item)
|
| 104 |
+
copied_files += 1
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f" Failed to copy file {item}: {e}")
|
| 107 |
+
return copied_files
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
parser = argparse.ArgumentParser(description="Evaluate quality gates and copy passed articles to destination.")
|
| 111 |
+
parser.add_argument("--locale", type=str, default=None, help="Filter by locale.")
|
| 112 |
+
parser.add_argument("--category", type=str, default=None, help="Filter by category.")
|
| 113 |
+
parser.add_argument("--dry-run", action="store_true", help="Evaluate only, do not copy.")
|
| 114 |
+
args = parser.parse_args()
|
| 115 |
+
|
| 116 |
+
print(f"=== Quality Gate Evaluation & Copy System: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
|
| 117 |
+
print(f"Source: {ROOT_DIR}")
|
| 118 |
+
print(f"Destination: {DEST_DIR}")
|
| 119 |
+
if args.dry_run:
|
| 120 |
+
print("NOTE: Running in DRY RUN mode (no files will be copied).")
|
| 121 |
+
print("-" * 60)
|
| 122 |
+
|
| 123 |
+
# Find article directories
|
| 124 |
+
locales = [args.locale] if args.locale else [
|
| 125 |
+
d for d in os.listdir(ROOT_DIR)
|
| 126 |
+
if os.path.isdir(os.path.join(ROOT_DIR, d)) and d not in ["__pycache__", "temp", "temp_sources", "images", "sources"]
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
total_articles = 0
|
| 130 |
+
passed_articles = 0
|
| 131 |
+
copied_count = 0
|
| 132 |
+
|
| 133 |
+
for locale in locales:
|
| 134 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 135 |
+
if not os.path.isdir(locale_path):
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
categories = [args.category] if args.category else [
|
| 139 |
+
c for c in os.listdir(locale_path)
|
| 140 |
+
if os.path.isdir(os.path.join(locale_path, c)) and c not in ["__pycache__", "images", "sources"]
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
for category in categories:
|
| 144 |
+
cat_path = os.path.join(locale_path, category)
|
| 145 |
+
if not os.path.isdir(cat_path):
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
for article in os.listdir(cat_path):
|
| 149 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 150 |
+
continue
|
| 151 |
+
article_path = os.path.join(cat_path, article)
|
| 152 |
+
if not os.path.isdir(article_path):
|
| 153 |
+
continue
|
| 154 |
+
|
| 155 |
+
total_articles += 1
|
| 156 |
+
|
| 157 |
+
# Check Gates
|
| 158 |
+
art_ok, art_reason = check_article_gate(article_path)
|
| 159 |
+
script_ok, script_reason = check_script_gate(article_path)
|
| 160 |
+
thumb_ok, thumb_reason = check_thumbnail_gate(article_path)
|
| 161 |
+
|
| 162 |
+
if art_ok and script_ok and thumb_ok:
|
| 163 |
+
passed_articles += 1
|
| 164 |
+
dest_path = os.path.join(DEST_DIR, locale, category, article)
|
| 165 |
+
|
| 166 |
+
if args.dry_run:
|
| 167 |
+
print(f"[PASS] {locale}/{category}/{article} (Dry Run)")
|
| 168 |
+
else:
|
| 169 |
+
print(f"[PASS] {locale}/{category}/{article}")
|
| 170 |
+
files_copied = sync_directory(article_path, dest_path)
|
| 171 |
+
if files_copied > 0:
|
| 172 |
+
print(f" -> Copied/Updated {files_copied} files.")
|
| 173 |
+
copied_count += 1
|
| 174 |
+
else:
|
| 175 |
+
print(" -> Already up-to-date in destination.")
|
| 176 |
+
else:
|
| 177 |
+
failures = []
|
| 178 |
+
if not art_ok: failures.append(f"Article: {art_reason}")
|
| 179 |
+
if not script_ok: failures.append(f"Script: {script_reason}")
|
| 180 |
+
if not thumb_ok: failures.append(f"Thumbnail: {thumb_reason}")
|
| 181 |
+
|
| 182 |
+
# Print failures in a compact way
|
| 183 |
+
print(f"[FAIL] {locale}/{category}/{article}")
|
| 184 |
+
for f in failures:
|
| 185 |
+
print(f" - {f}")
|
| 186 |
+
|
| 187 |
+
print("-" * 60)
|
| 188 |
+
print(f"Evaluation finished.")
|
| 189 |
+
print(f"Total articles scanned: {total_articles}")
|
| 190 |
+
print(f"Articles passed gates : {passed_articles}")
|
| 191 |
+
if not args.dry_run:
|
| 192 |
+
print(f"Article folders updated : {copied_count}")
|
| 193 |
+
print("=" * 60)
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
news_collection_and_script_generation/create_perplexity_article.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import urllib.request
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
def create_article():
|
| 7 |
+
title = "Amazon Secures $17.5 Billion Loan for AI Infrastructure"
|
| 8 |
+
safe_title = "Amazon_Secures_17_5_Billion_Loan_for_AI_Infrastructure"
|
| 9 |
+
root_dir = r"C:\ComfyUI\Articles"
|
| 10 |
+
article_dir = os.path.join(root_dir, safe_title)
|
| 11 |
+
images_dir = os.path.join(article_dir, "images")
|
| 12 |
+
sources_dir = os.path.join(article_dir, "sources")
|
| 13 |
+
|
| 14 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 15 |
+
os.makedirs(sources_dir, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# Download Unsplash images (Business theme)
|
| 18 |
+
img_urls = [
|
| 19 |
+
"https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?q=80&w=1000",
|
| 20 |
+
"https://images.unsplash.com/photo-1507679799987-c73779587ccf?q=80&w=1000"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
img_paths = []
|
| 24 |
+
for i, url in enumerate(img_urls, 1):
|
| 25 |
+
dest = os.path.join(images_dir, f"{safe_title}_img{i}.jpg")
|
| 26 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
| 27 |
+
try:
|
| 28 |
+
with urllib.request.urlopen(req, timeout=30) as response:
|
| 29 |
+
with open(dest, 'wb') as f:
|
| 30 |
+
f.write(response.read())
|
| 31 |
+
img_paths.append(dest.replace('\\', '/'))
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Failed to download image {url}: {e}")
|
| 34 |
+
img_paths.append("IMAGE_DOWNLOAD_FAILED")
|
| 35 |
+
|
| 36 |
+
date_str = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
|
| 37 |
+
|
| 38 |
+
md_content = f"""# {title}
|
| 39 |
+
{date_str}
|
| 40 |
+
|
| 41 |
+
```carousel
|
| 42 |
+

|
| 43 |
+
<!-- slide -->
|
| 44 |
+

|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
As of June 12, 2026, major developments in the AI industry are centered on massive infrastructure investment, strategic partnerships in content creation, and ongoing geopolitical and regulatory debates.
|
| 48 |
+
|
| 49 |
+
## Amazon's Massive AI Investment
|
| 50 |
+
Amazon has finalized a $17.5 billion loan facility with a consortium of major lenders, including Citibank, JPMorgan Chase, and Bank of America. This move underscores the industry-wide trend of "Big Tech" tapping into debt markets to fund the aggressive expansion of data centers and computing capacity required for generative AI, with combined industry capital expenditure now projected to exceed $700 billion this year.
|
| 51 |
+
|
| 52 |
+
## "AI+IP" Strategic Partnership in China
|
| 53 |
+
Volcano Engine has launched an in-depth partnership with Bingo Group, integrating Seedance 2.0 video generation technology with classic film intellectual property (IP), such as Stephen Chow’s *The King of Comedy* and *The God of Cookery*. This initiative aims to provide compliant AI content creation tools across multiple Chinese platforms.
|
| 54 |
+
|
| 55 |
+
## OpenAI Report on Foreign Influence
|
| 56 |
+
OpenAI recently published a report detailing how Chinese propaganda groups have attempted to use its AI models to influence U.S. political discourse, including efforts to foment dissent regarding trade policies and data center regulations. While the company noted the efforts had little impact, it highlights the increasing role of generative AI in digital influence operations.
|
| 57 |
+
|
| 58 |
+
## Ongoing Industry Trends
|
| 59 |
+
Analysts note that the current phase of the AI boom has shifted away from simple "model launches" toward building robust platforms—encompassing AI chips, runtimes, and control planes—which are becoming "stickier", multi-year investments for enterprises.
|
| 60 |
+
Oracle has also rolled out its June 2026 AI updates, including expanded multimodal capabilities and the integration of Cohere Rerank 4 to improve enterprise search and agentic AI performance.
|
| 61 |
+
|
| 62 |
+
---
|
| 63 |
+
**Images & Figures:**
|
| 64 |
+
- 
|
| 65 |
+
- 
|
| 66 |
+
|
| 67 |
+
**Author:** AntigravityAI News Collector (Perplexity Source)
|
| 68 |
+
|
| 69 |
+
**Sources & Citations:**
|
| 70 |
+
- [{title}](https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQHP6OOJS5VfJxEl-sM5nkfqGVyuYPQn3GKLJ-nPoElAHqPPcOs-fRVNulH1Vc_iA-E9c_sRuJsXjw2Xc0QmME5GiFa2igHOy9sRw4wD17x1dEO9J9QtNVMJLcdQWfJCsCehTrA0-BtWJXDqsdKPjF4HdTQ94ncCPdqYuIdRKZJ13h430edofAz2ca1v5tqPhKt0F4M4v-iqRUis9ui2EmeU2L1LM73cUvoJJFQOwYh1JEfTdAzOz4qWAVhuJaj34DaR)
|
| 71 |
+
- [Volcano Engine AI+IP](https://asianews.network)
|
| 72 |
+
- [OpenAI Report on Influence](https://taipeitimes.com)
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
dest_md = os.path.join(article_dir, f"{safe_title}.md")
|
| 76 |
+
with open(dest_md, "w", encoding="utf-8") as f:
|
| 77 |
+
f.write(md_content)
|
| 78 |
+
|
| 79 |
+
print(f"SUCCESS: Article created at {dest_md}")
|
| 80 |
+
|
| 81 |
+
# Optionally update history.json
|
| 82 |
+
history_file = os.path.join(root_dir, "history.json")
|
| 83 |
+
if os.path.exists(history_file):
|
| 84 |
+
try:
|
| 85 |
+
with open(history_file, 'r', encoding='utf-8') as f:
|
| 86 |
+
history = json.load(f)
|
| 87 |
+
history["perplexity_ai_news_june2026"] = {
|
| 88 |
+
"title": title,
|
| 89 |
+
"collected_at": datetime.now().isoformat(),
|
| 90 |
+
"category": "Business"
|
| 91 |
+
}
|
| 92 |
+
with open(history_file, 'w', encoding='utf-8') as f:
|
| 93 |
+
json.dump(history, f, indent=4, ensure_ascii=False)
|
| 94 |
+
print("Updated history.json")
|
| 95 |
+
except Exception as e:
|
| 96 |
+
print(f"Error updating history: {e}")
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
create_article()
|
news_collection_and_script_generation/cron_processor.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 5 |
+
PENDING_FILE = os.path.join(ROOT_DIR, "pending.json")
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
if not os.path.exists(PENDING_FILE):
|
| 9 |
+
print("No pending articles queue found.")
|
| 10 |
+
return
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
with open(PENDING_FILE, 'r', encoding='utf-8') as f:
|
| 14 |
+
pending = json.load(f)
|
| 15 |
+
except Exception as e:
|
| 16 |
+
print(f"Failed to read pending queue: {e}")
|
| 17 |
+
return
|
| 18 |
+
|
| 19 |
+
if not pending:
|
| 20 |
+
print("No pending articles in queue.")
|
| 21 |
+
return
|
| 22 |
+
|
| 23 |
+
# Group by category
|
| 24 |
+
by_category = {}
|
| 25 |
+
for item in pending:
|
| 26 |
+
cat = item["category"]
|
| 27 |
+
if cat not in by_category:
|
| 28 |
+
by_category[cat] = []
|
| 29 |
+
by_category[cat].append(item)
|
| 30 |
+
|
| 31 |
+
print(f"=== PENDING ARTICLES FOR SYNTHESIS (Total: {len(pending)}) ===")
|
| 32 |
+
for category, items in by_category.items():
|
| 33 |
+
print(f"\nCategory: {category}")
|
| 34 |
+
for idx, item in enumerate(items, 1):
|
| 35 |
+
print(f" {idx}. Title: {item['title']}")
|
| 36 |
+
print(f" Link: {item['link']}")
|
| 37 |
+
print(f" Source File: {item['source_file']}")
|
| 38 |
+
|
| 39 |
+
src_path = item["source_file"]
|
| 40 |
+
content = ""
|
| 41 |
+
if src_path and os.path.exists(src_path):
|
| 42 |
+
try:
|
| 43 |
+
with open(src_path, 'r', encoding='utf-8') as sf:
|
| 44 |
+
content = sf.read().strip()
|
| 45 |
+
except Exception as e:
|
| 46 |
+
content = f"Error reading source file: {e}"
|
| 47 |
+
else:
|
| 48 |
+
content = "Source file does not exist."
|
| 49 |
+
|
| 50 |
+
truncated = content
|
| 51 |
+
if len(content) > 1500:
|
| 52 |
+
truncated = content[:1500] + "... [truncated]"
|
| 53 |
+
|
| 54 |
+
print(" Content:")
|
| 55 |
+
# Indent content lines for cleaner logs
|
| 56 |
+
for line in truncated.splitlines():
|
| 57 |
+
if line.strip():
|
| 58 |
+
print(f" {line}")
|
| 59 |
+
print("\n" + "-" * 40)
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
main()
|
news_collection_and_script_generation/evaluate_for_tts.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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dout.reconfigure(encoding='utf-8')
|
| 9 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 10 |
+
|
| 11 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 12 |
+
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import litert_lm
|
| 16 |
+
HAS_LITERT = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
HAS_LITERT = False
|
| 19 |
+
|
| 20 |
+
def evaluate_script_text_quality(script_path):
|
| 21 |
+
"""
|
| 22 |
+
Perform fast, hard-coded checks on script length and content
|
| 23 |
+
before sending it to the LLM.
|
| 24 |
+
"""
|
| 25 |
+
# 1. Length Check
|
| 26 |
+
size = os.path.getsize(script_path)
|
| 27 |
+
if size < 100:
|
| 28 |
+
return {"status": "FAIL", "reason": f"Script is too short ({size} bytes). Likely an error or placeholder."}
|
| 29 |
+
if size > 8000:
|
| 30 |
+
return {"status": "FLAG", "reason": f"Script is unusually long ({size} bytes). May cause TTS timeout."}
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
with open(script_path, 'r', encoding='utf-8') as f:
|
| 34 |
+
content = f.read()
|
| 35 |
+
|
| 36 |
+
# 2. Regex Check: Scraping Errors
|
| 37 |
+
error_patterns = [
|
| 38 |
+
r"403\s+forbidden",
|
| 39 |
+
r"access\s+denied",
|
| 40 |
+
r"enable\s+javascript",
|
| 41 |
+
r"please\s+enable\s+cookies",
|
| 42 |
+
r"cloudflare",
|
| 43 |
+
r"captcha",
|
| 44 |
+
r"are\s+you\s+a\s+robot",
|
| 45 |
+
r"i\s+apologize"
|
| 46 |
+
]
|
| 47 |
+
for pattern in error_patterns:
|
| 48 |
+
if re.search(pattern, content, re.IGNORECASE):
|
| 49 |
+
return {"status": "FAIL", "reason": f"Script contains scraping error signature: '{pattern}'"}
|
| 50 |
+
|
| 51 |
+
# 3. Regex Check: TTS-Breaking Elements
|
| 52 |
+
if re.search(r'https?://[^\s]+', content):
|
| 53 |
+
return {"status": "FAIL", "reason": "Script contains raw URLs (http:// or https://) which breaks TTS output."}
|
| 54 |
+
|
| 55 |
+
if re.search(r'<\/?(?:html|div|script|style|body|head|iframe|p|span)[^>]*>', content, re.IGNORECASE):
|
| 56 |
+
return {"status": "FAIL", "reason": "Script contains raw HTML tags."}
|
| 57 |
+
|
| 58 |
+
return {"status": "PASS", "reason": "Passed hard-coded length and regex filters."}
|
| 59 |
+
except Exception as e:
|
| 60 |
+
return {"status": "FAIL", "reason": f"Could not read script to check quality: {e}"}
|
| 61 |
+
|
| 62 |
+
def evaluate_files(article_dir):
|
| 63 |
+
# Check for main md and scripts
|
| 64 |
+
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md")]
|
| 65 |
+
scripts = [f for f in md_files if "script" in f]
|
| 66 |
+
main_md = [f for f in md_files if "script" not in f]
|
| 67 |
+
|
| 68 |
+
if not main_md:
|
| 69 |
+
return {"status": "FAIL", "reason": "Main article markdown file not found"}
|
| 70 |
+
if not scripts:
|
| 71 |
+
return {"status": "FAIL", "reason": "No generated TTS script markdown files found"}
|
| 72 |
+
|
| 73 |
+
# Check text quality and sizes for each script
|
| 74 |
+
for script in scripts:
|
| 75 |
+
script_path = os.path.join(article_dir, script)
|
| 76 |
+
quality_check = evaluate_script_text_quality(script_path)
|
| 77 |
+
if quality_check["status"] != "PASS":
|
| 78 |
+
# Pass up the FAIL or FLAG status immediately
|
| 79 |
+
return quality_check
|
| 80 |
+
|
| 81 |
+
return {"status": "PASS", "reason": f"Found {len(scripts)} valid script file(s) passing strict quality filters"}
|
| 82 |
+
|
| 83 |
+
def run_llm_evaluation(engine, article_dir):
|
| 84 |
+
# Read one script (e.g., script_long.md or the first available script)
|
| 85 |
+
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md")]
|
| 86 |
+
scripts = [f for f in md_files if "script" in f]
|
| 87 |
+
|
| 88 |
+
if not scripts:
|
| 89 |
+
return {"status": "FAIL", "reason": "No script found for LLM evaluation"}
|
| 90 |
+
|
| 91 |
+
# Prefer script_long.md, otherwise just pick the first script
|
| 92 |
+
script_file = "script_long.md" if "script_long.md" in scripts else scripts[0]
|
| 93 |
+
|
| 94 |
+
content_to_check = ""
|
| 95 |
+
try:
|
| 96 |
+
with open(os.path.join(article_dir, script_file), 'r', encoding='utf-8') as f:
|
| 97 |
+
content_to_check = f.read()[:3000] # Read up to 3000 chars to avoid context limits
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return {"status": "FAIL", "reason": f"Could not read script file: {e}"}
|
| 100 |
+
|
| 101 |
+
if not content_to_check.strip():
|
| 102 |
+
return {"status": "FAIL", "reason": "Failed to read content for LLM evaluation"}
|
| 103 |
+
|
| 104 |
+
prompt = f"""You are a strict QA evaluator for a Text-To-Speech (TTS) pipeline.
|
| 105 |
+
Evaluate the following script to determine if it is ready to be synthesized into audio.
|
| 106 |
+
|
| 107 |
+
--- TTS SCRIPT ---
|
| 108 |
+
{content_to_check}
|
| 109 |
+
------------------
|
| 110 |
+
|
| 111 |
+
Check for the following issues that would break or ruin the TTS output:
|
| 112 |
+
1. Tone and Flow: Ensure the text flows naturally like a news anchor reading it. It should not sound robotic or abrupt.
|
| 113 |
+
2. AI Artifacts: Ensure the text doesn't contain weird AI artifacts like "As an AI language model..." or "Here is the rewritten text".
|
| 114 |
+
3. Spam/Non-News: Is it an empty placeholder, captcha text, or pure advertisement?
|
| 115 |
+
4. Completeness: Does the script look cut-off or nonsensical?
|
| 116 |
+
|
| 117 |
+
Respond strictly with a JSON object in this exact format:
|
| 118 |
+
{{
|
| 119 |
+
"status": "PASS" or "FAIL" or "FLAG",
|
| 120 |
+
"reason": "Brief explanation of your decision"
|
| 121 |
+
}}
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
with engine.create_conversation() as conversation:
|
| 126 |
+
response = conversation.send_message(prompt)
|
| 127 |
+
response_text = response["content"][0]["text"].strip()
|
| 128 |
+
|
| 129 |
+
# Extract JSON from response
|
| 130 |
+
json_start = response_text.find("{")
|
| 131 |
+
json_end = response_text.rfind("}") + 1
|
| 132 |
+
if json_start >= 0 and json_end > json_start:
|
| 133 |
+
json_str = response_text[json_start:json_end]
|
| 134 |
+
result = json.loads(json_str)
|
| 135 |
+
return {
|
| 136 |
+
"status": result.get("status", "FLAG"),
|
| 137 |
+
"reason": result.get("reason", "Could not parse reason from JSON")
|
| 138 |
+
}
|
| 139 |
+
else:
|
| 140 |
+
return {"status": "FLAG", "reason": "LLM response did not contain valid JSON"}
|
| 141 |
+
|
| 142 |
+
except Exception as e:
|
| 143 |
+
return {"status": "FLAG", "reason": f"LLM evaluation failed with exception: {e}"}
|
| 144 |
+
|
| 145 |
+
def evaluate_article(engine, article_dir, skip_llm=False):
|
| 146 |
+
print(f"\nEvaluating for TTS: {os.path.basename(article_dir)}")
|
| 147 |
+
results = {
|
| 148 |
+
"timestamp": datetime.now().isoformat(),
|
| 149 |
+
"status": "PENDING",
|
| 150 |
+
"checks": {},
|
| 151 |
+
"reject_reasons": []
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
# Run checks
|
| 155 |
+
results["checks"]["files"] = evaluate_files(article_dir)
|
| 156 |
+
|
| 157 |
+
if not skip_llm and engine and results["checks"]["files"]["status"] == "PASS":
|
| 158 |
+
print(" Running LLM evaluation on scripts...")
|
| 159 |
+
results["checks"]["llm"] = run_llm_evaluation(engine, article_dir)
|
| 160 |
+
else:
|
| 161 |
+
results["checks"]["llm"] = {"status": "SKIP", "reason": "LLM evaluation skipped or text files missing"}
|
| 162 |
+
|
| 163 |
+
# Determine overall status
|
| 164 |
+
is_rejected = False
|
| 165 |
+
is_flagged = False
|
| 166 |
+
|
| 167 |
+
for check_name, check_res in results["checks"].items():
|
| 168 |
+
status = check_res.get("status", "FAIL")
|
| 169 |
+
if status == "FAIL":
|
| 170 |
+
is_rejected = True
|
| 171 |
+
results["reject_reasons"].append(f"[{check_name.upper()}] {check_res.get('reason')}")
|
| 172 |
+
print(f" [FAIL] {check_name}: {check_res.get('reason')}")
|
| 173 |
+
elif status == "FLAG":
|
| 174 |
+
is_flagged = True
|
| 175 |
+
results["reject_reasons"].append(f"[{check_name.upper()} FLAGGED] {check_res.get('reason')}")
|
| 176 |
+
print(f" [FLAG] {check_name}: {check_res.get('reason')}")
|
| 177 |
+
else:
|
| 178 |
+
print(f" [{status}] {check_name}: {check_res.get('reason')}")
|
| 179 |
+
|
| 180 |
+
if is_rejected:
|
| 181 |
+
results["status"] = "REJECTED"
|
| 182 |
+
elif is_flagged:
|
| 183 |
+
results["status"] = "FLAGGED_FOR_REVIEW"
|
| 184 |
+
else:
|
| 185 |
+
results["status"] = "READY_FOR_TTS"
|
| 186 |
+
|
| 187 |
+
print(f" -> Final TTS Status: {results['status']}")
|
| 188 |
+
|
| 189 |
+
# Save results
|
| 190 |
+
result_path = os.path.join(article_dir, "evaluation_tts_result.json")
|
| 191 |
+
try:
|
| 192 |
+
with open(result_path, 'w', encoding='utf-8') as f:
|
| 193 |
+
json.dump(results, f, indent=4, ensure_ascii=False)
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f" Failed to save evaluation result: {e}")
|
| 196 |
+
|
| 197 |
+
return results["status"]
|
| 198 |
+
|
| 199 |
+
def main():
|
| 200 |
+
parser = argparse.ArgumentParser(description="Evaluate articles and scripts before TTS generation.")
|
| 201 |
+
parser.add_argument("--locale", type=str, default="en-US", help="Locale to evaluate (default: en-US)")
|
| 202 |
+
parser.add_argument("--category", type=str, default=None, help="Category to evaluate (e.g. World_Affairs)")
|
| 203 |
+
parser.add_argument("--skip-llm", action="store_true", help="Skip LLM text-quality evaluation")
|
| 204 |
+
parser.add_argument("--limit", type=int, default=0, help="Limit number of articles to evaluate. 0 for all.")
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
|
| 207 |
+
locale_dir = os.path.join(ROOT_DIR, args.locale)
|
| 208 |
+
if not os.path.exists(locale_dir):
|
| 209 |
+
print(f"Locale directory not found: {locale_dir}")
|
| 210 |
+
sys.exit(1)
|
| 211 |
+
|
| 212 |
+
article_dirs = []
|
| 213 |
+
categories = [args.category] if args.category else os.listdir(locale_dir)
|
| 214 |
+
|
| 215 |
+
for category in categories:
|
| 216 |
+
cat_path = os.path.join(locale_dir, category)
|
| 217 |
+
if not os.path.isdir(cat_path) or category == "__pycache__":
|
| 218 |
+
continue
|
| 219 |
+
|
| 220 |
+
for article in os.listdir(cat_path):
|
| 221 |
+
article_dir = os.path.join(cat_path, article)
|
| 222 |
+
if os.path.isdir(article_dir) and article not in ["images", "sources"]:
|
| 223 |
+
article_dirs.append(article_dir)
|
| 224 |
+
|
| 225 |
+
if not article_dirs:
|
| 226 |
+
print("No articles found to evaluate.")
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
if args.limit > 0:
|
| 230 |
+
article_dirs = article_dirs[:args.limit]
|
| 231 |
+
|
| 232 |
+
print(f"Found {len(article_dirs)} articles to evaluate for TTS readiness.")
|
| 233 |
+
|
| 234 |
+
engine = None
|
| 235 |
+
if not args.skip_llm:
|
| 236 |
+
if not HAS_LITERT:
|
| 237 |
+
print("Warning: litert_lm not found. Skipping LLM evaluation.")
|
| 238 |
+
args.skip_llm = True
|
| 239 |
+
elif not os.path.exists(LITERT_MODEL_PATH):
|
| 240 |
+
print(f"Warning: LLM model not found at {LITERT_MODEL_PATH}. Skipping LLM evaluation.")
|
| 241 |
+
args.skip_llm = True
|
| 242 |
+
else:
|
| 243 |
+
print("Loading LiteRT-LM Engine...")
|
| 244 |
+
try:
|
| 245 |
+
engine = litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.GPU, max_num_tokens=2048)
|
| 246 |
+
except Exception as e:
|
| 247 |
+
print(f"Failed to load LLM Engine (GPU): {e}. Trying CPU...")
|
| 248 |
+
try:
|
| 249 |
+
engine = litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.CPU, max_num_tokens=2048)
|
| 250 |
+
except Exception as e2:
|
| 251 |
+
print(f"Failed to load LLM Engine (CPU): {e2}. Skipping LLM evaluation.")
|
| 252 |
+
args.skip_llm = True
|
| 253 |
+
|
| 254 |
+
stats = {"READY_FOR_TTS": 0, "REJECTED": 0, "FLAGGED_FOR_REVIEW": 0}
|
| 255 |
+
|
| 256 |
+
try:
|
| 257 |
+
for article_dir in article_dirs:
|
| 258 |
+
status = evaluate_article(engine, article_dir, args.skip_llm)
|
| 259 |
+
stats[status] = stats.get(status, 0) + 1
|
| 260 |
+
finally:
|
| 261 |
+
if engine:
|
| 262 |
+
engine.close()
|
| 263 |
+
|
| 264 |
+
print("\n" + "="*40)
|
| 265 |
+
print("Pre-TTS Evaluation Complete!")
|
| 266 |
+
print(f"Total articles evaluated: {len(article_dirs)}")
|
| 267 |
+
print(f"READY_FOR_TTS: {stats['READY_FOR_TTS']}")
|
| 268 |
+
print(f"FLAGGED_FOR_REVIEW: {stats['FLAGGED_FOR_REVIEW']}")
|
| 269 |
+
print(f"REJECTED: {stats['REJECTED']}")
|
| 270 |
+
print("="*40)
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
main()
|
news_collection_and_script_generation/finalize_articles.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import sys
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import requests
|
| 9 |
+
try:
|
| 10 |
+
from curl_cffi import requests as requests_cffi
|
| 11 |
+
HAS_CURL_CFFI = True
|
| 12 |
+
except ImportError:
|
| 13 |
+
HAS_CURL_CFFI = False
|
| 14 |
+
from googlenewsdecoder import new_decoderv1
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 18 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 19 |
+
|
| 20 |
+
# Dynamic path for importing WatermarkRemover
|
| 21 |
+
sys.path.insert(0, r"C:\Roaming\scripts")
|
| 22 |
+
try:
|
| 23 |
+
from news_collector.watermark_remover import WatermarkRemover
|
| 24 |
+
HAS_REMOVER = True
|
| 25 |
+
except ImportError:
|
| 26 |
+
HAS_REMOVER = False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 30 |
+
HISTORY_FILE = os.path.join(ROOT_DIR, "history.json")
|
| 31 |
+
PENDING_FILE = os.path.join(ROOT_DIR, "pending.json")
|
| 32 |
+
SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json")
|
| 33 |
+
|
| 34 |
+
TEST_VIDEO_URL = "https://www.w3schools.com/html/mov_bbb.mp4"
|
| 35 |
+
|
| 36 |
+
# Fallback images removed for authentic scraping
|
| 37 |
+
|
| 38 |
+
def load_json(path, default):
|
| 39 |
+
if os.path.exists(path):
|
| 40 |
+
try:
|
| 41 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 42 |
+
return json.load(f)
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"Failed to load JSON {path}: {e}")
|
| 45 |
+
return default
|
| 46 |
+
|
| 47 |
+
def save_json(path, data):
|
| 48 |
+
try:
|
| 49 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 50 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"Failed to save JSON {path}: {e}")
|
| 53 |
+
|
| 54 |
+
def extract_main_word(title):
|
| 55 |
+
# Replace underscores and commas with spaces to handle words correctly
|
| 56 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 57 |
+
|
| 58 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 59 |
+
|
| 60 |
+
# Clean title from source marks
|
| 61 |
+
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)
|
| 62 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 63 |
+
|
| 64 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 65 |
+
|
| 66 |
+
def is_valid(word):
|
| 67 |
+
if not word:
|
| 68 |
+
return False
|
| 69 |
+
return word.strip().lower() not in blacklisted
|
| 70 |
+
|
| 71 |
+
# 1. Look for quotes like 「...」
|
| 72 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 73 |
+
for q in quotes_ja:
|
| 74 |
+
if is_valid(q):
|
| 75 |
+
return q
|
| 76 |
+
|
| 77 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 78 |
+
for q in quotes_en:
|
| 79 |
+
if len(q) < 25 and is_valid(q):
|
| 80 |
+
return q
|
| 81 |
+
|
| 82 |
+
# 2. Known key entities list
|
| 83 |
+
known_keywords = [
|
| 84 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 85 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 86 |
+
]
|
| 87 |
+
for kw in known_keywords:
|
| 88 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 89 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 90 |
+
if m:
|
| 91 |
+
return m.group(0)
|
| 92 |
+
|
| 93 |
+
if is_ja:
|
| 94 |
+
# Katakana sequences
|
| 95 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 96 |
+
for k in katakana:
|
| 97 |
+
if is_valid(k):
|
| 98 |
+
return k
|
| 99 |
+
# Kanji sequences
|
| 100 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 101 |
+
for k in kanji:
|
| 102 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 103 |
+
return k
|
| 104 |
+
if kanji:
|
| 105 |
+
for k in kanji:
|
| 106 |
+
if is_valid(k):
|
| 107 |
+
return k
|
| 108 |
+
# Alphabetic words
|
| 109 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 110 |
+
for a in alpha:
|
| 111 |
+
if is_valid(a):
|
| 112 |
+
return a
|
| 113 |
+
else:
|
| 114 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 115 |
+
if words:
|
| 116 |
+
for w in words:
|
| 117 |
+
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):
|
| 118 |
+
return w
|
| 119 |
+
for w in words:
|
| 120 |
+
if is_valid(w):
|
| 121 |
+
return w
|
| 122 |
+
|
| 123 |
+
first_token = re.search(r'\w+', cleaned)
|
| 124 |
+
if first_token and is_valid(first_token.group(0)):
|
| 125 |
+
return first_token.group(0)
|
| 126 |
+
|
| 127 |
+
return ""
|
| 128 |
+
|
| 129 |
+
def safe_filename(name, max_len=40):
|
| 130 |
+
main_word = extract_main_word(name).strip()
|
| 131 |
+
|
| 132 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 133 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
|
| 134 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 135 |
+
|
| 136 |
+
if main_word:
|
| 137 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 138 |
+
final_title = cleaned
|
| 139 |
+
else:
|
| 140 |
+
final_title = f"{main_word} {cleaned}"
|
| 141 |
+
else:
|
| 142 |
+
final_title = cleaned
|
| 143 |
+
|
| 144 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 145 |
+
|
| 146 |
+
if len(final_title) > max_len:
|
| 147 |
+
final_title = final_title[:max_len].strip()
|
| 148 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 149 |
+
|
| 150 |
+
return final_title
|
| 151 |
+
|
| 152 |
+
def to_file_uri(path):
|
| 153 |
+
path_part = path.replace(os.sep, '/')
|
| 154 |
+
return f"file:///{path_part.replace(' ', '%20')}"
|
| 155 |
+
|
| 156 |
+
def to_markdown_absolute_path(path):
|
| 157 |
+
return path.replace(os.sep, '/')
|
| 158 |
+
|
| 159 |
+
def download_file(url, dest_path):
|
| 160 |
+
print(f"Downloading: {url} -> {dest_path}")
|
| 161 |
+
headers = {
|
| 162 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 163 |
+
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
|
| 164 |
+
"Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
|
| 165 |
+
"Referer": "https://news.google.com/"
|
| 166 |
+
}
|
| 167 |
+
try:
|
| 168 |
+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
|
| 169 |
+
if HAS_CURL_CFFI:
|
| 170 |
+
response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=30)
|
| 171 |
+
else:
|
| 172 |
+
response = requests.get(url, headers=headers, timeout=30)
|
| 173 |
+
response.raise_for_status()
|
| 174 |
+
with open(dest_path, 'wb') as f:
|
| 175 |
+
f.write(response.content)
|
| 176 |
+
|
| 177 |
+
if os.path.exists(dest_path) and os.path.getsize(dest_path) > 0:
|
| 178 |
+
print(f"Download success: {dest_path} ({os.path.getsize(dest_path)} bytes)")
|
| 179 |
+
return True
|
| 180 |
+
else:
|
| 181 |
+
print(f"Downloaded file is empty: {dest_path}")
|
| 182 |
+
if os.path.exists(dest_path):
|
| 183 |
+
os.remove(dest_path)
|
| 184 |
+
return False
|
| 185 |
+
except Exception as e:
|
| 186 |
+
print(f"Failed to download {url}: {e}")
|
| 187 |
+
if os.path.exists(dest_path):
|
| 188 |
+
try:
|
| 189 |
+
os.remove(dest_path)
|
| 190 |
+
except:
|
| 191 |
+
pass
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
def is_valid_image(img_url, img_path):
|
| 195 |
+
# 1. URL Substring Check
|
| 196 |
+
url_lower = img_url.lower()
|
| 197 |
+
|
| 198 |
+
# Generic keywords indicating logos, default fallback pictures, ads, etc.
|
| 199 |
+
blacklist_keywords = [
|
| 200 |
+
"logo", "avatar", "favicon", "icon", "placeholder", "default", "fallback",
|
| 201 |
+
"dummy", "spacer", "pixel", "header", "footer", "ad-", "ads-",
|
| 202 |
+
"advertisement", "newsletter", "subscribe", "sign-up", "social-share",
|
| 203 |
+
"facebook-share", "twitter-share", "share-icon", "share-logo",
|
| 204 |
+
"app-store", "play-store", "transparent", "blank", "branding"
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
# Also block specific generic image names commonly used by news outlets
|
| 208 |
+
# e.g., Yahoo, Reuters, AP, Bloomberg, BBC, etc. logos or generic graphics
|
| 209 |
+
generic_patterns = [
|
| 210 |
+
"reuters-logo", "reuters_logo", "nytimes-logo", "nytimes_logo",
|
| 211 |
+
"ap-logo", "ap_logo", "bbc-logo", "bbc_logo", "cnn-logo", "cnn_logo",
|
| 212 |
+
"bloomberg-logo", "bloomberg_logo", "yahoo-logo", "yahoo_logo",
|
| 213 |
+
"wsj_logo", "wsj-logo", "guardian-logo", "guardian_logo"
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
for kw in blacklist_keywords:
|
| 217 |
+
if kw in url_lower:
|
| 218 |
+
print(f" Rejecting image URL (matches blacklist keyword '{kw}'): {img_url}")
|
| 219 |
+
return False
|
| 220 |
+
|
| 221 |
+
for pat in generic_patterns:
|
| 222 |
+
if pat in url_lower:
|
| 223 |
+
print(f" Rejecting image URL (matches generic logo pattern '{pat}'): {img_url}")
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
# 2. Image Content Check (using Pillow)
|
| 227 |
+
if not os.path.exists(img_path):
|
| 228 |
+
return False
|
| 229 |
+
|
| 230 |
+
try:
|
| 231 |
+
from PIL import Image, ImageStat
|
| 232 |
+
with Image.open(img_path) as img:
|
| 233 |
+
width, height = img.size
|
| 234 |
+
|
| 235 |
+
# Aspect Ratio
|
| 236 |
+
aspect_ratio = width / height
|
| 237 |
+
|
| 238 |
+
# Minimum dimension requirements
|
| 239 |
+
min_width = 300
|
| 240 |
+
min_height = 200
|
| 241 |
+
|
| 242 |
+
if width < min_width or height < min_height:
|
| 243 |
+
print(f" Rejecting image (too small: {width}x{height}, required min {min_width}x{min_height})")
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
+
# Aspect Ratio Check (block extremely wide/tall banner or ad layout blocks)
|
| 247 |
+
if aspect_ratio < 0.5 or aspect_ratio > 3.0:
|
| 248 |
+
print(f" Rejecting image (extreme aspect ratio: {aspect_ratio:.2f})")
|
| 249 |
+
return False
|
| 250 |
+
|
| 251 |
+
# Perfect square check (width == height) for small images (usually logos/avatars)
|
| 252 |
+
if width == height and width < 450:
|
| 253 |
+
print(f" Rejecting image (square logo/avatar heuristic: {width}x{height})")
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
# Standard Deviation check (blank or solid color placeholder images)
|
| 257 |
+
# A natural photograph typically has standard deviation > 10.
|
| 258 |
+
# Spacer GIFs or blank images will have standard deviation near 0.
|
| 259 |
+
stat = ImageStat.Stat(img)
|
| 260 |
+
# Check standard deviation of all bands (RGB / RGBA / L)
|
| 261 |
+
std_devs = stat.stddev
|
| 262 |
+
if std_devs and all(sd < 3.0 for sd in std_devs):
|
| 263 |
+
print(f" Rejecting image (low variance / solid color placeholder: stddev={std_devs})")
|
| 264 |
+
return False
|
| 265 |
+
|
| 266 |
+
except ImportError:
|
| 267 |
+
print(" Warning: Pillow (PIL) is not installed. Skipping image dimension and content validation.")
|
| 268 |
+
except Exception as e:
|
| 269 |
+
print(f" Warning: Failed to validate image content properties: {e}")
|
| 270 |
+
|
| 271 |
+
return True
|
| 272 |
+
|
| 273 |
+
def extract_og_image(url):
|
| 274 |
+
print(f"Extracting og:image from: {url}")
|
| 275 |
+
headers = {
|
| 276 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 277 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 278 |
+
"Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
|
| 279 |
+
"Referer": "https://news.google.com/"
|
| 280 |
+
}
|
| 281 |
+
try:
|
| 282 |
+
if HAS_CURL_CFFI:
|
| 283 |
+
response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=15)
|
| 284 |
+
else:
|
| 285 |
+
response = requests.get(url, headers=headers, timeout=15)
|
| 286 |
+
response.raise_for_status()
|
| 287 |
+
html = response.text
|
| 288 |
+
m = re.search(r'<meta[^>]*property=[\'"]og:image[\'"][^>]*content=[\'"]([^\'"]+)[\'"]', html, re.I)
|
| 289 |
+
if m:
|
| 290 |
+
return m.group(1)
|
| 291 |
+
m2 = re.search(r'<meta[^>]*content=[\'"]([^\'"]+)[\'"][^>]*property=[\'"]og:image[\'"]', html, re.I)
|
| 292 |
+
if m2:
|
| 293 |
+
return m2.group(1)
|
| 294 |
+
except Exception as e:
|
| 295 |
+
print(f"Failed to fetch og:image from {url}: {e}")
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def finalize_article(category, title, link, article_content, source_file):
|
| 300 |
+
print(f"\nFinalizing article: {title} under category: {category}")
|
| 301 |
+
|
| 302 |
+
safe_title = safe_filename(title)
|
| 303 |
+
|
| 304 |
+
# Determine language (ja-JP if title contains Japanese characters, else en-US)
|
| 305 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 306 |
+
lang = "ja-JP" if is_ja else "en-US"
|
| 307 |
+
|
| 308 |
+
# Map raw RSS category to directory category name
|
| 309 |
+
CAT_MAP = {
|
| 310 |
+
"Business": "Business_and_Economy",
|
| 311 |
+
"World_Affairs": "World_Affairs",
|
| 312 |
+
"General": "General_News",
|
| 313 |
+
"Animals": "Science_and_Animals"
|
| 314 |
+
}
|
| 315 |
+
cat_folder = CAT_MAP.get(category, "Uncategorized")
|
| 316 |
+
|
| 317 |
+
# Create article-specific directory structure under appropriate language/category
|
| 318 |
+
article_dir = os.path.join(ROOT_DIR, lang, cat_folder, safe_title)
|
| 319 |
+
images_dir = os.path.join(article_dir, "images")
|
| 320 |
+
sources_dir = os.path.join(article_dir, "sources")
|
| 321 |
+
|
| 322 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 323 |
+
os.makedirs(sources_dir, exist_ok=True)
|
| 324 |
+
|
| 325 |
+
# 1. Rename raw source file and collect details
|
| 326 |
+
downloaded_sources = []
|
| 327 |
+
if source_file and os.path.exists(source_file):
|
| 328 |
+
final_filename = f"{safe_title}_source_1.txt"
|
| 329 |
+
final_dest = os.path.join(sources_dir, final_filename)
|
| 330 |
+
try:
|
| 331 |
+
if os.path.exists(final_dest):
|
| 332 |
+
os.remove(final_dest)
|
| 333 |
+
os.rename(source_file, final_dest)
|
| 334 |
+
downloaded_sources.append((title, to_file_uri(final_dest)))
|
| 335 |
+
print(f"Moved source file: {source_file} -> {final_dest}")
|
| 336 |
+
except Exception as e:
|
| 337 |
+
print(f"Failed to move source file {source_file} to {final_dest}: {e}")
|
| 338 |
+
downloaded_sources.append((title, to_file_uri(source_file)))
|
| 339 |
+
else:
|
| 340 |
+
print(f"Source file not found or not specified for: {title}")
|
| 341 |
+
|
| 342 |
+
# 2. Download authentic images from source link
|
| 343 |
+
image_urls = []
|
| 344 |
+
|
| 345 |
+
decoded_link = link
|
| 346 |
+
if "news.google.com" in link:
|
| 347 |
+
try:
|
| 348 |
+
res = new_decoderv1(link, interval=1)
|
| 349 |
+
if res.get("status"):
|
| 350 |
+
decoded_link = res["decoded_url"]
|
| 351 |
+
print(f"Decoded Google News URL for image extraction: {decoded_link}")
|
| 352 |
+
except Exception as e:
|
| 353 |
+
print(f"Failed to decode Google News URL {link} for image extraction: {e}")
|
| 354 |
+
|
| 355 |
+
og_img = extract_og_image(decoded_link)
|
| 356 |
+
if og_img:
|
| 357 |
+
image_urls.append(og_img)
|
| 358 |
+
|
| 359 |
+
downloaded_images = []
|
| 360 |
+
|
| 361 |
+
# Initialize WatermarkRemover if available
|
| 362 |
+
from pathlib import Path
|
| 363 |
+
remover = WatermarkRemover(Path(ROOT_DIR)) if HAS_REMOVER else None
|
| 364 |
+
|
| 365 |
+
for idx, url in enumerate(image_urls[:2], 1):
|
| 366 |
+
img_filename = f"{safe_title}_img{idx}.jpg"
|
| 367 |
+
img_dest = os.path.join(images_dir, img_filename)
|
| 368 |
+
success = download_file(url, img_dest)
|
| 369 |
+
|
| 370 |
+
if success:
|
| 371 |
+
if not is_valid_image(url, img_dest):
|
| 372 |
+
print(f"Rejected downloaded image as unrelated: {url}")
|
| 373 |
+
if os.path.exists(img_dest):
|
| 374 |
+
try:
|
| 375 |
+
os.remove(img_dest)
|
| 376 |
+
except:
|
| 377 |
+
pass
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
downloaded_images.append(img_dest)
|
| 381 |
+
if remover:
|
| 382 |
+
try:
|
| 383 |
+
remover.remove_watermark(Path(img_dest), decoded_link)
|
| 384 |
+
except Exception as rem_err:
|
| 385 |
+
print(f"Failed to remove watermark for {img_dest}: {rem_err}")
|
| 386 |
+
|
| 387 |
+
# 3. No related video briefing available by default. Omit placeholder.
|
| 388 |
+
video_embed_md = ""
|
| 389 |
+
|
| 390 |
+
# 4. Inject Carousel at the top (right after title or date)
|
| 391 |
+
if downloaded_images:
|
| 392 |
+
lines = article_content.splitlines()
|
| 393 |
+
title_idx = -1
|
| 394 |
+
for i, line in enumerate(lines):
|
| 395 |
+
if line.strip().startswith("# "):
|
| 396 |
+
title_idx = i
|
| 397 |
+
break
|
| 398 |
+
|
| 399 |
+
date_idx = -1
|
| 400 |
+
if title_idx != -1:
|
| 401 |
+
for i in range(title_idx + 1, len(lines)):
|
| 402 |
+
if lines[i].strip():
|
| 403 |
+
date_idx = i
|
| 404 |
+
break
|
| 405 |
+
|
| 406 |
+
insert_idx = -1
|
| 407 |
+
if date_idx != -1:
|
| 408 |
+
insert_idx = date_idx + 1
|
| 409 |
+
elif title_idx != -1:
|
| 410 |
+
insert_idx = title_idx + 1
|
| 411 |
+
|
| 412 |
+
if insert_idx != -1:
|
| 413 |
+
carousel_lines = ["", "```carousel"]
|
| 414 |
+
for j, img_path in enumerate(downloaded_images, 1):
|
| 415 |
+
if j > 1:
|
| 416 |
+
carousel_lines.append("<!-- slide -->")
|
| 417 |
+
carousel_lines.append(f"})")
|
| 418 |
+
carousel_lines.append("```")
|
| 419 |
+
carousel_lines.append("")
|
| 420 |
+
lines = lines[:insert_idx] + carousel_lines + lines[insert_idx:]
|
| 421 |
+
article_content = "\n".join(lines)
|
| 422 |
+
|
| 423 |
+
# 5. Inject Video embed before the footer
|
| 424 |
+
if video_embed_md:
|
| 425 |
+
footer_idx = article_content.rfind("---")
|
| 426 |
+
if footer_idx != -1:
|
| 427 |
+
article_content = article_content[:footer_idx] + video_embed_md + article_content[footer_idx:]
|
| 428 |
+
else:
|
| 429 |
+
article_content += video_embed_md
|
| 430 |
+
|
| 431 |
+
# 6. Inject Source document preview iframe before the footer
|
| 432 |
+
if downloaded_sources:
|
| 433 |
+
sources_preview_md = "\n\n### Original Source Document Previews\n"
|
| 434 |
+
for title_src, uri in downloaded_sources[:3]:
|
| 435 |
+
sources_preview_md += f"#### {title_src}\n<iframe src=\"{uri}\" width=\"100%\" height=\"450px\" style=\"border: 1px solid #ccc; margin-bottom: 20px;\"></iframe>\n"
|
| 436 |
+
|
| 437 |
+
footer_idx = article_content.rfind("---")
|
| 438 |
+
if footer_idx != -1:
|
| 439 |
+
article_content = article_content[:footer_idx] + sources_preview_md + article_content[footer_idx:]
|
| 440 |
+
else:
|
| 441 |
+
article_content += sources_preview_md
|
| 442 |
+
|
| 443 |
+
# 7. Save the final Markdown file inside the article directory
|
| 444 |
+
dest_file_path = os.path.join(article_dir, f"{safe_title}.md")
|
| 445 |
+
try:
|
| 446 |
+
with open(dest_file_path, 'w', encoding='utf-8') as f:
|
| 447 |
+
f.write(article_content)
|
| 448 |
+
print(f"Saved Article successfully: {dest_file_path}")
|
| 449 |
+
|
| 450 |
+
# 7.5. Check if it's Russian, Ukrainian, or independent media to assign S-Tier (tier 1)
|
| 451 |
+
is_s_tier = False
|
| 452 |
+
s_tier_domains = [
|
| 453 |
+
"meduza.io", "themoscowtimes.com", "kyivindependent.com", "pravda.com.ua",
|
| 454 |
+
"novayagazeta.eu", "novayagazeta.ru", "zona.media", "mediazona.ca",
|
| 455 |
+
"tvrain.tv", "tvrain.ru", "istories.media", "theins.ru", "theins.press",
|
| 456 |
+
"verstka.media", "currenttime.tv", "rferl.org", "unian.net", "unian.info",
|
| 457 |
+
"euromaidanpress.com", "ukrinform.net", "ukrinform.ua", "hromadske.ua"
|
| 458 |
+
]
|
| 459 |
+
link_lower = link.lower()
|
| 460 |
+
decoded_link_lower = decoded_link.lower()
|
| 461 |
+
if any(domain in link_lower or domain in decoded_link_lower for domain in s_tier_domains):
|
| 462 |
+
is_s_tier = True
|
| 463 |
+
|
| 464 |
+
if is_s_tier:
|
| 465 |
+
meta_dest = os.path.join(article_dir, f"{safe_title}.json")
|
| 466 |
+
try:
|
| 467 |
+
with open(meta_dest, 'w', encoding='utf-8') as mf:
|
| 468 |
+
json.dump({
|
| 469 |
+
"importance": 9,
|
| 470 |
+
"urgency": 9,
|
| 471 |
+
"tier": 1
|
| 472 |
+
}, mf, indent=4)
|
| 473 |
+
print(f"Automatically assigned S-Tier (tier 1) for independent RU/UA source: {meta_dest}")
|
| 474 |
+
except Exception as e:
|
| 475 |
+
print(f"Failed to write S-Tier metadata for {safe_title}: {e}")
|
| 476 |
+
|
| 477 |
+
return True
|
| 478 |
+
except Exception as e:
|
| 479 |
+
print(f"Failed to save article {safe_title}: {e}")
|
| 480 |
+
return False
|
| 481 |
+
|
| 482 |
+
def main():
|
| 483 |
+
print(f"Starting finalization at {datetime.now().isoformat()}")
|
| 484 |
+
synthesis_data = load_json(SYNTHESIS_FILE, [])
|
| 485 |
+
if not synthesis_data:
|
| 486 |
+
print("No synthesis data found. Exiting.")
|
| 487 |
+
return []
|
| 488 |
+
|
| 489 |
+
history = load_json(HISTORY_FILE, {})
|
| 490 |
+
pending_list = load_json(PENDING_FILE, [])
|
| 491 |
+
|
| 492 |
+
processed_count = 0
|
| 493 |
+
newly_processed_urls = set()
|
| 494 |
+
finalized_dirs = []
|
| 495 |
+
|
| 496 |
+
for article_dict in synthesis_data:
|
| 497 |
+
category = article_dict.get("category")
|
| 498 |
+
title = article_dict.get("title")
|
| 499 |
+
link = article_dict.get("link")
|
| 500 |
+
markdown = article_dict.get("markdown")
|
| 501 |
+
source_file = article_dict.get("source_file")
|
| 502 |
+
|
| 503 |
+
if not markdown or not link:
|
| 504 |
+
continue
|
| 505 |
+
|
| 506 |
+
success = finalize_article(category, title, link, markdown, source_file)
|
| 507 |
+
if success:
|
| 508 |
+
processed_count += 1
|
| 509 |
+
newly_processed_urls.add(link)
|
| 510 |
+
history[link] = {
|
| 511 |
+
"title": title,
|
| 512 |
+
"collected_at": datetime.now().isoformat(),
|
| 513 |
+
"category": category
|
| 514 |
+
}
|
| 515 |
+
# Reconstruct the exact path where the article was finalized
|
| 516 |
+
safe_title = safe_filename(title)
|
| 517 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 518 |
+
lang = "ja-JP" if is_ja else "en-US"
|
| 519 |
+
CAT_MAP = {
|
| 520 |
+
"Business": "Business_and_Economy",
|
| 521 |
+
"World_Affairs": "World_Affairs",
|
| 522 |
+
"General": "General_News",
|
| 523 |
+
"Animals": "Science_and_Animals"
|
| 524 |
+
}
|
| 525 |
+
cat_folder = CAT_MAP.get(category, "Uncategorized")
|
| 526 |
+
article_dir = os.path.join(ROOT_DIR, lang, cat_folder, safe_title)
|
| 527 |
+
finalized_dirs.append(article_dir)
|
| 528 |
+
|
| 529 |
+
if processed_count > 0:
|
| 530 |
+
if len(history) > 2000:
|
| 531 |
+
sorted_keys = sorted(history.keys(), key=lambda k: history[k].get("collected_at", ""))
|
| 532 |
+
for k in sorted_keys[:len(history) - 2000]:
|
| 533 |
+
del history[k]
|
| 534 |
+
save_json(HISTORY_FILE, history)
|
| 535 |
+
|
| 536 |
+
updated_pending = [item for item in pending_list if item["link"] not in newly_processed_urls]
|
| 537 |
+
save_json(PENDING_FILE, updated_pending)
|
| 538 |
+
|
| 539 |
+
print(f"Successfully finalized {processed_count} articles.")
|
| 540 |
+
|
| 541 |
+
# Clean up temp_sources directory if empty
|
| 542 |
+
temp_sources_dir = os.path.join(ROOT_DIR, "temp_sources")
|
| 543 |
+
if os.path.exists(temp_sources_dir):
|
| 544 |
+
try:
|
| 545 |
+
if not os.listdir(temp_sources_dir):
|
| 546 |
+
os.rmdir(temp_sources_dir)
|
| 547 |
+
print("Removed empty temp_sources directory.")
|
| 548 |
+
except Exception as e:
|
| 549 |
+
print(f"Failed to check/remove temp_sources directory: {e}")
|
| 550 |
+
|
| 551 |
+
if os.path.exists(SYNTHESIS_FILE):
|
| 552 |
+
try:
|
| 553 |
+
os.remove(SYNTHESIS_FILE)
|
| 554 |
+
print("Cleared synthesis_output.json")
|
| 555 |
+
except Exception as e:
|
| 556 |
+
print(f"Failed to delete synthesis_output.json: {e}")
|
| 557 |
+
|
| 558 |
+
return finalized_dirs
|
| 559 |
+
|
| 560 |
+
if __name__ == "__main__":
|
| 561 |
+
main()
|
news_collection_and_script_generation/generate_scripts_all.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import argparse
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
# Reconfigure encoding to avoid Windows console encoding issues
|
| 9 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 10 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 11 |
+
|
| 12 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 13 |
+
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import litert_lm
|
| 17 |
+
HAS_LITERT = True
|
| 18 |
+
except ImportError:
|
| 19 |
+
HAS_LITERT = False
|
| 20 |
+
|
| 21 |
+
def clean_for_tts(text):
|
| 22 |
+
lines = text.splitlines()
|
| 23 |
+
cleaned_lines = []
|
| 24 |
+
for line in lines:
|
| 25 |
+
line = line.strip()
|
| 26 |
+
if not line:
|
| 27 |
+
continue
|
| 28 |
+
# Skip headers
|
| 29 |
+
if line.startswith('#'):
|
| 30 |
+
continue
|
| 31 |
+
|
| 32 |
+
# Remove speaker labels like "**Anchor:**" or "**Correspondent (Riga):**" or "Military Analyst:"
|
| 33 |
+
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
|
| 34 |
+
|
| 35 |
+
# Remove parenthetical performance notes or sound effects like (Opening music...) or [Music]
|
| 36 |
+
line = re.sub(r'\([^)]*\)', '', line)
|
| 37 |
+
line = re.sub(r'\[[^\]]*\]', '', line)
|
| 38 |
+
|
| 39 |
+
# Remove markdown bold/italic markers
|
| 40 |
+
line = line.replace('**', '').replace('*', '')
|
| 41 |
+
|
| 42 |
+
# Remove leading/trailing quotes
|
| 43 |
+
line = line.strip()
|
| 44 |
+
if line.startswith('"') and line.endswith('"'):
|
| 45 |
+
line = line[1:-1]
|
| 46 |
+
elif line.startswith('“') and line.endswith('”'):
|
| 47 |
+
line = line[1:-1]
|
| 48 |
+
|
| 49 |
+
line = line.strip()
|
| 50 |
+
if line:
|
| 51 |
+
cleaned_lines.append(line)
|
| 52 |
+
|
| 53 |
+
return '\n\n'.join(cleaned_lines)
|
| 54 |
+
|
| 55 |
+
def detect_japanese(text):
|
| 56 |
+
# Check for Hiragana (0x3040-0x309F), Katakana (0x30A0-0x30FF), or Kanji (0x4E00-0x9FFF)
|
| 57 |
+
for char in text:
|
| 58 |
+
cp = ord(char)
|
| 59 |
+
if (0x3040 <= cp <= 0x309F) or (0x30A0 <= cp <= 0x30FF) or (0x4E00 <= cp <= 0x9FFF):
|
| 60 |
+
return True
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
def generate_script_prompt(article_title, article_content, length_type, is_ja):
|
| 64 |
+
lang_name = "Japanese" if is_ja else "English"
|
| 65 |
+
is_very_short = len(article_content.strip()) < 300
|
| 66 |
+
|
| 67 |
+
if length_type == "short":
|
| 68 |
+
word_limit = "100 words" if is_very_short else "200 words"
|
| 69 |
+
elif length_type == "middle":
|
| 70 |
+
word_limit = "200 words" if is_very_short else "400 words"
|
| 71 |
+
else: # long
|
| 72 |
+
word_limit = "400 words" if is_very_short else "800-1000 words"
|
| 73 |
+
|
| 74 |
+
# Common rules for anchor script
|
| 75 |
+
if is_ja:
|
| 76 |
+
rules = """1. スクリプトは日本語で書いてください。
|
| 77 |
+
2. ニュースキャスターが声に出して読み上げるのに適した、自然で分かりやすい話し言葉(です・ます調)にしてください。
|
| 78 |
+
3. 主観的な解説や、「この記事は~」「この記事が強調するように~」といったメタ的な表現(記事そのものに言及する表現)は絶対に含めないでください。あなた自身がニュースを直接伝えているキャスターであるかのように描写してください。
|
| 79 |
+
4. 「これは〜を示唆しています」「この状況は〜という複雑な現実を浮き彫りにしています」のような学術的・分析的な表現は避け、事実と状況をストレートに伝えてください。
|
| 80 |
+
5. 自然な導入フレーズ(例:「こんばんは。本日お伝えするニュースは、」など)で始め、最後は「アンドロイド・タイムズがお伝えしました。」という結びの言葉で終わらせてください。
|
| 81 |
+
6. 単一のキャスターが連続して読み上げる形式にしてください。対話形式やヘッダー(「導入」「背景」など)、話者ラベル(「キャスター:」「ナレーター:」など)は含めないでください。"""
|
| 82 |
+
else:
|
| 83 |
+
rules = """1. Write the script in clear, spoken English, suitable for reading aloud.
|
| 84 |
+
2. Use a professional yet conversational tone, typical of international news broadcasts.
|
| 85 |
+
3. Act as if YOU are reporting the news firsthand as a live anchor. Crucially, do NOT say "The article says", "The article highlights", "According to the article", "This report", or refer to the text/article itself in any metatextual way.
|
| 86 |
+
4. Avoid analytical or academic phrasing like "This suggests...", "The narrative...", "This highlights...". Focus only on the facts and developments of the event.
|
| 87 |
+
5. Begin the script with a natural introductory phrase (e.g., "Good evening. Today, we turn to..." or "Tonight, we have an important update regarding...").
|
| 88 |
+
6. Sign-off by explicitly saying a closing phrase such as "Reporting for The Android Times."
|
| 89 |
+
7. Crucially, do NOT include any speaker labels (e.g., do NOT write '**Anchor:**', '**Reporter:**', etc.) or section headers. Just output the clean script text. Do not wrap paragraphs in quotation marks.
|
| 90 |
+
8. Ensure correct grammar and natural phrasing. Do not omit necessary articles (e.g., say "An airstrike..." instead of "Airstrike...")."""
|
| 91 |
+
|
| 92 |
+
prompt = f"""You are a professional news anchor.
|
| 93 |
+
Write a {length_type}-length news script (about {word_limit}) in {lang_name} based on the following article.
|
| 94 |
+
{"Since the article content is extremely brief, expand on the potential implications and general context of this news." if is_very_short and length_type == "long" else ""}
|
| 95 |
+
The script should be optimized for a news broadcast voiceover.
|
| 96 |
+
|
| 97 |
+
Article Title: {article_title}
|
| 98 |
+
Article Content:
|
| 99 |
+
{article_content}
|
| 100 |
+
|
| 101 |
+
Requirements:
|
| 102 |
+
{rules}
|
| 103 |
+
Keep it to approximately {word_limit} (or equivalent length in Japanese).
|
| 104 |
+
Return only the script content. Do not include any introductory or concluding chat remarks or code block formatting (like ```).
|
| 105 |
+
"""
|
| 106 |
+
return prompt
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def strip_forbidden_labels(text):
|
| 110 |
+
forbidden_patterns = [
|
| 111 |
+
r'^([\s\*\-]*)\**Anchor\b:\**\s*',
|
| 112 |
+
r'^([\s\*\-]*)\**Reporter\b:\**\s*',
|
| 113 |
+
r'^([\s\*\-]*)\**Correspondent\b:\**\s*',
|
| 114 |
+
r'^([\s\*\-]*)\**Presenter\b:\**\s*',
|
| 115 |
+
r'^([\s\*\-]*)\**Narrator\b:\**\s*',
|
| 116 |
+
r'^([\s\*\-]*)\**Host\b:\**\s*',
|
| 117 |
+
r'^([\s\*\-]*)\**Voiceover\b:\**\s*'
|
| 118 |
+
]
|
| 119 |
+
lines = text.splitlines()
|
| 120 |
+
cleaned_lines = []
|
| 121 |
+
for line in lines:
|
| 122 |
+
cleaned_line = line
|
| 123 |
+
for pattern in forbidden_patterns:
|
| 124 |
+
cleaned_line = re.sub(pattern, r'\1', cleaned_line, flags=re.IGNORECASE)
|
| 125 |
+
cleaned_lines.append(cleaned_line)
|
| 126 |
+
return '\n'.join(cleaned_lines)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def process_article(engine, article_dir, force):
|
| 130 |
+
dir_name = os.path.basename(article_dir)
|
| 131 |
+
print(f"\nProcessing article directory: {dir_name}")
|
| 132 |
+
|
| 133 |
+
# Find the main article file (same name as directory, or ends with .md but not a script)
|
| 134 |
+
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md")]
|
| 135 |
+
main_article_file = None
|
| 136 |
+
for f in md_files:
|
| 137 |
+
if not f.endswith(("script_short.md", "script_middle.md", "script_long.md", "script_normal.md", "script.md")):
|
| 138 |
+
main_article_file = f
|
| 139 |
+
break
|
| 140 |
+
|
| 141 |
+
if not main_article_file:
|
| 142 |
+
# Fallback: search for any .md file
|
| 143 |
+
for f in md_files:
|
| 144 |
+
main_article_file = f
|
| 145 |
+
break
|
| 146 |
+
|
| 147 |
+
if not main_article_file:
|
| 148 |
+
print(f"Error: No main markdown file found in {dir_name}. Skipping.")
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
main_article_path = os.path.join(article_dir, main_article_file)
|
| 152 |
+
try:
|
| 153 |
+
with open(main_article_path, 'r', encoding='utf-8') as f:
|
| 154 |
+
article_content = f.read().strip()
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print(f"Error reading {main_article_path}: {e}. Skipping.")
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
# Get article title
|
| 160 |
+
title_m = re.match(r'^#\s+(.+)$', article_content.splitlines()[0])
|
| 161 |
+
article_title = title_m.group(1) if title_m else dir_name
|
| 162 |
+
|
| 163 |
+
is_ja = detect_japanese(article_content)
|
| 164 |
+
print(f"Detected language: {'Japanese' if is_ja else 'English'}")
|
| 165 |
+
|
| 166 |
+
lengths = ["short", "middle", "long"]
|
| 167 |
+
generated_any = False
|
| 168 |
+
|
| 169 |
+
for length in lengths:
|
| 170 |
+
script_file_name = f"script_{length}.md"
|
| 171 |
+
script_path = os.path.join(article_dir, script_file_name)
|
| 172 |
+
txt_file_name = f"script_{length}_clean.txt"
|
| 173 |
+
txt_path = os.path.join(article_dir, txt_file_name)
|
| 174 |
+
|
| 175 |
+
# Check if files already exist
|
| 176 |
+
if os.path.exists(script_path) and os.path.exists(txt_path) and not force:
|
| 177 |
+
print(f" {length} script and TTS text already exist. Skipping.")
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
print(f" Generating {length} script...")
|
| 181 |
+
prompt = generate_script_prompt(article_title, article_content, length, is_ja)
|
| 182 |
+
|
| 183 |
+
try:
|
| 184 |
+
with engine.create_conversation() as conversation:
|
| 185 |
+
response = conversation.send_message(prompt)
|
| 186 |
+
script_text = response["content"][0]["text"].strip()
|
| 187 |
+
|
| 188 |
+
# Strip forbidden speaker labels from the script markdown itself
|
| 189 |
+
script_text = strip_forbidden_labels(script_text)
|
| 190 |
+
|
| 191 |
+
# Write markdown script
|
| 192 |
+
with open(script_path, 'w', encoding='utf-8') as f:
|
| 193 |
+
f.write(script_text)
|
| 194 |
+
print(f" Saved script: {script_path}")
|
| 195 |
+
|
| 196 |
+
# Clean for TTS and write text file
|
| 197 |
+
clean_text = clean_for_tts(script_text)
|
| 198 |
+
with open(txt_path, 'w', encoding='utf-8') as f:
|
| 199 |
+
f.write(clean_text)
|
| 200 |
+
print(f" Saved TTS text: {txt_path}")
|
| 201 |
+
|
| 202 |
+
generated_any = True
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f" Error generating {length} script: {e}")
|
| 205 |
+
|
| 206 |
+
return generated_any
|
| 207 |
+
|
| 208 |
+
def main():
|
| 209 |
+
parser = argparse.ArgumentParser(description="Batch generate news scripts and clean TTS text files for all articles.")
|
| 210 |
+
parser.add_argument("--limit", type=int, default=5, help="Maximum number of articles to process in this run. Default is 5.")
|
| 211 |
+
parser.add_argument("--category", type=str, default=None, help="Process only a specific category (e.g. World_Affairs).")
|
| 212 |
+
parser.add_argument("--locale", type=str, default=None, help="Process only a specific locale (e.g. en-US, ja-JP).")
|
| 213 |
+
parser.add_argument("--force", action="store_true", help="Force regeneration of scripts even if they exist.")
|
| 214 |
+
parser.add_argument("--all", action="store_true", help="Process all articles without limit.")
|
| 215 |
+
parser.add_argument("--gpu", action="store_true", help="Use GPU backend for inference.")
|
| 216 |
+
args = parser.parse_args()
|
| 217 |
+
|
| 218 |
+
if not HAS_LITERT:
|
| 219 |
+
print("Error: litert_lm package is not installed. Please check environment.")
|
| 220 |
+
sys.exit(1)
|
| 221 |
+
|
| 222 |
+
if not os.path.exists(LITERT_MODEL_PATH):
|
| 223 |
+
print(f"Error: Model not found at {LITERT_MODEL_PATH}")
|
| 224 |
+
sys.exit(1)
|
| 225 |
+
|
| 226 |
+
# Scan article directories
|
| 227 |
+
locales = [args.locale] if args.locale else ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 228 |
+
article_dirs = []
|
| 229 |
+
|
| 230 |
+
for locale in locales:
|
| 231 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 232 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 233 |
+
continue
|
| 234 |
+
|
| 235 |
+
categories = [args.category] if args.category else os.listdir(locale_path)
|
| 236 |
+
for category in categories:
|
| 237 |
+
if category in ["__pycache__"]:
|
| 238 |
+
continue
|
| 239 |
+
cat_path = os.path.join(locale_path, category)
|
| 240 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 241 |
+
continue
|
| 242 |
+
|
| 243 |
+
articles = os.listdir(cat_path)
|
| 244 |
+
for article in articles:
|
| 245 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 246 |
+
continue
|
| 247 |
+
article_path = os.path.join(cat_path, article)
|
| 248 |
+
if os.path.isdir(article_path):
|
| 249 |
+
# Check if it has a main markdown file
|
| 250 |
+
md_files = [f for f in os.listdir(article_path) if f.endswith(".md")]
|
| 251 |
+
if md_files:
|
| 252 |
+
article_dirs.append(article_path)
|
| 253 |
+
|
| 254 |
+
def get_priority_score(article_dir):
|
| 255 |
+
path_lower = article_dir.lower()
|
| 256 |
+
score = 0
|
| 257 |
+
if "en-us" in path_lower:
|
| 258 |
+
score += 10000
|
| 259 |
+
if "en-us" in path_lower and "moscow_attacks" in path_lower:
|
| 260 |
+
score += 1000
|
| 261 |
+
elif "moscow_attacks" in path_lower:
|
| 262 |
+
score += 500
|
| 263 |
+
elif "war_and_military" in path_lower:
|
| 264 |
+
score += 400
|
| 265 |
+
|
| 266 |
+
# War-related keywords in English and Japanese
|
| 267 |
+
war_keywords = [
|
| 268 |
+
"war", "military", "conflict", "attack", "bombing", "invasion",
|
| 269 |
+
"soldier", "battle", "clash", "defense", "missile", "drone",
|
| 270 |
+
"bomb", "strike", "shelling", "army", "troop", "nato", "putin",
|
| 271 |
+
"ukraine", "russia", "kremlin", "pentagon", "blasts",
|
| 272 |
+
"戦争", "軍事", "衝突", "攻撃", "爆撃", "侵攻", "兵士", "戦闘",
|
| 273 |
+
"ミサイル", "ドローン", "爆発", "ウクライナ", "ロシア", "プーチン"
|
| 274 |
+
]
|
| 275 |
+
if any(kw in path_lower for kw in war_keywords):
|
| 276 |
+
score += 200
|
| 277 |
+
return score
|
| 278 |
+
|
| 279 |
+
# Sort by priority score descending first, then by modification time descending
|
| 280 |
+
article_dirs.sort(key=lambda x: (get_priority_score(x), os.path.getmtime(x)), reverse=True)
|
| 281 |
+
|
| 282 |
+
print(f"Found total of {len(article_dirs)} articles.")
|
| 283 |
+
|
| 284 |
+
# Filter directories depending on whether they need processing (unless --force is set)
|
| 285 |
+
dirs_to_process = []
|
| 286 |
+
for d in article_dirs:
|
| 287 |
+
# Check if script_short.md and script_short_clean.txt etc. exist
|
| 288 |
+
all_exist = True
|
| 289 |
+
for length in ["short", "middle", "long"]:
|
| 290 |
+
script_path = os.path.join(d, f"script_{length}.md")
|
| 291 |
+
txt_path = os.path.join(d, f"script_{length}_clean.txt")
|
| 292 |
+
if not os.path.exists(script_path) or not os.path.exists(txt_path):
|
| 293 |
+
all_exist = False
|
| 294 |
+
break
|
| 295 |
+
if not all_exist or args.force:
|
| 296 |
+
dirs_to_process.append(d)
|
| 297 |
+
|
| 298 |
+
print(f"Articles requiring script generation: {len(dirs_to_process)}")
|
| 299 |
+
|
| 300 |
+
if not dirs_to_process:
|
| 301 |
+
print("All articles already have scripts. Use --force to regenerate.")
|
| 302 |
+
return
|
| 303 |
+
|
| 304 |
+
# Apply limit
|
| 305 |
+
limit = len(dirs_to_process) if args.all else args.limit
|
| 306 |
+
dirs_to_process = dirs_to_process[:limit]
|
| 307 |
+
print(f"Will process {len(dirs_to_process)} articles in this run.")
|
| 308 |
+
|
| 309 |
+
# Helper to check GPU utilization
|
| 310 |
+
def is_gpu_busy(threshold_util=25):
|
| 311 |
+
import subprocess
|
| 312 |
+
try:
|
| 313 |
+
output = subprocess.check_output(
|
| 314 |
+
['nvidia-smi', '--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'],
|
| 315 |
+
stderr=subprocess.DEVNULL
|
| 316 |
+
).decode().strip()
|
| 317 |
+
util = int(output.strip())
|
| 318 |
+
return util > threshold_util
|
| 319 |
+
except Exception:
|
| 320 |
+
return False
|
| 321 |
+
|
| 322 |
+
processed_count = 0
|
| 323 |
+
|
| 324 |
+
for idx, article_dir in enumerate(dirs_to_process, 1):
|
| 325 |
+
print(f"\n--- Article {idx}/{len(dirs_to_process)} ---")
|
| 326 |
+
|
| 327 |
+
# Select backend dynamically based on GPU load
|
| 328 |
+
current_backend = litert_lm.Backend.CPU
|
| 329 |
+
backend_name = "CPU"
|
| 330 |
+
if args.gpu:
|
| 331 |
+
if is_gpu_busy():
|
| 332 |
+
print("GPU is currently busy (utilization > 25%). Falling back to CPU backend for this article to avoid contention and timeouts.")
|
| 333 |
+
else:
|
| 334 |
+
current_backend = litert_lm.Backend.GPU
|
| 335 |
+
backend_name = "GPU"
|
| 336 |
+
|
| 337 |
+
print(f"Loading LiteRT-LM Engine with Gemma-4 model on {backend_name}...")
|
| 338 |
+
try:
|
| 339 |
+
with litert_lm.Engine(LITERT_MODEL_PATH, backend=current_backend, max_num_tokens=8192) as engine:
|
| 340 |
+
success = process_article(engine, article_dir, args.force)
|
| 341 |
+
if success:
|
| 342 |
+
processed_count += 1
|
| 343 |
+
except Exception as engine_err:
|
| 344 |
+
print(f"LiteRT-LM engine error for article {idx}: {engine_err}")
|
| 345 |
+
|
| 346 |
+
print(f"\nFinished. Successfully generated scripts for {processed_count} articles.")
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
main()
|
news_collection_and_script_generation/generator_task_config.xml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-16"?>
|
| 2 |
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
| 3 |
+
<RegistrationInfo>
|
| 4 |
+
<Date>2026-07-09T17:45:00</Date>
|
| 5 |
+
<Author>AntigravityAI</Author>
|
| 6 |
+
<Description>Automatically generate English (US) news scripts using LiteRT-LM (Gemma-4) every 15 minutes.</Description>
|
| 7 |
+
</RegistrationInfo>
|
| 8 |
+
<Triggers>
|
| 9 |
+
<LogonTrigger>
|
| 10 |
+
<Enabled>true</Enabled>
|
| 11 |
+
<Repetition>
|
| 12 |
+
<Interval>PT15M</Interval>
|
| 13 |
+
<StopAtDurationEnd>false</StopAtDurationEnd>
|
| 14 |
+
</Repetition>
|
| 15 |
+
</LogonTrigger>
|
| 16 |
+
</Triggers>
|
| 17 |
+
<Principals>
|
| 18 |
+
<Principal id="Author">
|
| 19 |
+
<LogonType>InteractiveToken</LogonType>
|
| 20 |
+
<RunLevel>LeastPrivilege</RunLevel>
|
| 21 |
+
</Principal>
|
| 22 |
+
</Principals>
|
| 23 |
+
<Settings>
|
| 24 |
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
| 25 |
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
| 26 |
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
| 27 |
+
<AllowHardTerminate>true</AllowHardTerminate>
|
| 28 |
+
<StartWhenAvailable>true</StartWhenAvailable>
|
| 29 |
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
| 30 |
+
<IdleSettings>
|
| 31 |
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
| 32 |
+
<RestartOnIdle>false</RestartOnIdle>
|
| 33 |
+
</IdleSettings>
|
| 34 |
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
| 35 |
+
<Enabled>true</Enabled>
|
| 36 |
+
<Hidden>false</Hidden>
|
| 37 |
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
| 38 |
+
<WakeToRun>false</WakeToRun>
|
| 39 |
+
<ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
|
| 40 |
+
<Priority>7</Priority>
|
| 41 |
+
</Settings>
|
| 42 |
+
<Actions Context="Author">
|
| 43 |
+
<Exec>
|
| 44 |
+
<Command>wscript.exe</Command>
|
| 45 |
+
<Arguments>C:\ComfyUI\Articles\run_generator_silent.vbs</Arguments>
|
| 46 |
+
</Exec>
|
| 47 |
+
</Actions>
|
| 48 |
+
</Task>
|
news_collection_and_script_generation/quality_gate_articles.py
ADDED
|
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
import difflib
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import litert_lm
|
| 10 |
+
except ImportError:
|
| 11 |
+
litert_lm = None
|
| 12 |
+
|
| 13 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 14 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 15 |
+
|
| 16 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 17 |
+
SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json")
|
| 18 |
+
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
|
| 19 |
+
|
| 20 |
+
def get_existing_article_titles():
|
| 21 |
+
"""
|
| 22 |
+
Scan category directories under locales (en-US, en-EU, ja-JP) to collect
|
| 23 |
+
existing sanitized titles/folder names for duplicate detection.
|
| 24 |
+
"""
|
| 25 |
+
titles = set()
|
| 26 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 27 |
+
for locale in locales:
|
| 28 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 29 |
+
if not os.path.exists(loc_path):
|
| 30 |
+
continue
|
| 31 |
+
for cat in os.listdir(loc_path):
|
| 32 |
+
cat_path = os.path.join(loc_path, cat)
|
| 33 |
+
if not os.path.isdir(cat_path) or cat == "__pycache__":
|
| 34 |
+
continue
|
| 35 |
+
for art in os.listdir(cat_path):
|
| 36 |
+
art_path = os.path.join(cat_path, art)
|
| 37 |
+
if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]:
|
| 38 |
+
titles.add(art.lower())
|
| 39 |
+
titles.add(art.replace('_', ' ').lower())
|
| 40 |
+
return titles
|
| 41 |
+
|
| 42 |
+
def is_duplicate(new_title, existing_titles, current_batch_titles, threshold=0.8):
|
| 43 |
+
"""
|
| 44 |
+
Check if a new article title is a duplicate of past articles or current batch.
|
| 45 |
+
Uses SequenceMatcher ratio with a length-difference speed filter.
|
| 46 |
+
"""
|
| 47 |
+
new_title_clean = new_title.strip().lower()
|
| 48 |
+
|
| 49 |
+
# 1. Exact matches
|
| 50 |
+
if new_title_clean in existing_titles or new_title_clean in current_batch_titles:
|
| 51 |
+
return True, "Exact title match"
|
| 52 |
+
|
| 53 |
+
# 2. Similarity checks against existing articles
|
| 54 |
+
for ext_title in existing_titles:
|
| 55 |
+
# Fast optimization: skip if length difference is too large
|
| 56 |
+
if abs(len(new_title_clean) - len(ext_title)) > max(10, len(new_title_clean) * 0.4):
|
| 57 |
+
continue
|
| 58 |
+
ratio = difflib.SequenceMatcher(None, new_title_clean, ext_title).ratio()
|
| 59 |
+
if ratio >= threshold:
|
| 60 |
+
return True, f"High similarity ({int(ratio*100)}%) with existing article: '{ext_title}'"
|
| 61 |
+
|
| 62 |
+
# 3. Similarity checks against current batch
|
| 63 |
+
for cur_title in current_batch_titles:
|
| 64 |
+
if abs(len(new_title_clean) - len(cur_title)) > max(10, len(new_title_clean) * 0.4):
|
| 65 |
+
continue
|
| 66 |
+
ratio = difflib.SequenceMatcher(None, new_title_clean, cur_title).ratio()
|
| 67 |
+
if ratio >= threshold:
|
| 68 |
+
return True, f"High similarity ({int(ratio*100)}%) with another article in this batch: '{cur_title}'"
|
| 69 |
+
|
| 70 |
+
return False, ""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def clean_article_text(markdown_content):
|
| 74 |
+
"""
|
| 75 |
+
Remove markdown headers, metadata lines, image embeds, links, and common footers
|
| 76 |
+
to extract the pure body text of the article for similarity comparison.
|
| 77 |
+
"""
|
| 78 |
+
if not markdown_content:
|
| 79 |
+
return ""
|
| 80 |
+
|
| 81 |
+
lines = markdown_content.splitlines()
|
| 82 |
+
cleaned_lines = []
|
| 83 |
+
|
| 84 |
+
for line in lines:
|
| 85 |
+
line_strip = line.strip()
|
| 86 |
+
if not line_strip:
|
| 87 |
+
continue
|
| 88 |
+
if line_strip.startswith("#"):
|
| 89 |
+
continue
|
| 90 |
+
if line_strip.startswith("**Category:**") or line_strip.startswith("**Locale:**") or line_strip.startswith("**Source:**") or line_strip.startswith("**Date Collected:**"):
|
| 91 |
+
continue
|
| 92 |
+
if line_strip.startswith("!["):
|
| 93 |
+
continue
|
| 94 |
+
if line_strip == "---":
|
| 95 |
+
continue
|
| 96 |
+
if "*This article was automatically collected" in line_strip or "scraped" in line_strip.lower():
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
cleaned_lines.append(line_strip)
|
| 100 |
+
|
| 101 |
+
text = " ".join(cleaned_lines)
|
| 102 |
+
text = re.sub(r'<[^>]+>', '', text)
|
| 103 |
+
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
|
| 104 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 105 |
+
return text
|
| 106 |
+
|
| 107 |
+
def get_recent_article_bodies(max_per_category=30):
|
| 108 |
+
"""
|
| 109 |
+
Scan category directories under locales (en-US, en-EU, ja-JP) to collect
|
| 110 |
+
recent articles' markdown file paths, read their content, and return a dict of {title: cleaned_body}.
|
| 111 |
+
"""
|
| 112 |
+
recent_bodies = {}
|
| 113 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 114 |
+
for locale in locales:
|
| 115 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 116 |
+
if not os.path.exists(loc_path):
|
| 117 |
+
continue
|
| 118 |
+
for cat in os.listdir(loc_path):
|
| 119 |
+
cat_path = os.path.join(loc_path, cat)
|
| 120 |
+
if not os.path.isdir(cat_path) or cat == "__pycache__":
|
| 121 |
+
continue
|
| 122 |
+
|
| 123 |
+
articles = []
|
| 124 |
+
for art in os.listdir(cat_path):
|
| 125 |
+
art_path = os.path.join(cat_path, art)
|
| 126 |
+
if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]:
|
| 127 |
+
try:
|
| 128 |
+
mtime = os.path.getmtime(art_path)
|
| 129 |
+
articles.append((art, art_path, mtime))
|
| 130 |
+
except Exception:
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
articles.sort(key=lambda x: x[2], reverse=True)
|
| 134 |
+
for art, art_path, _ in articles[:max_per_category]:
|
| 135 |
+
md_file_name = f"{art}.md"
|
| 136 |
+
md_file_path = os.path.join(art_path, md_file_name)
|
| 137 |
+
if os.path.exists(md_file_path):
|
| 138 |
+
try:
|
| 139 |
+
with open(md_file_path, "r", encoding="utf-8") as f:
|
| 140 |
+
content = f.read()
|
| 141 |
+
cleaned = clean_article_text(content)
|
| 142 |
+
if cleaned:
|
| 143 |
+
recent_bodies[art.lower()] = cleaned
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"Error reading past article {md_file_path}: {e}")
|
| 146 |
+
return recent_bodies
|
| 147 |
+
|
| 148 |
+
def get_words(text):
|
| 149 |
+
"""
|
| 150 |
+
Extract alphanumeric words from text and normalize to lowercase.
|
| 151 |
+
For Japanese, extract character bi-grams (2-character pairs) to improve similarity precision.
|
| 152 |
+
"""
|
| 153 |
+
text_lower = text.lower()
|
| 154 |
+
is_ja = any(ord(char) > 0x3000 for char in text_lower)
|
| 155 |
+
if is_ja:
|
| 156 |
+
cleaned_chars = [char for char in text_lower if char.isalnum() and not char.isspace()]
|
| 157 |
+
bigrams = set()
|
| 158 |
+
for i in range(len(cleaned_chars) - 1):
|
| 159 |
+
bigrams.add(cleaned_chars[i] + cleaned_chars[i+1])
|
| 160 |
+
return bigrams
|
| 161 |
+
else:
|
| 162 |
+
return set(re.findall(r'\b[a-z0-9]+\b', text_lower))
|
| 163 |
+
|
| 164 |
+
def is_content_duplicate(new_text, existing_bodies, current_batch_bodies, jaccard_threshold=0.65, seq_threshold=0.70):
|
| 165 |
+
"""
|
| 166 |
+
Check if the cleaned new_text is a duplicate of existing articles or current batch.
|
| 167 |
+
Uses Jaccard word/bigram similarity as a fast pre-filter, followed by SequenceMatcher on prefix.
|
| 168 |
+
"""
|
| 169 |
+
new_cleaned = clean_article_text(new_text)
|
| 170 |
+
if not new_cleaned:
|
| 171 |
+
return False, ""
|
| 172 |
+
|
| 173 |
+
new_words = get_words(new_cleaned)
|
| 174 |
+
if not new_words:
|
| 175 |
+
return False, ""
|
| 176 |
+
|
| 177 |
+
# Check against existing articles
|
| 178 |
+
for ext_title, ext_body in existing_bodies.items():
|
| 179 |
+
ext_words = get_words(ext_body)
|
| 180 |
+
if not ext_words:
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
intersection = new_words.intersection(ext_words)
|
| 184 |
+
union = new_words.union(ext_words)
|
| 185 |
+
jaccard = len(intersection) / len(union) if union else 0.0
|
| 186 |
+
|
| 187 |
+
# Fast early-exit: Jaccard similarity must be at least 0.35 to be a candidate
|
| 188 |
+
if jaccard < 0.35:
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
new_prefix = new_cleaned[:1000]
|
| 192 |
+
ext_prefix = ext_body[:1000]
|
| 193 |
+
ratio = difflib.SequenceMatcher(None, new_prefix, ext_prefix).ratio()
|
| 194 |
+
|
| 195 |
+
# Strict AND condition to minimize false positives
|
| 196 |
+
if jaccard >= jaccard_threshold and ratio >= seq_threshold:
|
| 197 |
+
reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with existing article: '{ext_title}'"
|
| 198 |
+
return True, reason
|
| 199 |
+
|
| 200 |
+
# Check against current batch
|
| 201 |
+
for cur_title, cur_body in current_batch_bodies.items():
|
| 202 |
+
cur_words = get_words(cur_body)
|
| 203 |
+
if not cur_words:
|
| 204 |
+
continue
|
| 205 |
+
|
| 206 |
+
intersection = new_words.intersection(cur_words)
|
| 207 |
+
union = new_words.union(cur_words)
|
| 208 |
+
jaccard = len(intersection) / len(union) if union else 0.0
|
| 209 |
+
|
| 210 |
+
# Fast early-exit
|
| 211 |
+
if jaccard < 0.35:
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
new_prefix = new_cleaned[:1000]
|
| 215 |
+
cur_prefix = cur_body[:1000]
|
| 216 |
+
ratio = difflib.SequenceMatcher(None, new_prefix, cur_prefix).ratio()
|
| 217 |
+
|
| 218 |
+
# Strict AND condition
|
| 219 |
+
if jaccard >= jaccard_threshold and ratio >= seq_threshold:
|
| 220 |
+
reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with another article in this batch: '{cur_title}'"
|
| 221 |
+
return True, reason
|
| 222 |
+
|
| 223 |
+
return False, ""
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def load_json(path, default):
|
| 228 |
+
if os.path.exists(path):
|
| 229 |
+
try:
|
| 230 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 231 |
+
return json.load(f)
|
| 232 |
+
except Exception as e:
|
| 233 |
+
print(f"Failed to load JSON {path}: {e}")
|
| 234 |
+
return default
|
| 235 |
+
|
| 236 |
+
def save_json(path, data):
|
| 237 |
+
try:
|
| 238 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 239 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 240 |
+
except Exception as e:
|
| 241 |
+
print(f"Failed to save JSON {path}: {e}")
|
| 242 |
+
|
| 243 |
+
def evaluate_raw_markdown(markdown_content):
|
| 244 |
+
"""
|
| 245 |
+
Perform fast, hard-coded checks before sending to LLM.
|
| 246 |
+
Returns (is_valid: bool, reason: str)
|
| 247 |
+
"""
|
| 248 |
+
# 1. Length check
|
| 249 |
+
if len(markdown_content) < 150:
|
| 250 |
+
return False, "Article is too short (< 150 chars). Likely a scraping error or stub."
|
| 251 |
+
|
| 252 |
+
# 2. Regex Check: Scraping Errors
|
| 253 |
+
error_patterns = [
|
| 254 |
+
r"403\s+forbidden",
|
| 255 |
+
r"access\s+denied",
|
| 256 |
+
r"enable\s+javascript",
|
| 257 |
+
r"please\s+enable\s+cookies",
|
| 258 |
+
r"cloudflare",
|
| 259 |
+
r"captcha",
|
| 260 |
+
r"are\s+you\s+a\s+robot"
|
| 261 |
+
]
|
| 262 |
+
for pattern in error_patterns:
|
| 263 |
+
if re.search(pattern, markdown_content, re.IGNORECASE):
|
| 264 |
+
return False, f"Matches scraping error signature: '{pattern}'"
|
| 265 |
+
|
| 266 |
+
return True, "Pass"
|
| 267 |
+
|
| 268 |
+
def build_proofread_prompt(article_markdown):
|
| 269 |
+
prompt = f"""You are a strict News Quality Gatekeeper and Proofreader.
|
| 270 |
+
Your task is to evaluate the following scraped text.
|
| 271 |
+
|
| 272 |
+
Instructions:
|
| 273 |
+
1. If the text is an error page, a privacy policy, a captcha request, or pure spam, reply strictly and ONLY with the text: "REJECT: [Reason]".
|
| 274 |
+
2. If it is a valid news article, review it for grammatical correctness, natural flow, and factual consistency.
|
| 275 |
+
3. PRESERVE the exact formatting of the article, including Markdown headings (#, ##), bullets, and the footer section ("---" and below containing Author and Sources).
|
| 276 |
+
4. Output ONLY the corrected markdown text or the REJECT signal. Do not include any introductory or concluding remarks.
|
| 277 |
+
|
| 278 |
+
Article to evaluate:
|
| 279 |
+
{article_markdown}
|
| 280 |
+
"""
|
| 281 |
+
return prompt
|
| 282 |
+
|
| 283 |
+
def main():
|
| 284 |
+
print(f"Starting Quality Gate (READY_FOR_NEWS Evaluation) at {datetime.now().isoformat()}")
|
| 285 |
+
|
| 286 |
+
synthesis_data = load_json(SYNTHESIS_FILE, [])
|
| 287 |
+
if not synthesis_data:
|
| 288 |
+
print("No synthesis data found. Exiting Quality Gate.")
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
print(f"Total articles pending evaluation: {len(synthesis_data)}")
|
| 292 |
+
|
| 293 |
+
if not litert_lm:
|
| 294 |
+
print("litert_lm module not found. Falling back to hard-filters only.")
|
| 295 |
+
engine = None
|
| 296 |
+
else:
|
| 297 |
+
print(f"Loading LiteRT-LM engine for deep evaluation: {LITERT_MODEL_PATH}")
|
| 298 |
+
try:
|
| 299 |
+
engine = litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.CPU, max_num_tokens=8192)
|
| 300 |
+
except Exception as e:
|
| 301 |
+
print(f"LiteRT-LM Engine failure: {e}. Falling back to hard-filters only.")
|
| 302 |
+
engine = None
|
| 303 |
+
|
| 304 |
+
filtered_synthesis_data = []
|
| 305 |
+
rejected_count = 0
|
| 306 |
+
passed_count = 0
|
| 307 |
+
|
| 308 |
+
# Collect existing titles and bodies once at start
|
| 309 |
+
existing_titles = get_existing_article_titles()
|
| 310 |
+
print("Loading recent article bodies for content duplication check...")
|
| 311 |
+
existing_bodies = get_recent_article_bodies(max_per_category=30)
|
| 312 |
+
print(f"Loaded {len(existing_bodies)} recent article bodies.")
|
| 313 |
+
current_batch_processed_titles = set()
|
| 314 |
+
current_batch_processed_bodies = {} # {title: cleaned_body}
|
| 315 |
+
|
| 316 |
+
try:
|
| 317 |
+
for item in synthesis_data:
|
| 318 |
+
title = item.get("title", "Unknown Title")
|
| 319 |
+
markdown_content = item.get("markdown", "")
|
| 320 |
+
|
| 321 |
+
if not markdown_content:
|
| 322 |
+
print(f"REJECTED '{title}': Empty markdown content.")
|
| 323 |
+
rejected_count += 1
|
| 324 |
+
continue
|
| 325 |
+
|
| 326 |
+
print(f"Evaluating article: '{title}'...")
|
| 327 |
+
|
| 328 |
+
# Step 0: Duplicate Checks
|
| 329 |
+
is_dup, dup_reason = is_duplicate(title, existing_titles, current_batch_processed_titles)
|
| 330 |
+
if is_dup:
|
| 331 |
+
print(f" [REJECTED - Duplicate Title] {dup_reason}")
|
| 332 |
+
rejected_count += 1
|
| 333 |
+
continue
|
| 334 |
+
|
| 335 |
+
is_content_dup, content_dup_reason = is_content_duplicate(
|
| 336 |
+
markdown_content, existing_bodies, current_batch_processed_bodies
|
| 337 |
+
)
|
| 338 |
+
if is_content_dup:
|
| 339 |
+
print(f" [REJECTED - Duplicate Content] {content_dup_reason}")
|
| 340 |
+
rejected_count += 1
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
# Step 1: Hard Filters
|
| 344 |
+
is_valid, reason = evaluate_raw_markdown(markdown_content)
|
| 345 |
+
if not is_valid:
|
| 346 |
+
print(f" [REJECTED by Hard Filter] {reason}")
|
| 347 |
+
rejected_count += 1
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
# Truncate if ridiculously long, but 8192 tokens should be enough
|
| 351 |
+
if len(markdown_content) > 15000:
|
| 352 |
+
print(f" [FLAG] Article is extremely long. Skipping LLM proofread but passing through.")
|
| 353 |
+
item["status"] = "READY_FOR_NEWS"
|
| 354 |
+
filtered_synthesis_data.append(item)
|
| 355 |
+
passed_count += 1
|
| 356 |
+
continue
|
| 357 |
+
|
| 358 |
+
# Step 2: LLM Evaluation
|
| 359 |
+
if engine:
|
| 360 |
+
prompt = build_proofread_prompt(markdown_content)
|
| 361 |
+
try:
|
| 362 |
+
with engine.create_conversation() as conversation:
|
| 363 |
+
response = conversation.send_message(prompt)
|
| 364 |
+
output = response["content"][0]["text"].strip()
|
| 365 |
+
|
| 366 |
+
if output.startswith("REJECT:"):
|
| 367 |
+
print(f" [REJECTED by LLM] {output[7:].strip()}")
|
| 368 |
+
rejected_count += 1
|
| 369 |
+
continue
|
| 370 |
+
|
| 371 |
+
# Basic safety check: if model outputs something extremely short, keep original
|
| 372 |
+
if len(output) > len(markdown_content) * 0.5:
|
| 373 |
+
item["markdown"] = output
|
| 374 |
+
print(f" [PASS] Successfully evaluated and proofread.")
|
| 375 |
+
else:
|
| 376 |
+
print(f" [PASS with Warning] Corrected output seems too short. Using original.")
|
| 377 |
+
|
| 378 |
+
except Exception as model_err:
|
| 379 |
+
print(f" [PASS with Warning] Error during LLM evaluation: {model_err}. Using original text.")
|
| 380 |
+
else:
|
| 381 |
+
print(" [PASS] Evaluated via hard-filter only (LLM offline).")
|
| 382 |
+
|
| 383 |
+
item["status"] = "READY_FOR_NEWS"
|
| 384 |
+
filtered_synthesis_data.append(item)
|
| 385 |
+
current_batch_processed_titles.add(title.strip().lower())
|
| 386 |
+
|
| 387 |
+
# Store cleaned body for future comparisons in the same batch
|
| 388 |
+
cleaned_body = clean_article_text(markdown_content)
|
| 389 |
+
current_batch_processed_bodies[title.strip().lower()] = cleaned_body
|
| 390 |
+
|
| 391 |
+
passed_count += 1
|
| 392 |
+
|
| 393 |
+
finally:
|
| 394 |
+
if engine:
|
| 395 |
+
engine.close()
|
| 396 |
+
|
| 397 |
+
# Save the filtered results, dropping the rejected articles
|
| 398 |
+
if passed_count > 0 or rejected_count > 0:
|
| 399 |
+
save_json(SYNTHESIS_FILE, filtered_synthesis_data)
|
| 400 |
+
print("\n" + "="*40)
|
| 401 |
+
print("Quality Gate (READY_FOR_NEWS) Finished.")
|
| 402 |
+
print(f"Articles Passed: {passed_count}")
|
| 403 |
+
print(f"Articles Rejected & Dropped: {rejected_count}")
|
| 404 |
+
print(f"Filtered data saved to {SYNTHESIS_FILE}")
|
| 405 |
+
print("="*40)
|
| 406 |
+
else:
|
| 407 |
+
print("\nQuality Gate finished. No articles found to process.")
|
| 408 |
+
|
| 409 |
+
if __name__ == "__main__":
|
| 410 |
+
main()
|
news_collection_and_script_generation/run_pipeline_safely.ps1
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# run_pipeline_safely.ps1
|
| 2 |
+
# Runs script generation, media collection, and quality gate copying for all locales sequentially,
|
| 3 |
+
# and sleeps between batches to allow TTS/Video generation on GPU to proceed.
|
| 4 |
+
|
| 5 |
+
$limit = 20
|
| 6 |
+
$sleepSeconds = 90 # Give plenty of time for TTS/video generation to run when GPU is idle
|
| 7 |
+
|
| 8 |
+
Write-Host "=== Safe Coordinated Sequential Pipeline Loop Started ==="
|
| 9 |
+
|
| 10 |
+
while ($true) {
|
| 11 |
+
$locales = @("en-US", "en-EU", "ja-JP")
|
| 12 |
+
$any_remaining = $false
|
| 13 |
+
|
| 14 |
+
foreach ($locale in $locales) {
|
| 15 |
+
Write-Host ""
|
| 16 |
+
Write-Host "========================================"
|
| 17 |
+
Write-Host "Processing Locale: $locale at $(Get-Date -Format 'HH:mm:ss')"
|
| 18 |
+
Write-Host "========================================"
|
| 19 |
+
|
| 20 |
+
# 1. Check remaining count first
|
| 21 |
+
$check = python -c "
|
| 22 |
+
import os
|
| 23 |
+
ROOT_DIR = r'C:\ComfyUI\Articles'
|
| 24 |
+
locale = '$locale'
|
| 25 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 26 |
+
article_dirs = []
|
| 27 |
+
if os.path.exists(loc_path):
|
| 28 |
+
for cat in os.listdir(loc_path):
|
| 29 |
+
if cat == '__pycache__': continue
|
| 30 |
+
cat_path = os.path.join(loc_path, cat)
|
| 31 |
+
if os.path.isdir(cat_path):
|
| 32 |
+
for art in os.listdir(cat_path):
|
| 33 |
+
if art in ['__pycache__', 'images', 'sources']: continue
|
| 34 |
+
art_path = os.path.join(cat_path, art)
|
| 35 |
+
if os.path.isdir(art_path):
|
| 36 |
+
md_files = [f for f in os.listdir(art_path) if f.endswith('.md')]
|
| 37 |
+
if md_files:
|
| 38 |
+
article_dirs.append(art_path)
|
| 39 |
+
dirs_to_process = []
|
| 40 |
+
for d in article_dirs:
|
| 41 |
+
all_exist = True
|
| 42 |
+
for length in ['short', 'middle', 'long']:
|
| 43 |
+
script_path = os.path.join(d, f'script_{length}.md')
|
| 44 |
+
txt_path = os.path.join(d, f'script_{length}_clean.txt')
|
| 45 |
+
if not os.path.exists(script_path) or not os.path.exists(txt_path):
|
| 46 |
+
all_exist = False
|
| 47 |
+
break
|
| 48 |
+
if not all_exist:
|
| 49 |
+
dirs_to_process.append(d)
|
| 50 |
+
print(len(dirs_to_process))
|
| 51 |
+
"
|
| 52 |
+
$remaining = [int]($check.Trim())
|
| 53 |
+
Write-Host "Remaining articles needing scripts in $($locale): $remaining"
|
| 54 |
+
|
| 55 |
+
if ($remaining -gt 0) {
|
| 56 |
+
$any_remaining = $true
|
| 57 |
+
|
| 58 |
+
Write-Host "1. Running script generation (limit $limit, GPU)..."
|
| 59 |
+
$process = Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\generate_scripts_all.py --locale $locale --limit $limit --gpu" -NoNewWindow -PassThru -Wait
|
| 60 |
+
|
| 61 |
+
Write-Host "2. Running media collection..."
|
| 62 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\collect_media_parallel.py --locale $locale" -NoNewWindow -PassThru -Wait
|
| 63 |
+
|
| 64 |
+
Write-Host "3. Running quality gate evaluation and copy..."
|
| 65 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\copy_passed_articles.py --locale $locale" -NoNewWindow -PassThru -Wait
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
if (-not $any_remaining) {
|
| 70 |
+
Write-Host "All locales have 100% of their scripts drafted!"
|
| 71 |
+
# We can still sleep and check again later, or sleep a long time.
|
| 72 |
+
Write-Host "Sleeping for 5 minutes before next check..."
|
| 73 |
+
Start-Sleep -Seconds 300
|
| 74 |
+
} else {
|
| 75 |
+
# Sleep to let the GPU run TTS and video generation
|
| 76 |
+
Write-Host "Cycle complete at $(Get-Date -Format 'HH:mm:ss'). Sleeping for $sleepSeconds seconds to let ComfyUI process TTS and videos..."
|
| 77 |
+
Start-Sleep -Seconds $sleepSeconds
|
| 78 |
+
}
|
| 79 |
+
}
|
news_collection_and_script_generation/run_scripts_safely.ps1
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param (
|
| 2 |
+
[string]$locale = "en-EU",
|
| 3 |
+
[string]$category = "",
|
| 4 |
+
[int]$limit = 10,
|
| 5 |
+
[switch]$gpu
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
Write-Host "Starting safe script generation loop for locale: $locale, category: $category, limit: $limit, GPU: $gpu"
|
| 9 |
+
|
| 10 |
+
$cmdArgs = "--locale $locale --limit $limit"
|
| 11 |
+
if ($gpu) {
|
| 12 |
+
$cmdArgs = $cmdArgs + " --gpu"
|
| 13 |
+
}
|
| 14 |
+
if ($category -ne "") {
|
| 15 |
+
$cmdArgs = $cmdArgs + " --category " + $category
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# Infinite loop running generate_scripts_all.py
|
| 19 |
+
while ($true) {
|
| 20 |
+
Write-Host "Running next batch (limit $limit)..."
|
| 21 |
+
|
| 22 |
+
# Run the script and capture both stdout and stderr
|
| 23 |
+
$process = Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\generate_scripts_all.py $cmdArgs" -NoNewWindow -PassThru -Wait
|
| 24 |
+
|
| 25 |
+
$exitCode = $process.ExitCode
|
| 26 |
+
Write-Host "Process finished with exit code: $exitCode"
|
| 27 |
+
|
| 28 |
+
Write-Host "Running media collection..."
|
| 29 |
+
$mediaArgs = "--locale $locale"
|
| 30 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\collect_media_parallel.py $mediaArgs" -NoNewWindow -PassThru -Wait
|
| 31 |
+
|
| 32 |
+
Write-Host "Running quality gate evaluation and copy..."
|
| 33 |
+
$copyArgs = "--locale $locale"
|
| 34 |
+
if ($category -ne "") {
|
| 35 |
+
$copyArgs = $copyArgs + " --category " + $category
|
| 36 |
+
}
|
| 37 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\copy_passed_articles.py $copyArgs" -NoNewWindow -PassThru -Wait
|
| 38 |
+
|
| 39 |
+
# Wait a bit to prevent tight loop if something is fundamentally broken
|
| 40 |
+
Start-Sleep -Seconds 3
|
| 41 |
+
|
| 42 |
+
# Verify if there are any remaining articles by doing a quick run that will check status
|
| 43 |
+
# We can run with --limit 0 (if supported) or just check the output of a test check.
|
| 44 |
+
# To keep it simple, we run a check logic:
|
| 45 |
+
# If the process completed successfully but processed 0 count, it means we are done.
|
| 46 |
+
# We can inspect history or files, but running the script and checking if it skips immediately is easiest.
|
| 47 |
+
# Let's run a dry run check via python inline
|
| 48 |
+
$check = python -c "
|
| 49 |
+
import os
|
| 50 |
+
ROOT_DIR = r'C:\ComfyUI\Articles'
|
| 51 |
+
locale = '$locale'
|
| 52 |
+
category = '$category' if '$category' else None
|
| 53 |
+
locales = [locale]
|
| 54 |
+
article_dirs = []
|
| 55 |
+
for loc in locales:
|
| 56 |
+
loc_path = os.path.join(ROOT_DIR, loc)
|
| 57 |
+
if not os.path.exists(loc_path): continue
|
| 58 |
+
cats = [category] if category else os.listdir(loc_path)
|
| 59 |
+
for cat in cats:
|
| 60 |
+
if cat == '__pycache__': continue
|
| 61 |
+
cat_path = os.path.join(loc_path, cat)
|
| 62 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path): continue
|
| 63 |
+
for art in os.listdir(cat_path):
|
| 64 |
+
if art in ['__pycache__', 'images', 'sources']: continue
|
| 65 |
+
art_path = os.path.join(cat_path, art)
|
| 66 |
+
if os.path.isdir(art_path):
|
| 67 |
+
md_files = [f for f in os.listdir(art_path) if f.endswith('.md')]
|
| 68 |
+
if md_files:
|
| 69 |
+
article_dirs.append(art_path)
|
| 70 |
+
|
| 71 |
+
dirs_to_process = []
|
| 72 |
+
for d in article_dirs:
|
| 73 |
+
all_exist = True
|
| 74 |
+
for length in ['short', 'middle', 'long']:
|
| 75 |
+
script_path = os.path.join(d, f'script_{length}.md')
|
| 76 |
+
txt_path = os.path.join(d, f'script_{length}_clean.txt')
|
| 77 |
+
if not os.path.exists(script_path) or not os.path.exists(txt_path):
|
| 78 |
+
all_exist = False
|
| 79 |
+
break
|
| 80 |
+
if not all_exist:
|
| 81 |
+
dirs_to_process.append(d)
|
| 82 |
+
|
| 83 |
+
print(len(dirs_to_process))
|
| 84 |
+
"
|
| 85 |
+
|
| 86 |
+
$remaining = [int]($check.Trim())
|
| 87 |
+
Write-Host "Remaining articles requiring scripts: $remaining"
|
| 88 |
+
|
| 89 |
+
if ($remaining -eq 0) {
|
| 90 |
+
Write-Host "Success! All articles in $locale (category: $category) have scripts generated."
|
| 91 |
+
break
|
| 92 |
+
}
|
| 93 |
+
}
|
news_collection_and_script_generation/synthesize_articles_litert.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import litert_lm
|
| 6 |
+
|
| 7 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 8 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 9 |
+
|
| 10 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 11 |
+
PENDING_FILE = os.path.join(ROOT_DIR, "pending.json")
|
| 12 |
+
SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json")
|
| 13 |
+
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
|
| 14 |
+
|
| 15 |
+
CATEGORY_LIMITS = {
|
| 16 |
+
"Business": 3,
|
| 17 |
+
"World_Affairs": 5,
|
| 18 |
+
"Animals": 3,
|
| 19 |
+
"General": 3
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
# Removed UNSPLASH_IMAGES constants to use authentic images
|
| 23 |
+
|
| 24 |
+
def load_json(path, default):
|
| 25 |
+
if os.path.exists(path):
|
| 26 |
+
try:
|
| 27 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 28 |
+
return json.load(f)
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"Failed to load JSON {path}: {e}")
|
| 31 |
+
return default
|
| 32 |
+
|
| 33 |
+
def save_json(path, data):
|
| 34 |
+
try:
|
| 35 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 36 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Failed to save JSON {path}: {e}")
|
| 39 |
+
|
| 40 |
+
def parse_date(date_str):
|
| 41 |
+
formats = [
|
| 42 |
+
"%a, %d %b %Y %H:%M:%S %Z",
|
| 43 |
+
"%a, %d %b %Y %H:%M:%S %z",
|
| 44 |
+
"%Y-%m-%dT%H:%M:%S%z",
|
| 45 |
+
"%Y-%m-%d %H:%M:%S"
|
| 46 |
+
]
|
| 47 |
+
for fmt in formats:
|
| 48 |
+
try:
|
| 49 |
+
return datetime.strptime(date_str, fmt)
|
| 50 |
+
except:
|
| 51 |
+
pass
|
| 52 |
+
return datetime.min
|
| 53 |
+
|
| 54 |
+
def build_single_article_prompt(title, category, content):
|
| 55 |
+
prompt = f"""You are a professional news editor.
|
| 56 |
+
Your task is to write a clean, engaging, and comprehensive news report in English based on the following raw crawled source text.
|
| 57 |
+
|
| 58 |
+
Category: {category}
|
| 59 |
+
Title of the news: {title}
|
| 60 |
+
|
| 61 |
+
Raw source text:
|
| 62 |
+
{content}
|
| 63 |
+
|
| 64 |
+
Requirements:
|
| 65 |
+
1. Write the entire article in English and format it in Markdown (.md).
|
| 66 |
+
2. The first line of your output MUST be the article title prefixed by a single '#', like: '# [Article Title]'.
|
| 67 |
+
3. The second line should be the current date (e.g. {datetime.now().strftime('%B %d, %Y')}).
|
| 68 |
+
4. Write a detailed, cohesive summary of the main news events. Organize the content into paragraphs and sections with '## [Section Name]' where appropriate. Do not include external links or image URLs in your summary.
|
| 69 |
+
|
| 70 |
+
Generate only the markdown article content. Do not include any introductory or concluding chat remarks.
|
| 71 |
+
"""
|
| 72 |
+
return prompt
|
| 73 |
+
|
| 74 |
+
def main():
|
| 75 |
+
print(f"Starting individual LiteRT-LM news synthesis at {datetime.now().isoformat()}")
|
| 76 |
+
|
| 77 |
+
pending_list = load_json(PENDING_FILE, [])
|
| 78 |
+
if not pending_list:
|
| 79 |
+
print("No pending articles to process.")
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
# Group by category to apply limits
|
| 83 |
+
by_category = {}
|
| 84 |
+
for item in pending_list:
|
| 85 |
+
cat = item["category"]
|
| 86 |
+
if cat not in by_category:
|
| 87 |
+
by_category[cat] = []
|
| 88 |
+
by_category[cat].append(item)
|
| 89 |
+
|
| 90 |
+
cleaned_pending = []
|
| 91 |
+
process_jobs = []
|
| 92 |
+
discarded_count = 0
|
| 93 |
+
|
| 94 |
+
for category, items in by_category.items():
|
| 95 |
+
limit = CATEGORY_LIMITS.get(category, 5)
|
| 96 |
+
# Sort by pub_date descending (latest first)
|
| 97 |
+
sorted_items = sorted(items, key=lambda x: parse_date(x.get("pub_date", "")), reverse=True)
|
| 98 |
+
|
| 99 |
+
kept_items = sorted_items[:limit]
|
| 100 |
+
discarded_items = sorted_items[limit:]
|
| 101 |
+
|
| 102 |
+
cleaned_pending.extend(kept_items)
|
| 103 |
+
process_jobs.extend(kept_items)
|
| 104 |
+
|
| 105 |
+
for item in discarded_items:
|
| 106 |
+
discarded_count += 1
|
| 107 |
+
src_file = item.get("source_file", "")
|
| 108 |
+
if src_file and os.path.exists(src_file):
|
| 109 |
+
try:
|
| 110 |
+
os.remove(src_file)
|
| 111 |
+
print(f"Removed excess source file: {src_file}")
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print(f"Failed to remove excess source file: {e}")
|
| 114 |
+
|
| 115 |
+
save_json(PENDING_FILE, cleaned_pending)
|
| 116 |
+
if discarded_count > 0:
|
| 117 |
+
print(f"Cleaned queue: kept {len(cleaned_pending)} items, discarded {discarded_count} items.")
|
| 118 |
+
|
| 119 |
+
synthesis_output = []
|
| 120 |
+
|
| 121 |
+
if not process_jobs:
|
| 122 |
+
print("No articles to process after filtering.")
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
print(f"Loading LiteRT-LM engine with model: {LITERT_MODEL_PATH}")
|
| 126 |
+
try:
|
| 127 |
+
# Load with max_num_tokens=8192 for longer contexts
|
| 128 |
+
with litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.CPU, max_num_tokens=8192) as engine:
|
| 129 |
+
for item in process_jobs:
|
| 130 |
+
category = item["category"]
|
| 131 |
+
title = item["title"]
|
| 132 |
+
link = item["link"]
|
| 133 |
+
src_path = item.get("source_file", "")
|
| 134 |
+
|
| 135 |
+
print(f"Summarizing article '{title}' under category '{category}' with Gemma-4...")
|
| 136 |
+
|
| 137 |
+
# Read full text content
|
| 138 |
+
content = ""
|
| 139 |
+
if src_path and os.path.exists(src_path):
|
| 140 |
+
try:
|
| 141 |
+
with open(src_path, 'r', encoding='utf-8') as sf:
|
| 142 |
+
content = sf.read().strip()
|
| 143 |
+
except Exception as e:
|
| 144 |
+
print(f"Failed to read source file {src_path}: {e}")
|
| 145 |
+
|
| 146 |
+
if not content:
|
| 147 |
+
content = item.get('description', '')
|
| 148 |
+
|
| 149 |
+
# Truncate content per article to keep prompt length reasonable (under model limits)
|
| 150 |
+
if len(content) > 4000:
|
| 151 |
+
content = content[:4000] + "... [truncated]"
|
| 152 |
+
|
| 153 |
+
prompt = build_single_article_prompt(title, category, content)
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
with engine.create_conversation() as conversation:
|
| 157 |
+
response = conversation.send_message(prompt)
|
| 158 |
+
gemma_markdown = response["content"][0]["text"].strip()
|
| 159 |
+
except Exception as model_err:
|
| 160 |
+
print(f"Gemma-4 synthesis error for '{title}': {model_err}. Falling back to raw text.")
|
| 161 |
+
gemma_markdown = f"# {title}\n\n{content}"
|
| 162 |
+
|
| 163 |
+
# Append Unsplash images and citation block to the model's markdown output
|
| 164 |
+
lines = [gemma_markdown]
|
| 165 |
+
lines.append("")
|
| 166 |
+
lines.append("---")
|
| 167 |
+
lines.append("")
|
| 168 |
+
lines.append("**Author:** AntigravityAI News Collector")
|
| 169 |
+
lines.append("")
|
| 170 |
+
lines.append("**Sources & Citations:**")
|
| 171 |
+
lines.append(f"- [{title}]({link})")
|
| 172 |
+
|
| 173 |
+
final_markdown = "\n".join(lines)
|
| 174 |
+
|
| 175 |
+
synthesis_output.append({
|
| 176 |
+
"category": category,
|
| 177 |
+
"title": title,
|
| 178 |
+
"link": link,
|
| 179 |
+
"markdown": final_markdown,
|
| 180 |
+
"source_file": src_path
|
| 181 |
+
})
|
| 182 |
+
print(f"Gemma-4 synthesis finished for '{title}' successfully.")
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print(f"LiteRT-LM Engine failure during synthesis: {e}")
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
if synthesis_output:
|
| 188 |
+
save_json(SYNTHESIS_FILE, synthesis_output)
|
| 189 |
+
print(f"Individual compilation finished. Saved {len(synthesis_output)} articles to {SYNTHESIS_FILE}")
|
| 190 |
+
else:
|
| 191 |
+
print("No outputs generated.")
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
main()
|
news_collection_and_script_generation/synthesize_articles_raw.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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"C:\ComfyUI\Articles"
|
| 10 |
+
PENDING_FILE = os.path.join(ROOT_DIR, "pending.json")
|
| 11 |
+
SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json")
|
| 12 |
+
|
| 13 |
+
CATEGORY_LIMITS = {
|
| 14 |
+
"Business": 5,
|
| 15 |
+
"World_Affairs": 15,
|
| 16 |
+
"Animals": 5,
|
| 17 |
+
"General": 5
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# Removed UNSPLASH_IMAGES constants to use authentic images
|
| 21 |
+
|
| 22 |
+
def load_json(path, default):
|
| 23 |
+
if os.path.exists(path):
|
| 24 |
+
try:
|
| 25 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 26 |
+
return json.load(f)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Failed to load JSON {path}: {e}")
|
| 29 |
+
return default
|
| 30 |
+
|
| 31 |
+
def save_json(path, data):
|
| 32 |
+
try:
|
| 33 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 34 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"Failed to save JSON {path}: {e}")
|
| 37 |
+
|
| 38 |
+
def parse_date(date_str):
|
| 39 |
+
formats = [
|
| 40 |
+
"%a, %d %b %Y %H:%M:%S %Z",
|
| 41 |
+
"%a, %d %b %Y %H:%M:%S %z",
|
| 42 |
+
"%Y-%m-%dT%H:%M:%S%z",
|
| 43 |
+
"%Y-%m-%d %H:%M:%S"
|
| 44 |
+
]
|
| 45 |
+
for fmt in formats:
|
| 46 |
+
try:
|
| 47 |
+
return datetime.strptime(date_str, fmt)
|
| 48 |
+
except:
|
| 49 |
+
pass
|
| 50 |
+
return datetime.min
|
| 51 |
+
|
| 52 |
+
def main():
|
| 53 |
+
print(f"Starting raw individual news compilation at {datetime.now().isoformat()}")
|
| 54 |
+
|
| 55 |
+
pending_list = load_json(PENDING_FILE, [])
|
| 56 |
+
if not pending_list:
|
| 57 |
+
print("No pending articles to process.")
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
# Group by category to apply limits
|
| 61 |
+
by_category = {}
|
| 62 |
+
for item in pending_list:
|
| 63 |
+
cat = item["category"]
|
| 64 |
+
if cat not in by_category:
|
| 65 |
+
by_category[cat] = []
|
| 66 |
+
by_category[cat].append(item)
|
| 67 |
+
|
| 68 |
+
cleaned_pending = []
|
| 69 |
+
process_jobs = []
|
| 70 |
+
discarded_count = 0
|
| 71 |
+
|
| 72 |
+
for category, items in by_category.items():
|
| 73 |
+
limit = CATEGORY_LIMITS.get(category, 10)
|
| 74 |
+
# Sort by pub_date descending
|
| 75 |
+
sorted_items = sorted(items, key=lambda x: parse_date(x.get("pub_date", "")), reverse=True)
|
| 76 |
+
|
| 77 |
+
kept_items = sorted_items[:limit]
|
| 78 |
+
discarded_items = sorted_items[limit:]
|
| 79 |
+
|
| 80 |
+
cleaned_pending.extend(kept_items)
|
| 81 |
+
process_jobs.extend(kept_items)
|
| 82 |
+
|
| 83 |
+
for item in discarded_items:
|
| 84 |
+
discarded_count += 1
|
| 85 |
+
src_file = item.get("source_file", "")
|
| 86 |
+
if src_file and os.path.exists(src_file):
|
| 87 |
+
try:
|
| 88 |
+
os.remove(src_file)
|
| 89 |
+
print(f"Removed excess source file: {src_file}")
|
| 90 |
+
except Exception as e:
|
| 91 |
+
print(f"Failed to remove excess source file: {e}")
|
| 92 |
+
|
| 93 |
+
save_json(PENDING_FILE, cleaned_pending)
|
| 94 |
+
if discarded_count > 0:
|
| 95 |
+
print(f"Cleaned queue: kept {len(cleaned_pending)} items, discarded {discarded_count} items.")
|
| 96 |
+
|
| 97 |
+
synthesis_output = []
|
| 98 |
+
|
| 99 |
+
for item in process_jobs:
|
| 100 |
+
category = item["category"]
|
| 101 |
+
title = item["title"]
|
| 102 |
+
link = item["link"]
|
| 103 |
+
pub_date = item.get("pub_date", "Unknown")
|
| 104 |
+
src_path = item.get("source_file", "")
|
| 105 |
+
|
| 106 |
+
print(f"Compiling article '{title}' under category '{category}'...")
|
| 107 |
+
|
| 108 |
+
# Read full text content
|
| 109 |
+
content = ""
|
| 110 |
+
if src_path and os.path.exists(src_path):
|
| 111 |
+
try:
|
| 112 |
+
with open(src_path, 'r', encoding='utf-8') as sf:
|
| 113 |
+
content = sf.read().strip()
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"Failed to read source file {src_path}: {e}")
|
| 116 |
+
|
| 117 |
+
if not content:
|
| 118 |
+
content = item.get('description', '')
|
| 119 |
+
|
| 120 |
+
# Build individual article document
|
| 121 |
+
lines = []
|
| 122 |
+
lines.append(f"# {title}")
|
| 123 |
+
lines.append(pub_date)
|
| 124 |
+
lines.append("")
|
| 125 |
+
lines.append(content)
|
| 126 |
+
lines.append("")
|
| 127 |
+
lines.append("---")
|
| 128 |
+
lines.append("")
|
| 129 |
+
lines.append("**Author:** AntigravityAI News Collector")
|
| 130 |
+
lines.append("")
|
| 131 |
+
lines.append("**Sources & Citations:**")
|
| 132 |
+
lines.append(f"- [{title}]({link})")
|
| 133 |
+
|
| 134 |
+
markdown_content = "\n".join(lines)
|
| 135 |
+
|
| 136 |
+
synthesis_output.append({
|
| 137 |
+
"category": category,
|
| 138 |
+
"title": title,
|
| 139 |
+
"link": link,
|
| 140 |
+
"markdown": markdown_content,
|
| 141 |
+
"source_file": src_path
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
if synthesis_output:
|
| 145 |
+
save_json(SYNTHESIS_FILE, synthesis_output)
|
| 146 |
+
print(f"Compilation finished. Saved {len(synthesis_output)} articles to {SYNTHESIS_FILE}")
|
| 147 |
+
else:
|
| 148 |
+
print("No outputs generated.")
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|
news_collection_and_script_generation/task_config.xml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-16"?>
|
| 2 |
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
| 3 |
+
<RegistrationInfo>
|
| 4 |
+
<Date>2026-06-11T12:00:00</Date>
|
| 5 |
+
<Author>AntigravityAI</Author>
|
| 6 |
+
<Description>Automatically collect English news reports every 4 hours and on logon.</Description>
|
| 7 |
+
</RegistrationInfo>
|
| 8 |
+
<Triggers>
|
| 9 |
+
<LogonTrigger>
|
| 10 |
+
<Enabled>true</Enabled>
|
| 11 |
+
<Repetition>
|
| 12 |
+
<Interval>PT4H</Interval>
|
| 13 |
+
<StopAtDurationEnd>false</StopAtDurationEnd>
|
| 14 |
+
</Repetition>
|
| 15 |
+
</LogonTrigger>
|
| 16 |
+
</Triggers>
|
| 17 |
+
<Principals>
|
| 18 |
+
<Principal id="Author">
|
| 19 |
+
<LogonType>InteractiveToken</LogonType>
|
| 20 |
+
<RunLevel>LeastPrivilege</RunLevel>
|
| 21 |
+
</Principal>
|
| 22 |
+
</Principals>
|
| 23 |
+
<Settings>
|
| 24 |
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
| 25 |
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
| 26 |
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
| 27 |
+
<AllowHardTerminate>true</AllowHardTerminate>
|
| 28 |
+
<StartWhenAvailable>true</StartWhenAvailable>
|
| 29 |
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
| 30 |
+
<IdleSettings>
|
| 31 |
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
| 32 |
+
<RestartOnIdle>false</RestartOnIdle>
|
| 33 |
+
</IdleSettings>
|
| 34 |
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
| 35 |
+
<Enabled>true</Enabled>
|
| 36 |
+
<Hidden>false</Hidden>
|
| 37 |
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
| 38 |
+
<WakeToRun>false</WakeToRun>
|
| 39 |
+
<ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
|
| 40 |
+
<Priority>7</Priority>
|
| 41 |
+
</Settings>
|
| 42 |
+
<Actions Context="Author">
|
| 43 |
+
<Exec>
|
| 44 |
+
<Command>wscript.exe</Command>
|
| 45 |
+
<Arguments>C:\ComfyUI\Articles\run_silent.vbs</Arguments>
|
| 46 |
+
</Exec>
|
| 47 |
+
</Actions>
|
| 48 |
+
</Task>
|
news_collection_and_script_generation/tts_articles.py
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import uuid
|
| 6 |
+
import time
|
| 7 |
+
import argparse
|
| 8 |
+
import shutil
|
| 9 |
+
import urllib.request
|
| 10 |
+
import urllib.parse
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Reconfigure encoding to avoid Windows console encoding issues
|
| 14 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 15 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 16 |
+
|
| 17 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 18 |
+
DEFAULT_WORKFLOW = r"C:\ComfyUI\workflows\05_Audio_&_TTS\Text to Speech.json"
|
| 19 |
+
DEFAULT_PORT = 7777
|
| 20 |
+
|
| 21 |
+
def get_default_value(node_info, key):
|
| 22 |
+
inputs = node_info.get("input", {})
|
| 23 |
+
for cat in ["required", "optional"]:
|
| 24 |
+
if key in inputs.get(cat, {}):
|
| 25 |
+
param = inputs[cat][key]
|
| 26 |
+
if len(param) > 1 and isinstance(param[1], dict) and "default" in param[1]:
|
| 27 |
+
return param[1]["default"]
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
def convert_ui_to_api(wf_path, server_url):
|
| 31 |
+
print(f"Fetching node object info from ComfyUI server at {server_url}...")
|
| 32 |
+
try:
|
| 33 |
+
with urllib.request.urlopen(f"{server_url}/object_info") as r:
|
| 34 |
+
object_info = json.loads(r.read().decode('utf-8'))
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"Error connecting to ComfyUI at {server_url}: {e}")
|
| 37 |
+
print("Please make sure ComfyUI is running on this port.")
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
print(f"Loading UI workflow from {wf_path}...")
|
| 41 |
+
with open(wf_path, 'r', encoding='utf-8') as f:
|
| 42 |
+
wf = json.load(f)
|
| 43 |
+
|
| 44 |
+
# Map link_id -> (from_node_id, from_slot)
|
| 45 |
+
link_map = {}
|
| 46 |
+
for link in wf.get("links", []):
|
| 47 |
+
if link:
|
| 48 |
+
link_id, from_node, from_slot, to_node, to_slot, type_name = link
|
| 49 |
+
link_map[link_id] = [str(from_node), from_slot]
|
| 50 |
+
|
| 51 |
+
api_prompt = {}
|
| 52 |
+
for node in wf.get("nodes", []):
|
| 53 |
+
node_id = str(node["id"])
|
| 54 |
+
class_type = node["type"]
|
| 55 |
+
|
| 56 |
+
if class_type not in object_info:
|
| 57 |
+
print(f"Warning: node type '{class_type}' not found in ComfyUI object info. Skipping node {node_id}.")
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
node_info = object_info[class_type]
|
| 61 |
+
req_inputs = node_info.get("input", {}).get("required", {})
|
| 62 |
+
opt_inputs = node_info.get("input", {}).get("optional", {})
|
| 63 |
+
all_input_keys = list(req_inputs.keys()) + list(opt_inputs.keys())
|
| 64 |
+
|
| 65 |
+
inputs = {}
|
| 66 |
+
linked_keys = {}
|
| 67 |
+
for ui_input in node.get("inputs", []):
|
| 68 |
+
name = ui_input["name"]
|
| 69 |
+
link_id = ui_input.get("link")
|
| 70 |
+
if link_id and link_id in link_map:
|
| 71 |
+
linked_keys[name] = link_map[link_id]
|
| 72 |
+
|
| 73 |
+
widgets_values = node.get("widgets_values", [])
|
| 74 |
+
widget_idx = 0
|
| 75 |
+
|
| 76 |
+
for key in all_input_keys:
|
| 77 |
+
if key in linked_keys:
|
| 78 |
+
inputs[key] = linked_keys[key]
|
| 79 |
+
else:
|
| 80 |
+
if widget_idx < len(widgets_values):
|
| 81 |
+
val = widgets_values[widget_idx]
|
| 82 |
+
if val is not None:
|
| 83 |
+
inputs[key] = val
|
| 84 |
+
else:
|
| 85 |
+
inputs[key] = get_default_value(node_info, key)
|
| 86 |
+
widget_idx += 1
|
| 87 |
+
else:
|
| 88 |
+
inputs[key] = get_default_value(node_info, key)
|
| 89 |
+
|
| 90 |
+
# Clean up None values to let ComfyUI use its default behavior
|
| 91 |
+
if inputs[key] is None:
|
| 92 |
+
del inputs[key]
|
| 93 |
+
|
| 94 |
+
api_prompt[node_id] = {
|
| 95 |
+
"class_type": class_type,
|
| 96 |
+
"inputs": inputs
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
return api_prompt
|
| 100 |
+
|
| 101 |
+
def queue_prompt(server_url, prompt, prompt_id, client_id):
|
| 102 |
+
p = {"prompt": prompt, "client_id": client_id, "prompt_id": prompt_id}
|
| 103 |
+
data = json.dumps(p).encode('utf-8')
|
| 104 |
+
req = urllib.request.Request(f"{server_url}/prompt", data=data)
|
| 105 |
+
with urllib.request.urlopen(req) as response:
|
| 106 |
+
return json.loads(response.read().decode('utf-8'))
|
| 107 |
+
|
| 108 |
+
def get_history(server_url, prompt_id):
|
| 109 |
+
with urllib.request.urlopen(f"{server_url}/history/{prompt_id}") as response:
|
| 110 |
+
return json.loads(response.read().decode('utf-8'))
|
| 111 |
+
|
| 112 |
+
def find_script_file(article_dir):
|
| 113 |
+
files = os.listdir(article_dir)
|
| 114 |
+
# Prefer normal script
|
| 115 |
+
for f in files:
|
| 116 |
+
if f.endswith("_script_normal.md"):
|
| 117 |
+
return os.path.join(article_dir, f)
|
| 118 |
+
# Fallback to general script
|
| 119 |
+
for f in files:
|
| 120 |
+
if f.endswith("_script.md"):
|
| 121 |
+
return os.path.join(article_dir, f)
|
| 122 |
+
# Fallback to other script types
|
| 123 |
+
for f in files:
|
| 124 |
+
if f.endswith(("_script_short.md", "_script_long.md")):
|
| 125 |
+
return os.path.join(article_dir, f)
|
| 126 |
+
# Absolute fallback to any md file except the main article one if possible
|
| 127 |
+
for f in files:
|
| 128 |
+
if f.endswith(".md") and not f.endswith(os.path.basename(article_dir) + ".md"):
|
| 129 |
+
return os.path.join(article_dir, f)
|
| 130 |
+
# Final fallback
|
| 131 |
+
for f in files:
|
| 132 |
+
if f.endswith(".md"):
|
| 133 |
+
return os.path.join(article_dir, f)
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
def clean_script_text(file_path):
|
| 137 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 138 |
+
text = f.read().strip()
|
| 139 |
+
|
| 140 |
+
# If it's a raw article file containing a summary, extract just the summary
|
| 141 |
+
if "## Summary" in text:
|
| 142 |
+
parts = text.split("## Summary", 1)
|
| 143 |
+
if len(parts) > 1:
|
| 144 |
+
summary_part = parts[1]
|
| 145 |
+
if "---" in summary_part:
|
| 146 |
+
summary_part = summary_part.split("---", 1)[0]
|
| 147 |
+
text = summary_part.strip()
|
| 148 |
+
|
| 149 |
+
lines = text.splitlines()
|
| 150 |
+
cleaned_lines = []
|
| 151 |
+
in_carousel = False
|
| 152 |
+
|
| 153 |
+
for line in lines:
|
| 154 |
+
stripped = line.strip()
|
| 155 |
+
|
| 156 |
+
# Handle carousel blocks
|
| 157 |
+
if stripped.startswith("```carousel"):
|
| 158 |
+
in_carousel = True
|
| 159 |
+
continue
|
| 160 |
+
if in_carousel:
|
| 161 |
+
if stripped.startswith("```"):
|
| 162 |
+
in_carousel = False
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
# Skip headers
|
| 166 |
+
if stripped.startswith("#"):
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
# Skip metadata lines
|
| 170 |
+
if any(stripped.startswith(prefix) for prefix in [
|
| 171 |
+
"Category:", "Locale:", "Source:", "Date Collected:",
|
| 172 |
+
"Author:", "Sources & Citations:", "**Category:**",
|
| 173 |
+
"**Locale:**", "**Source:**", "**Date Collected:**"
|
| 174 |
+
]):
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
# Clean inline markdown bold/italic
|
| 178 |
+
cleaned_line = line.replace("**", "").replace("*", "")
|
| 179 |
+
|
| 180 |
+
# Replace with spaces
|
| 181 |
+
cleaned_line = cleaned_line.replace(" ", " ")
|
| 182 |
+
|
| 183 |
+
# Clean up markdown links [Text](URL) -> Text
|
| 184 |
+
cleaned_line = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', cleaned_line)
|
| 185 |
+
|
| 186 |
+
if cleaned_line.strip():
|
| 187 |
+
cleaned_lines.append(cleaned_line)
|
| 188 |
+
|
| 189 |
+
return "\n".join(cleaned_lines).strip()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def split_into_segments(text):
|
| 194 |
+
# Split by sentence endings keeping the punctuation
|
| 195 |
+
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
|
| 196 |
+
return [s.strip() for s in sentences if s.strip()]
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_speed_factor(sentence):
|
| 200 |
+
words = sentence.split()
|
| 201 |
+
word_count = len(words)
|
| 202 |
+
|
| 203 |
+
# 1. Very short sentence / punctuation emphasis -> speak slower
|
| 204 |
+
if word_count <= 3:
|
| 205 |
+
return 0.80 # 20% slower
|
| 206 |
+
|
| 207 |
+
# 2. Key quotes, emotional words, exclamation -> speak slower
|
| 208 |
+
if '"' in sentence or "'" in sentence:
|
| 209 |
+
return 0.85
|
| 210 |
+
if sentence.endswith('!') or any(w.lower() in ["must", "never", "critical", "painful", "truce", "ceasefire", "alert", "warn"] for w in words):
|
| 211 |
+
return 0.85 # 15% slower
|
| 212 |
+
|
| 213 |
+
# 3. Long sentence / transition explanations -> speak faster
|
| 214 |
+
if word_count >= 18:
|
| 215 |
+
return 1.15 # 15% faster
|
| 216 |
+
|
| 217 |
+
if words and words[0].lower() in ["and", "but", "so", "however", "because", "also", "then"]:
|
| 218 |
+
return 1.15 # 15% faster
|
| 219 |
+
|
| 220 |
+
# 4. Default normal speed
|
| 221 |
+
return 1.00
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def get_pause_duration(sentence):
|
| 225 |
+
if sentence.endswith('?') or sentence.endswith('!'):
|
| 226 |
+
return 0.50
|
| 227 |
+
elif sentence.endswith(','):
|
| 228 |
+
return 0.15
|
| 229 |
+
else:
|
| 230 |
+
return 0.35
|
| 231 |
+
|
| 232 |
+
def get_emotion_description(text):
|
| 233 |
+
text_lower = text.lower()
|
| 234 |
+
urgent_keywords = ['breaking', 'just now', 'immediately', 'urgent', 'sudden', 'latest']
|
| 235 |
+
tense_keywords = ['warning', 'threat', 'alert', 'imminent', 'escalate', 'danger', 'fear', 'tense', 'unstable']
|
| 236 |
+
serious_keywords = ['war', 'attack', 'death', 'casualty', 'killed', 'destroy', 'bomb', 'fire', 'severe', 'tragedy', 'crisis', 'terror', 'ukraine', 'moscow', 'russia', 'military', 'soldier', 'strike', 'conflict']
|
| 237 |
+
|
| 238 |
+
if any(kw in text_lower for kw in urgent_keywords):
|
| 239 |
+
return "Urgent, fast-paced, breathless news reporter delivering breaking news"
|
| 240 |
+
|
| 241 |
+
if any(kw in text_lower for kw in tense_keywords):
|
| 242 |
+
return "Tense, worried, anxious news reporter talking about danger"
|
| 243 |
+
|
| 244 |
+
if any(kw in text_lower for kw in serious_keywords):
|
| 245 |
+
return "Serious, sad, grim, news reporter talking about tragedy"
|
| 246 |
+
|
| 247 |
+
if "!" in text or "amazing" in text_lower or "incredible" in text_lower:
|
| 248 |
+
return "Excited, energetic, happy news reporter"
|
| 249 |
+
|
| 250 |
+
return "Neutral, calm, informative, professional news anchor"
|
| 251 |
+
|
| 252 |
+
def add_emphasis_pauses(text):
|
| 253 |
+
# Add native easy-indextts2 pauses around important keywords
|
| 254 |
+
important_keywords = ['must', 'never', 'critical', 'warning', 'breaking', 'however']
|
| 255 |
+
words = text.split()
|
| 256 |
+
for i, w in enumerate(words):
|
| 257 |
+
clean_w = w.lower().strip(',.?!')
|
| 258 |
+
if clean_w in important_keywords:
|
| 259 |
+
words[i] = "-0.2s- " + w + " -0.2s-"
|
| 260 |
+
return " ".join(words)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main():
|
| 264 |
+
import numpy as np
|
| 265 |
+
import librosa
|
| 266 |
+
import soundfile as sf
|
| 267 |
+
|
| 268 |
+
parser = argparse.ArgumentParser(description="Batch process ComfyUI TTS on articles.")
|
| 269 |
+
parser.add_argument("--limit", type=int, default=None, help="Limit number of articles to process.")
|
| 270 |
+
parser.add_argument("--overwrite", action="store_true", help="Force process even if audio file already exists.")
|
| 271 |
+
parser.add_argument("--workflow", type=str, default=DEFAULT_WORKFLOW, help="Path to UI Text to Speech workflow JSON.")
|
| 272 |
+
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Port of running ComfyUI server.")
|
| 273 |
+
parser.add_argument("--lang", type=str, default=None, help="Only process articles in this language (e.g. en-US, en-EU, ja-JP).")
|
| 274 |
+
parser.add_argument("--category", type=str, default=None, help="Only process articles in this category (e.g. Moscow_Attacks).")
|
| 275 |
+
args = parser.parse_args()
|
| 276 |
+
|
| 277 |
+
server_url = f"http://127.0.0.1:{args.port}"
|
| 278 |
+
client_id = str(uuid.uuid4())
|
| 279 |
+
|
| 280 |
+
# Build api prompt template
|
| 281 |
+
api_prompt_template = convert_ui_to_api(args.workflow, server_url)
|
| 282 |
+
|
| 283 |
+
# Find nodes to manipulate
|
| 284 |
+
text_input_node_id = None
|
| 285 |
+
save_audio_node_id = None
|
| 286 |
+
index_tts_node_id = None
|
| 287 |
+
emotion_text_node_id = None
|
| 288 |
+
|
| 289 |
+
for node_id, node in api_prompt_template.items():
|
| 290 |
+
if node["class_type"] == "TextInput_":
|
| 291 |
+
text_input_node_id = node_id
|
| 292 |
+
elif node["class_type"] == "SaveAudio":
|
| 293 |
+
save_audio_node_id = node_id
|
| 294 |
+
elif node["class_type"] in ["IndexTTSRun", "easy indexTTSGenerate", "IndexTTS2EmotionText"]:
|
| 295 |
+
index_tts_node_id = node_id
|
| 296 |
+
elif node["class_type"] == "easy indexTTSEmotionText":
|
| 297 |
+
emotion_text_node_id = node_id
|
| 298 |
+
|
| 299 |
+
if not text_input_node_id:
|
| 300 |
+
print("Error: Could not find TextInput_ node in workflow.")
|
| 301 |
+
sys.exit(1)
|
| 302 |
+
if not save_audio_node_id:
|
| 303 |
+
print("Error: Could not find SaveAudio node in workflow.")
|
| 304 |
+
sys.exit(1)
|
| 305 |
+
|
| 306 |
+
# Scan directories (both root level and language/category subdirectories)
|
| 307 |
+
article_dirs = []
|
| 308 |
+
|
| 309 |
+
# 1. Check root level direct article directories (for backward compatibility)
|
| 310 |
+
if not args.lang and not args.category:
|
| 311 |
+
for d in os.listdir(ROOT_DIR):
|
| 312 |
+
full_path = os.path.join(ROOT_DIR, d)
|
| 313 |
+
if os.path.isdir(full_path) and d not in ["__pycache__", "temp_sources", "en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]:
|
| 314 |
+
article_dirs.append(full_path)
|
| 315 |
+
|
| 316 |
+
# 2. Check under language and category directories
|
| 317 |
+
langs_to_scan = [args.lang] if args.lang else ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 318 |
+
for lang in langs_to_scan:
|
| 319 |
+
lang_path = os.path.join(ROOT_DIR, lang)
|
| 320 |
+
if os.path.exists(lang_path) and os.path.isdir(lang_path):
|
| 321 |
+
for cat in os.listdir(lang_path):
|
| 322 |
+
if args.category and cat != args.category:
|
| 323 |
+
continue
|
| 324 |
+
cat_path = os.path.join(lang_path, cat)
|
| 325 |
+
if os.path.isdir(cat_path) and cat not in ["__pycache__"]:
|
| 326 |
+
for article in os.listdir(cat_path):
|
| 327 |
+
article_path = os.path.join(cat_path, article)
|
| 328 |
+
if os.path.isdir(article_path) and article not in ["__pycache__", "images", "sources"]:
|
| 329 |
+
article_dirs.append(article_path)
|
| 330 |
+
|
| 331 |
+
# Sort alphabetically by the article directory name for predictability
|
| 332 |
+
article_dirs.sort(key=lambda x: os.path.basename(x))
|
| 333 |
+
|
| 334 |
+
print(f"Found {len(article_dirs)} article directories.")
|
| 335 |
+
|
| 336 |
+
processed_count = 0
|
| 337 |
+
skipped_count = 0
|
| 338 |
+
failed_count = 0
|
| 339 |
+
|
| 340 |
+
comfy_output_dir = os.path.abspath(os.path.join(os.path.dirname(args.workflow), "..", "output"))
|
| 341 |
+
# In case workflow is in C:\ComfyUI\workflow, output is C:\ComfyUI\output
|
| 342 |
+
|
| 343 |
+
for idx, article_dir in enumerate(article_dirs, 1):
|
| 344 |
+
d = os.path.basename(article_dir)
|
| 345 |
+
if args.limit is not None and processed_count >= args.limit:
|
| 346 |
+
print(f"Limit of {args.limit} reached. Stopping.")
|
| 347 |
+
break
|
| 348 |
+
|
| 349 |
+
# Check if audio file already exists in directory
|
| 350 |
+
audio_files = [f for f in os.listdir(article_dir) if f.endswith((".wav", ".flac", ".mp3"))]
|
| 351 |
+
if audio_files and not args.overwrite:
|
| 352 |
+
skipped_count += 1
|
| 353 |
+
continue
|
| 354 |
+
|
| 355 |
+
script_file = find_script_file(article_dir)
|
| 356 |
+
if not script_file:
|
| 357 |
+
print(f"[{idx}/{len(article_dirs)}] Warning: No script file found in {d}. Skipping.")
|
| 358 |
+
failed_count += 1
|
| 359 |
+
continue
|
| 360 |
+
|
| 361 |
+
try:
|
| 362 |
+
script_text = clean_script_text(script_file)
|
| 363 |
+
except Exception as e:
|
| 364 |
+
print(f"[{idx}/{len(article_dirs)}] Error: Failed to read script in {d}: {e}")
|
| 365 |
+
failed_count += 1
|
| 366 |
+
continue
|
| 367 |
+
|
| 368 |
+
segments = split_into_segments(script_text)
|
| 369 |
+
if not segments:
|
| 370 |
+
print(f"[{idx}/{len(article_dirs)}] Warning: Script file in {d} is empty. Skipping.")
|
| 371 |
+
failed_count += 1
|
| 372 |
+
continue
|
| 373 |
+
|
| 374 |
+
print(f"\n[{idx}/{len(article_dirs)}] Processing: {d} ({len(segments)} segments) ...")
|
| 375 |
+
|
| 376 |
+
audio_segments = []
|
| 377 |
+
segment_failed = False
|
| 378 |
+
sr = 24000 # default fallback
|
| 379 |
+
|
| 380 |
+
for s_idx, segment in enumerate(segments):
|
| 381 |
+
is_last = (s_idx == len(segments) - 1)
|
| 382 |
+
speed_factor = get_speed_factor(segment)
|
| 383 |
+
pause_duration = get_pause_duration(segment)
|
| 384 |
+
|
| 385 |
+
# Apply emphasis pauses natively
|
| 386 |
+
emphasized_segment = add_emphasis_pauses(segment)
|
| 387 |
+
emotion_desc = get_emotion_description(segment)
|
| 388 |
+
print(f" -> Emotion: {emotion_desc}")
|
| 389 |
+
|
| 390 |
+
# Prepare custom prompt
|
| 391 |
+
prompt = json.loads(json.dumps(api_prompt_template))
|
| 392 |
+
prompt[text_input_node_id]["inputs"]["text"] = emphasized_segment
|
| 393 |
+
|
| 394 |
+
is_japanese = "ja-jp" in article_dir.lower()
|
| 395 |
+
if is_japanese:
|
| 396 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 397 |
+
prompt[index_tts_node_id]["inputs"]["version"] = "v2.0-jp"
|
| 398 |
+
elif "105" in prompt:
|
| 399 |
+
prompt["105"]["inputs"]["version"] = "v2.0-jp"
|
| 400 |
+
|
| 401 |
+
if emotion_text_node_id:
|
| 402 |
+
prompt[emotion_text_node_id]["inputs"]["description"] = emotion_desc
|
| 403 |
+
elif index_tts_node_id and prompt[index_tts_node_id]["class_type"] == "IndexTTS2EmotionText":
|
| 404 |
+
prompt[index_tts_node_id]["inputs"]["emo_text"] = emotion_desc
|
| 405 |
+
prompt[index_tts_node_id]["inputs"]["use_emo_text"] = True
|
| 406 |
+
|
| 407 |
+
prompt_id = str(uuid.uuid4())
|
| 408 |
+
filename_prefix = f"audio/article_tts_{prompt_id}"
|
| 409 |
+
prompt[save_audio_node_id]["inputs"]["filename_prefix"] = filename_prefix
|
| 410 |
+
|
| 411 |
+
# VRAM optimization: Keep model loaded except for the very last segment
|
| 412 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 413 |
+
if prompt[index_tts_node_id]["class_type"] != "IndexTTS2EmotionText":
|
| 414 |
+
prompt[index_tts_node_id]["inputs"]["unload_model"] = is_last
|
| 415 |
+
elif "105" in prompt:
|
| 416 |
+
if prompt["105"]["class_type"] not in ["IndexTTS2ModelLoader", "IndexTTS2EmotionText"]:
|
| 417 |
+
prompt["105"]["inputs"]["unload_model"] = is_last
|
| 418 |
+
|
| 419 |
+
# Queue prompt
|
| 420 |
+
try:
|
| 421 |
+
resp = queue_prompt(server_url, prompt, prompt_id, client_id)
|
| 422 |
+
except Exception as e:
|
| 423 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: Failed to queue prompt: {e}")
|
| 424 |
+
segment_failed = True
|
| 425 |
+
break
|
| 426 |
+
|
| 427 |
+
# Wait for completion
|
| 428 |
+
completed = False
|
| 429 |
+
start_time = time.time()
|
| 430 |
+
|
| 431 |
+
while time.time() - start_time < 1800:
|
| 432 |
+
try:
|
| 433 |
+
history = get_history(server_url, prompt_id)
|
| 434 |
+
if prompt_id in history:
|
| 435 |
+
completed = True
|
| 436 |
+
break
|
| 437 |
+
except Exception as e:
|
| 438 |
+
pass
|
| 439 |
+
time.sleep(0.5)
|
| 440 |
+
|
| 441 |
+
if not completed:
|
| 442 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: TTS timed out.")
|
| 443 |
+
segment_failed = True
|
| 444 |
+
break
|
| 445 |
+
|
| 446 |
+
# Process output
|
| 447 |
+
history_entry = history[prompt_id]
|
| 448 |
+
outputs = history_entry.get("outputs", {})
|
| 449 |
+
|
| 450 |
+
if save_audio_node_id not in outputs or "audio" not in outputs[save_audio_node_id]:
|
| 451 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: SaveAudio output not found.")
|
| 452 |
+
segment_failed = True
|
| 453 |
+
break
|
| 454 |
+
|
| 455 |
+
audio_outputs = outputs[save_audio_node_id]["audio"]
|
| 456 |
+
if not audio_outputs:
|
| 457 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: No audio files returned.")
|
| 458 |
+
segment_failed = True
|
| 459 |
+
break
|
| 460 |
+
|
| 461 |
+
# Load generated file
|
| 462 |
+
audio_info = audio_outputs[0]
|
| 463 |
+
gen_filename = audio_info["filename"]
|
| 464 |
+
gen_subfolder = audio_info["subfolder"]
|
| 465 |
+
|
| 466 |
+
# Path to generated file
|
| 467 |
+
src_path = os.path.join(comfy_output_dir, gen_subfolder, gen_filename)
|
| 468 |
+
|
| 469 |
+
if not os.path.exists(src_path):
|
| 470 |
+
# Fallback check directly in C:\ComfyUI\output\audio
|
| 471 |
+
src_path = os.path.join(r"C:\ComfyUI\output", gen_subfolder, gen_filename)
|
| 472 |
+
|
| 473 |
+
if not os.path.exists(src_path):
|
| 474 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: Generated audio file not found at: {src_path}")
|
| 475 |
+
segment_failed = True
|
| 476 |
+
break
|
| 477 |
+
|
| 478 |
+
try:
|
| 479 |
+
# Load and time-stretch
|
| 480 |
+
y, sr = librosa.load(src_path, sr=None)
|
| 481 |
+
if abs(speed_factor - 1.0) > 0.01:
|
| 482 |
+
y_stretched = librosa.effects.time_stretch(y=y, rate=speed_factor)
|
| 483 |
+
else:
|
| 484 |
+
y_stretched = y
|
| 485 |
+
audio_segments.append(y_stretched)
|
| 486 |
+
|
| 487 |
+
# Add pause
|
| 488 |
+
if pause_duration > 0 and not is_last:
|
| 489 |
+
silence = np.zeros(int(sr * pause_duration))
|
| 490 |
+
audio_segments.append(silence)
|
| 491 |
+
|
| 492 |
+
# Clean up temp file
|
| 493 |
+
os.remove(src_path)
|
| 494 |
+
except Exception as audio_err:
|
| 495 |
+
print(f" Segment {s_idx+1}/{len(segments)} Error: Audio post-processing failed: {audio_err}")
|
| 496 |
+
segment_failed = True
|
| 497 |
+
break
|
| 498 |
+
|
| 499 |
+
if segment_failed:
|
| 500 |
+
failed_count += 1
|
| 501 |
+
# Clean up the loaded model just in case it got stuck loaded
|
| 502 |
+
try:
|
| 503 |
+
prompt = json.loads(json.dumps(api_prompt_template))
|
| 504 |
+
prompt[text_input_node_id]["inputs"]["text"] = "."
|
| 505 |
+
prompt_id = str(uuid.uuid4())
|
| 506 |
+
prompt[save_audio_node_id]["inputs"]["filename_prefix"] = f"audio/cleanup_{prompt_id}"
|
| 507 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 508 |
+
prompt[index_tts_node_id]["inputs"]["unload_model"] = True
|
| 509 |
+
elif "105" in prompt:
|
| 510 |
+
prompt["105"]["inputs"]["unload_model"] = True
|
| 511 |
+
queue_prompt(server_url, prompt, prompt_id, client_id)
|
| 512 |
+
except:
|
| 513 |
+
pass
|
| 514 |
+
continue
|
| 515 |
+
|
| 516 |
+
# Destination filename is the directory name with .flac extension
|
| 517 |
+
dest_filename = f"{d}.flac"
|
| 518 |
+
dest_path = os.path.join(article_dir, dest_filename)
|
| 519 |
+
|
| 520 |
+
try:
|
| 521 |
+
final_audio = np.concatenate(audio_segments)
|
| 522 |
+
# Peak normalize the audio to 0.9 (approx -1dB) to ensure consistent volume
|
| 523 |
+
max_val = np.max(np.abs(final_audio))
|
| 524 |
+
if max_val > 0.001:
|
| 525 |
+
final_audio = final_audio / max_val * 0.9
|
| 526 |
+
sf.write(dest_path, final_audio, sr, format='FLAC')
|
| 527 |
+
print(f"Saved TTS audio to: {dest_path}")
|
| 528 |
+
processed_count += 1
|
| 529 |
+
except Exception as save_err:
|
| 530 |
+
print(f"Error: Failed to save final audio for {d}: {save_err}")
|
| 531 |
+
failed_count += 1
|
| 532 |
+
|
| 533 |
+
print("\n" + "="*40)
|
| 534 |
+
print("Batch TTS Job Summary:")
|
| 535 |
+
print(f"Successfully processed: {processed_count}")
|
| 536 |
+
print(f"Skipped (already exist): {skipped_count}")
|
| 537 |
+
print(f"Failed or skipped (no script): {failed_count}")
|
| 538 |
+
print("="*40)
|
| 539 |
+
|
| 540 |
+
if __name__ == "__main__":
|
| 541 |
+
main()
|
process_broll_watermarks.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import shutil
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
# Set up logging
|
| 8 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 9 |
+
logger = logging.getLogger("process_broll_watermarks")
|
| 10 |
+
|
| 11 |
+
# Add ComfyUI Articles directory to sys.path
|
| 12 |
+
sys.path.append(r"C:\ComfyUI\Articles")
|
| 13 |
+
|
| 14 |
+
from quality_gate_broll import detect_watermarks, remove_watermark_with_lama
|
| 15 |
+
from collect_broll_agent import generate_ken_burns_clip
|
| 16 |
+
|
| 17 |
+
ROOT_DIR = Path(r"C:\ComfyUI\Articles")
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
logger.info("Scanning for existing B-roll images in Articles directory...")
|
| 21 |
+
|
| 22 |
+
# Walk through ROOT_DIR to find Broll folders
|
| 23 |
+
broll_images = []
|
| 24 |
+
for root, dirs, files in os.walk(ROOT_DIR):
|
| 25 |
+
if Path(root).name == "Broll":
|
| 26 |
+
for f in files:
|
| 27 |
+
f_path = Path(root) / f
|
| 28 |
+
# Target only jpg/png images, skipping temporary files, masks, and originals
|
| 29 |
+
if f_path.suffix.lower() in [".jpg", ".jpeg", ".png"]:
|
| 30 |
+
if f.startswith("tmp_") or f.startswith("std_") or "_original" in f or "_mask" in f:
|
| 31 |
+
continue
|
| 32 |
+
broll_images.append(f_path)
|
| 33 |
+
|
| 34 |
+
logger.info(f"Found {len(broll_images)} candidate B-roll images.")
|
| 35 |
+
|
| 36 |
+
flagged_count = 0
|
| 37 |
+
removed_count = 0
|
| 38 |
+
regenerated_count = 0
|
| 39 |
+
|
| 40 |
+
for i, img_path in enumerate(broll_images, 1):
|
| 41 |
+
logger.info(f"[{i}/{len(broll_images)}] Scanning {img_path.relative_to(ROOT_DIR)}")
|
| 42 |
+
|
| 43 |
+
detected_corners = detect_watermarks(img_path)
|
| 44 |
+
if detected_corners:
|
| 45 |
+
flagged_count += 1
|
| 46 |
+
logger.info(f" -> Watermark detected in corners: {detected_corners}")
|
| 47 |
+
|
| 48 |
+
# Backup original image if not already done
|
| 49 |
+
backup_path = img_path.parent / f"{img_path.name.replace(img_path.suffix, '')}_original{img_path.suffix}"
|
| 50 |
+
if not backup_path.exists():
|
| 51 |
+
shutil.copy2(img_path, backup_path)
|
| 52 |
+
logger.info(f" -> Created backup: {backup_path.name}")
|
| 53 |
+
|
| 54 |
+
# Perform watermark removal using LaMa
|
| 55 |
+
# We pass backup_path as input and img_path as output, so we always inpaint from the clean original
|
| 56 |
+
success, reason = remove_watermark_with_lama(backup_path, img_path)
|
| 57 |
+
|
| 58 |
+
if success:
|
| 59 |
+
removed_count += 1
|
| 60 |
+
logger.info(f" -> Successfully removed watermark from {img_path.name}")
|
| 61 |
+
|
| 62 |
+
# Check for corresponding mp4 clip to regenerate
|
| 63 |
+
mp4_path = img_path.parent / f"{img_path.stem}.mp4"
|
| 64 |
+
if mp4_path.exists():
|
| 65 |
+
logger.info(f" -> Corresponding video clip found: {mp4_path.name}. Regenerating...")
|
| 66 |
+
# Re-render clip from the watermarked-free image
|
| 67 |
+
if generate_ken_burns_clip(img_path, mp4_path):
|
| 68 |
+
regenerated_count += 1
|
| 69 |
+
logger.info(f" -> Successfully regenerated video clip: {mp4_path.name}")
|
| 70 |
+
else:
|
| 71 |
+
logger.error(f" -> Failed to regenerate video clip: {mp4_path.name}")
|
| 72 |
+
else:
|
| 73 |
+
logger.warning(f" -> Watermark removal failed: {reason}")
|
| 74 |
+
|
| 75 |
+
logger.info("========================================")
|
| 76 |
+
logger.info("Watermark Processing Finished.")
|
| 77 |
+
logger.info(f"Total images scanned: {len(broll_images)}")
|
| 78 |
+
logger.info(f"Images flagged with watermarks: {flagged_count}")
|
| 79 |
+
logger.info(f"Images successfully inpainted: {removed_count}")
|
| 80 |
+
logger.info(f"Video clips successfully regenerated: {regenerated_count}")
|
| 81 |
+
logger.info("========================================")
|
| 82 |
+
|
| 83 |
+
if __name__ == "__main__":
|
| 84 |
+
main()
|
process_ready_videos_step.py
ADDED
|
@@ -0,0 +1,797 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import shutil
|
| 6 |
+
import urllib.request
|
| 7 |
+
import subprocess
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 11 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 12 |
+
|
| 13 |
+
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
ROOT_DIR = SCRIPT_DIR if os.path.exists(os.path.join(SCRIPT_DIR, "en-US")) else r"C:\ComfyUI\Articles"
|
| 15 |
+
WORKSPACE_DIR = os.path.dirname(SCRIPT_DIR)
|
| 16 |
+
COMFY_INPUT_DIR = r"C:\ComfyUI\input"
|
| 17 |
+
COMFY_OUTPUT_DIR = r"C:\ComfyUI\output"
|
| 18 |
+
|
| 19 |
+
def extract_main_word(title):
|
| 20 |
+
# Replace underscores and commas with spaces to handle words correctly
|
| 21 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 22 |
+
|
| 23 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 24 |
+
|
| 25 |
+
# Clean title from source marks
|
| 26 |
+
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)
|
| 27 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 28 |
+
|
| 29 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 30 |
+
|
| 31 |
+
def is_valid(word):
|
| 32 |
+
if not word:
|
| 33 |
+
return False
|
| 34 |
+
return word.strip().lower() not in blacklisted
|
| 35 |
+
|
| 36 |
+
# 1. Look for quotes like 「...」
|
| 37 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 38 |
+
for q in quotes_ja:
|
| 39 |
+
if is_valid(q):
|
| 40 |
+
return q
|
| 41 |
+
|
| 42 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 43 |
+
for q in quotes_en:
|
| 44 |
+
if len(q) < 25 and is_valid(q):
|
| 45 |
+
return q
|
| 46 |
+
|
| 47 |
+
# 2. Known key entities list
|
| 48 |
+
known_keywords = [
|
| 49 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 50 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 51 |
+
]
|
| 52 |
+
for kw in known_keywords:
|
| 53 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 54 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 55 |
+
if m:
|
| 56 |
+
return m.group(0)
|
| 57 |
+
|
| 58 |
+
if is_ja:
|
| 59 |
+
# Katakana sequences
|
| 60 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 61 |
+
for k in katakana:
|
| 62 |
+
if is_valid(k):
|
| 63 |
+
return k
|
| 64 |
+
# Kanji sequences
|
| 65 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 66 |
+
for k in kanji:
|
| 67 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 68 |
+
return k
|
| 69 |
+
if kanji:
|
| 70 |
+
for k in kanji:
|
| 71 |
+
if is_valid(k):
|
| 72 |
+
return k
|
| 73 |
+
# Alphabetic words
|
| 74 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 75 |
+
for a in alpha:
|
| 76 |
+
if is_valid(a):
|
| 77 |
+
return a
|
| 78 |
+
else:
|
| 79 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 80 |
+
if words:
|
| 81 |
+
for w in words:
|
| 82 |
+
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):
|
| 83 |
+
return w
|
| 84 |
+
for w in words:
|
| 85 |
+
if is_valid(w):
|
| 86 |
+
return w
|
| 87 |
+
|
| 88 |
+
first_token = re.search(r'\w+', cleaned)
|
| 89 |
+
if first_token and is_valid(first_token.group(0)):
|
| 90 |
+
return first_token.group(0)
|
| 91 |
+
|
| 92 |
+
return ""
|
| 93 |
+
|
| 94 |
+
def safe_filename(name, max_len=40):
|
| 95 |
+
main_word = extract_main_word(name).strip()
|
| 96 |
+
|
| 97 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 98 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
|
| 99 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 100 |
+
|
| 101 |
+
if main_word:
|
| 102 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 103 |
+
final_title = cleaned
|
| 104 |
+
else:
|
| 105 |
+
final_title = f"{main_word} {cleaned}"
|
| 106 |
+
else:
|
| 107 |
+
final_title = cleaned
|
| 108 |
+
|
| 109 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 110 |
+
|
| 111 |
+
if len(final_title) > max_len:
|
| 112 |
+
final_title = final_title[:max_len].strip()
|
| 113 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 114 |
+
|
| 115 |
+
return final_title
|
| 116 |
+
|
| 117 |
+
def get_gpu_stats():
|
| 118 |
+
try:
|
| 119 |
+
output = subprocess.check_output(
|
| 120 |
+
['nvidia-smi', '--query-gpu=utilization.gpu,memory.used,memory.total', '--format=csv,noheader,nounits'],
|
| 121 |
+
stderr=subprocess.DEVNULL
|
| 122 |
+
).decode().strip()
|
| 123 |
+
parts = output.split(',')
|
| 124 |
+
if len(parts) >= 3:
|
| 125 |
+
return {
|
| 126 |
+
"util": int(parts[0].strip()),
|
| 127 |
+
"mem_used": int(parts[1].strip()),
|
| 128 |
+
"mem_total": int(parts[2].strip())
|
| 129 |
+
}
|
| 130 |
+
except Exception:
|
| 131 |
+
pass
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
def is_gpu_actually_busy(threshold_util=25, threshold_mem_ratio=0.96):
|
| 135 |
+
stats = get_gpu_stats()
|
| 136 |
+
if stats is None:
|
| 137 |
+
return False
|
| 138 |
+
mem_ratio = stats["mem_used"] / stats["mem_total"]
|
| 139 |
+
if stats["util"] > threshold_util or mem_ratio > threshold_mem_ratio:
|
| 140 |
+
return True
|
| 141 |
+
return False
|
| 142 |
+
|
| 143 |
+
def is_port_open(host, port):
|
| 144 |
+
import socket
|
| 145 |
+
try:
|
| 146 |
+
with socket.create_connection((host, port), timeout=1):
|
| 147 |
+
return True
|
| 148 |
+
except OSError:
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
def get_comfyui_url():
|
| 152 |
+
if is_port_open("127.0.0.1", 8188):
|
| 153 |
+
return "http://127.0.0.1:8188"
|
| 154 |
+
if is_port_open("127.0.0.1", 7777):
|
| 155 |
+
return "http://127.0.0.1:7777"
|
| 156 |
+
return "http://127.0.0.1:8188"
|
| 157 |
+
|
| 158 |
+
def get_queue():
|
| 159 |
+
try:
|
| 160 |
+
url = get_comfyui_url()
|
| 161 |
+
req = urllib.request.Request(f"{url}/queue")
|
| 162 |
+
with urllib.request.urlopen(req, timeout=3) as response:
|
| 163 |
+
return json.loads(response.read().decode('utf-8'))
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Error connecting to ComfyUI ({get_comfyui_url()}): {e}")
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
def queue_prompt(prompt, client_id="video_generator_agent"):
|
| 169 |
+
p = {"prompt": prompt, "client_id": client_id}
|
| 170 |
+
data = json.dumps(p).encode('utf-8')
|
| 171 |
+
url = get_comfyui_url()
|
| 172 |
+
req = urllib.request.Request(f"{url}/prompt", data=data, headers={'Content-Type': 'application/json'})
|
| 173 |
+
with urllib.request.urlopen(req) as response:
|
| 174 |
+
return json.loads(response.read().decode('utf-8'))
|
| 175 |
+
|
| 176 |
+
def check_severe_assets():
|
| 177 |
+
avatar_exists = os.path.exists(os.path.join(COMFY_INPUT_DIR, "android_severe_upscale.png"))
|
| 178 |
+
voice_exists = os.path.exists(os.path.join(COMFY_INPUT_DIR, "android_severe.wav"))
|
| 179 |
+
return avatar_exists and voice_exists
|
| 180 |
+
|
| 181 |
+
def generate_youtube_metadata(article_path, dest_dir, safe_name, size):
|
| 182 |
+
# Try to find the original article title from the main markdown file
|
| 183 |
+
main_title = safe_name
|
| 184 |
+
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"]
|
| 185 |
+
article_summary = ""
|
| 186 |
+
source_info = ""
|
| 187 |
+
|
| 188 |
+
if main_md_files:
|
| 189 |
+
main_md_path = os.path.join(article_path, main_md_files[0])
|
| 190 |
+
try:
|
| 191 |
+
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
|
| 192 |
+
first_line = f.readline().strip()
|
| 193 |
+
if first_line.startswith("#"):
|
| 194 |
+
main_title = first_line.lstrip("#").strip()
|
| 195 |
+
else:
|
| 196 |
+
main_title = os.path.splitext(main_md_files[0])[0]
|
| 197 |
+
|
| 198 |
+
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
|
| 199 |
+
content = f.read().strip()
|
| 200 |
+
paragraphs = [p.strip() for p in content.split('\n') if p.strip()]
|
| 201 |
+
non_headers = [p for p in paragraphs if not p.startswith('#')]
|
| 202 |
+
if non_headers:
|
| 203 |
+
article_summary = non_headers[0]
|
| 204 |
+
|
| 205 |
+
for p in paragraphs:
|
| 206 |
+
if p.startswith("**Source:**"):
|
| 207 |
+
source_text = p.replace("**Source:**", "").strip()
|
| 208 |
+
match = re.search(r'\[([^\]]+)\]\(([^)]+)\)', source_text)
|
| 209 |
+
if match:
|
| 210 |
+
source_info = f"{match.group(1)} ({match.group(2)})"
|
| 211 |
+
else:
|
| 212 |
+
source_info = source_text
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f" Warning: Could not parse markdown for metadata: {e}")
|
| 215 |
+
|
| 216 |
+
suffix = f" ({size.capitalize()} Version)"
|
| 217 |
+
max_title_len = 100 - len(suffix)
|
| 218 |
+
if len(main_title) > max_title_len:
|
| 219 |
+
main_title = main_title[:max_title_len-3].strip() + "..."
|
| 220 |
+
|
| 221 |
+
main_title = f"{main_title}{suffix}"
|
| 222 |
+
|
| 223 |
+
script_text = ""
|
| 224 |
+
script_path = os.path.join(article_path, f"script_{size}_clean.txt")
|
| 225 |
+
if not os.path.exists(script_path):
|
| 226 |
+
script_path = os.path.join(article_path, f"script_{size}.md")
|
| 227 |
+
|
| 228 |
+
if os.path.exists(script_path):
|
| 229 |
+
try:
|
| 230 |
+
with open(script_path, "r", encoding="utf-8") as f:
|
| 231 |
+
script_text = f.read().strip()
|
| 232 |
+
except Exception:
|
| 233 |
+
pass
|
| 234 |
+
|
| 235 |
+
if script_path.endswith('.md') and script_text:
|
| 236 |
+
lines = script_text.splitlines()
|
| 237 |
+
cleaned_lines = []
|
| 238 |
+
for line in lines:
|
| 239 |
+
line = line.strip()
|
| 240 |
+
if not line or line.startswith('#'):
|
| 241 |
+
continue
|
| 242 |
+
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
|
| 243 |
+
line = re.sub(r'\([^)]*\)', '', line)
|
| 244 |
+
line = re.sub(r'\[[^\]]*\]', '', line)
|
| 245 |
+
line = line.replace('**', '').replace('*', '').strip()
|
| 246 |
+
if line:
|
| 247 |
+
cleaned_lines.append(line)
|
| 248 |
+
script_text = "\n\n".join(cleaned_lines)
|
| 249 |
+
|
| 250 |
+
metadata_lines = []
|
| 251 |
+
metadata_lines.append("=== YOUTUBE UPLOAD METADATA ===")
|
| 252 |
+
metadata_lines.append(f"SUGGESTED TITLE: {main_title}")
|
| 253 |
+
metadata_lines.append("===============================")
|
| 254 |
+
metadata_lines.append("")
|
| 255 |
+
metadata_lines.append("=== DESCRIPTION ===")
|
| 256 |
+
|
| 257 |
+
if script_text:
|
| 258 |
+
metadata_lines.append(script_text[:500] + ("..." if len(script_text) > 500 else ""))
|
| 259 |
+
elif article_summary:
|
| 260 |
+
metadata_lines.append(article_summary)
|
| 261 |
+
else:
|
| 262 |
+
metadata_lines.append(f"In this video: Latest news and updates about {main_title}.")
|
| 263 |
+
|
| 264 |
+
if source_info:
|
| 265 |
+
metadata_lines.append(f"\nSource: {source_info}")
|
| 266 |
+
else:
|
| 267 |
+
metadata_lines.append("\nSource: The Android Times / Provided News Sources")
|
| 268 |
+
|
| 269 |
+
metadata_lines.append("")
|
| 270 |
+
metadata_lines.append("--- Video Transcript ---")
|
| 271 |
+
if script_text:
|
| 272 |
+
metadata_lines.append(script_text)
|
| 273 |
+
else:
|
| 274 |
+
metadata_lines.append("(Transcript not available)")
|
| 275 |
+
|
| 276 |
+
metadata_lines.append("")
|
| 277 |
+
metadata_lines.append("--- About The Android Times ---")
|
| 278 |
+
metadata_lines.append("Your daily source for Android, AI, and technology news updates.")
|
| 279 |
+
metadata_lines.append("Subscribe to stay updated with the latest in tech!")
|
| 280 |
+
metadata_lines.append("")
|
| 281 |
+
metadata_lines.append(f"#Android #Tech #News #{size.capitalize()}")
|
| 282 |
+
metadata_lines.append("")
|
| 283 |
+
|
| 284 |
+
metadata_path = os.path.join(dest_dir, "youtube_metadata.txt")
|
| 285 |
+
try:
|
| 286 |
+
with open(metadata_path, "w", encoding="utf-8") as f:
|
| 287 |
+
f.write("\n".join(metadata_lines))
|
| 288 |
+
print(f" Generated YouTube metadata: {metadata_path}")
|
| 289 |
+
except Exception as e:
|
| 290 |
+
print(f" Error generating YouTube metadata file: {e}")
|
| 291 |
+
|
| 292 |
+
def package_youtube_assets(article_path, src_video_path, safe_name, size):
|
| 293 |
+
try:
|
| 294 |
+
youtube_dest_dir = os.path.join(WORKSPACE_DIR, "Youtube", f"{safe_name}_{size}")
|
| 295 |
+
os.makedirs(youtube_dest_dir, exist_ok=True)
|
| 296 |
+
|
| 297 |
+
# 1. Copy article folder contents to Youtube\<safe_name>_<size>
|
| 298 |
+
for item in os.listdir(article_path):
|
| 299 |
+
s_item = os.path.join(article_path, item)
|
| 300 |
+
d_item = os.path.join(youtube_dest_dir, item)
|
| 301 |
+
if os.path.isdir(s_item):
|
| 302 |
+
if item not in ["__pycache__", "images", "sources"]:
|
| 303 |
+
shutil.copytree(s_item, d_item, dirs_exist_ok=True)
|
| 304 |
+
else:
|
| 305 |
+
shutil.copy2(s_item, d_item)
|
| 306 |
+
|
| 307 |
+
# Copy the video .mp4 there too
|
| 308 |
+
youtube_video_dest = os.path.join(youtube_dest_dir, f"{safe_name}_{size}.mp4")
|
| 309 |
+
shutil.copy2(src_video_path, youtube_video_dest)
|
| 310 |
+
print(f" Successfully copied video to Youtube folder: {youtube_video_dest}")
|
| 311 |
+
|
| 312 |
+
# 2. Generate YouTube Metadata
|
| 313 |
+
generate_youtube_metadata(article_path, youtube_dest_dir, safe_name, size)
|
| 314 |
+
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print(f" Error packaging YouTube assets: {e}")
|
| 317 |
+
|
| 318 |
+
def get_all_article_directories():
|
| 319 |
+
article_paths = []
|
| 320 |
+
locales = ["en-US"]
|
| 321 |
+
for locale in locales:
|
| 322 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 323 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 324 |
+
continue
|
| 325 |
+
try:
|
| 326 |
+
categories = os.listdir(locale_path)
|
| 327 |
+
except OSError:
|
| 328 |
+
continue
|
| 329 |
+
for category in categories:
|
| 330 |
+
if category == "__pycache__":
|
| 331 |
+
continue
|
| 332 |
+
cat_path = os.path.join(locale_path, category)
|
| 333 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 334 |
+
continue
|
| 335 |
+
try:
|
| 336 |
+
articles = os.listdir(cat_path)
|
| 337 |
+
except OSError:
|
| 338 |
+
continue
|
| 339 |
+
for article in articles:
|
| 340 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 341 |
+
continue
|
| 342 |
+
article_path = os.path.join(cat_path, article)
|
| 343 |
+
if os.path.isdir(article_path):
|
| 344 |
+
article_paths.append(article_path)
|
| 345 |
+
return article_paths
|
| 346 |
+
|
| 347 |
+
def copy_talkvideos_to_articles():
|
| 348 |
+
talkvideo_dir = r"C:\Android Times\newsvideo"
|
| 349 |
+
if not os.path.exists(talkvideo_dir):
|
| 350 |
+
print(f"talkvideo directory not found: {talkvideo_dir}")
|
| 351 |
+
return
|
| 352 |
+
|
| 353 |
+
try:
|
| 354 |
+
video_files = [f for f in os.listdir(talkvideo_dir) if f.lower().endswith(".mp4")]
|
| 355 |
+
except OSError as e:
|
| 356 |
+
print(f"Error listing talkvideo directory: {e}")
|
| 357 |
+
return
|
| 358 |
+
|
| 359 |
+
if not video_files:
|
| 360 |
+
print("No video files found in talkvideo directory.")
|
| 361 |
+
return
|
| 362 |
+
|
| 363 |
+
article_dirs = get_all_article_directories()
|
| 364 |
+
|
| 365 |
+
copied_count = 0
|
| 366 |
+
for video_file in video_files:
|
| 367 |
+
src_path = os.path.join(talkvideo_dir, video_file)
|
| 368 |
+
|
| 369 |
+
# Parse prefix and suffix
|
| 370 |
+
base_name = os.path.splitext(video_file)[0]
|
| 371 |
+
size = None
|
| 372 |
+
for s in ["_short", "_middle", "_long"]:
|
| 373 |
+
if base_name.endswith(s):
|
| 374 |
+
size = s[1:]
|
| 375 |
+
prefix = base_name[:-len(s)]
|
| 376 |
+
break
|
| 377 |
+
else:
|
| 378 |
+
size = "middle"
|
| 379 |
+
prefix = base_name
|
| 380 |
+
|
| 381 |
+
normalized_prefix = prefix.strip().lower()
|
| 382 |
+
matched_article_path = None
|
| 383 |
+
|
| 384 |
+
# 1. Try exact matching
|
| 385 |
+
for art_path in article_dirs:
|
| 386 |
+
folder_name = os.path.basename(art_path)
|
| 387 |
+
if safe_filename(folder_name).strip().lower() == normalized_prefix:
|
| 388 |
+
matched_article_path = art_path
|
| 389 |
+
break
|
| 390 |
+
if folder_name.strip().lower() == normalized_prefix:
|
| 391 |
+
matched_article_path = art_path
|
| 392 |
+
break
|
| 393 |
+
if folder_name.replace('_', ' ').strip().lower() == normalized_prefix:
|
| 394 |
+
matched_article_path = art_path
|
| 395 |
+
break
|
| 396 |
+
|
| 397 |
+
# 2. Try word-based fallback matching if no exact match found
|
| 398 |
+
if not matched_article_path:
|
| 399 |
+
words = re.findall(r'[a-zA-Z0-9]+', prefix)
|
| 400 |
+
ignore_words = {"and", "the", "for", "with", "from", "that", "this", "our", "you", "your", "com"}
|
| 401 |
+
filtered_words = [w.lower() for w in words if len(w) >= 2 and w.lower() not in ignore_words]
|
| 402 |
+
|
| 403 |
+
if filtered_words:
|
| 404 |
+
candidates = []
|
| 405 |
+
for art_path in article_dirs:
|
| 406 |
+
folder_name = os.path.basename(art_path).replace('_', ' ').lower()
|
| 407 |
+
if all(w in folder_name for w in filtered_words):
|
| 408 |
+
candidates.append(art_path)
|
| 409 |
+
|
| 410 |
+
if len(candidates) == 1:
|
| 411 |
+
matched_article_path = candidates[0]
|
| 412 |
+
elif len(candidates) > 1:
|
| 413 |
+
# Filter candidates that have .flac files
|
| 414 |
+
candidates_with_flac = []
|
| 415 |
+
for c in candidates:
|
| 416 |
+
flac_files = [f for f in os.listdir(c) if f.lower().endswith(".flac")]
|
| 417 |
+
if flac_files:
|
| 418 |
+
candidates_with_flac.append(c)
|
| 419 |
+
|
| 420 |
+
if len(candidates_with_flac) == 1:
|
| 421 |
+
matched_article_path = candidates_with_flac[0]
|
| 422 |
+
elif len(candidates_with_flac) > 1:
|
| 423 |
+
candidates_with_flac.sort(key=lambda p: len(os.path.basename(p)))
|
| 424 |
+
matched_article_path = candidates_with_flac[0]
|
| 425 |
+
else:
|
| 426 |
+
candidates.sort(key=lambda p: len(os.path.basename(p)))
|
| 427 |
+
matched_article_path = candidates[0]
|
| 428 |
+
|
| 429 |
+
if matched_article_path:
|
| 430 |
+
folder_name = os.path.basename(matched_article_path)
|
| 431 |
+
safe_name = safe_filename(folder_name)
|
| 432 |
+
dest_filename = f"{safe_name}_{size}.mp4"
|
| 433 |
+
|
| 434 |
+
# Copy to ComfyUI articles folder
|
| 435 |
+
dest_path = os.path.join(matched_article_path, dest_filename)
|
| 436 |
+
|
| 437 |
+
# Copy to Workspace articles folder
|
| 438 |
+
rel_path = os.path.relpath(matched_article_path, ROOT_DIR)
|
| 439 |
+
workspace_dest_dir = os.path.join(WORKSPACE_DIR, "Articles", rel_path)
|
| 440 |
+
workspace_dest_path = os.path.join(workspace_dest_dir, dest_filename)
|
| 441 |
+
|
| 442 |
+
try:
|
| 443 |
+
src_size = os.path.getsize(src_path)
|
| 444 |
+
|
| 445 |
+
# Check ComfyUI target
|
| 446 |
+
comfy_updated = False
|
| 447 |
+
if (not os.path.exists(dest_path)) or (os.path.getsize(dest_path) != src_size):
|
| 448 |
+
print(f"Saving speaker video to ComfyUI article folder:")
|
| 449 |
+
print(f" {src_path} -> {dest_path}")
|
| 450 |
+
shutil.copy2(src_path, dest_path)
|
| 451 |
+
comfy_updated = True
|
| 452 |
+
copied_count += 1
|
| 453 |
+
|
| 454 |
+
# Check Workspace target
|
| 455 |
+
if (not os.path.exists(workspace_dest_path)) or (os.path.getsize(workspace_dest_path) != src_size):
|
| 456 |
+
print(f"Saving speaker video to Workspace article folder:")
|
| 457 |
+
print(f" {src_path} -> {workspace_dest_path}")
|
| 458 |
+
os.makedirs(workspace_dest_dir, exist_ok=True)
|
| 459 |
+
shutil.copy2(src_path, workspace_dest_path)
|
| 460 |
+
if not comfy_updated: # avoid double counting
|
| 461 |
+
copied_count += 1
|
| 462 |
+
|
| 463 |
+
except Exception as e:
|
| 464 |
+
print(f" Error copying {video_file}: {e}")
|
| 465 |
+
|
| 466 |
+
print(f"Speaker video sync finished. Copied/updated {copied_count} file(s).")
|
| 467 |
+
|
| 468 |
+
def main():
|
| 469 |
+
print(f"=== News Video Generator Step Utility: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
|
| 470 |
+
|
| 471 |
+
# Copy speaker videos from talkvideo to corresponding article directories
|
| 472 |
+
copy_talkvideos_to_articles()
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
if not (is_port_open("127.0.0.1", 8188) or is_port_open("127.0.0.1", 7777)):
|
| 476 |
+
print("Error: ComfyUI server is offline (ports 8188 / 7777).")
|
| 477 |
+
sys.exit(1)
|
| 478 |
+
|
| 479 |
+
queue_status = get_queue()
|
| 480 |
+
if queue_status is None:
|
| 481 |
+
sys.exit(1)
|
| 482 |
+
|
| 483 |
+
running_jobs = queue_status.get("queue_running", [])
|
| 484 |
+
pending_jobs = queue_status.get("queue_pending", [])
|
| 485 |
+
|
| 486 |
+
running_count = len(running_jobs)
|
| 487 |
+
pending_count = len(pending_jobs)
|
| 488 |
+
|
| 489 |
+
print(f"ComfyUI Status - Running: {running_count}, Pending: {pending_count}")
|
| 490 |
+
|
| 491 |
+
# 1. Scan for READY_FOR_VIDEO articles
|
| 492 |
+
locales = ["en-US"]
|
| 493 |
+
ready_articles = []
|
| 494 |
+
|
| 495 |
+
target_article = None
|
| 496 |
+
if len(sys.argv) > 1:
|
| 497 |
+
for i in range(1, len(sys.argv)):
|
| 498 |
+
if sys.argv[i] == "--article" and i + 1 < len(sys.argv):
|
| 499 |
+
target_article = sys.argv[i+1]
|
| 500 |
+
|
| 501 |
+
for locale in locales:
|
| 502 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 503 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 504 |
+
continue
|
| 505 |
+
|
| 506 |
+
try:
|
| 507 |
+
categories = os.listdir(locale_path)
|
| 508 |
+
except OSError:
|
| 509 |
+
continue
|
| 510 |
+
|
| 511 |
+
for category in categories:
|
| 512 |
+
if category == "__pycache__":
|
| 513 |
+
continue
|
| 514 |
+
cat_path = os.path.join(locale_path, category)
|
| 515 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 516 |
+
continue
|
| 517 |
+
|
| 518 |
+
try:
|
| 519 |
+
articles = os.listdir(cat_path)
|
| 520 |
+
except OSError:
|
| 521 |
+
continue
|
| 522 |
+
|
| 523 |
+
for article in articles:
|
| 524 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 525 |
+
continue
|
| 526 |
+
if target_article and target_article not in article:
|
| 527 |
+
continue
|
| 528 |
+
article_path = os.path.join(cat_path, article)
|
| 529 |
+
if not os.path.isdir(article_path):
|
| 530 |
+
continue
|
| 531 |
+
|
| 532 |
+
# Check evaluation status
|
| 533 |
+
eval_path = os.path.join(article_path, "evaluation_result.json")
|
| 534 |
+
if os.path.exists(eval_path):
|
| 535 |
+
try:
|
| 536 |
+
with open(eval_path, 'r', encoding='utf-8') as ef:
|
| 537 |
+
eval_data = ef.read()
|
| 538 |
+
if '"status": "READY_FOR_VIDEO"' in eval_data:
|
| 539 |
+
# Check tier (Only S/A tier: 1 or 2)
|
| 540 |
+
json_path = os.path.join(article_path, f"{article}.json")
|
| 541 |
+
if not os.path.exists(json_path):
|
| 542 |
+
continue
|
| 543 |
+
try:
|
| 544 |
+
with open(json_path, 'r', encoding='utf-8') as jf:
|
| 545 |
+
meta = json.load(jf)
|
| 546 |
+
if meta.get("tier") not in [1, 2]:
|
| 547 |
+
continue
|
| 548 |
+
except Exception as te:
|
| 549 |
+
print(f"Warning: Failed to read tier for {article}: {te}")
|
| 550 |
+
continue
|
| 551 |
+
|
| 552 |
+
safe_name = safe_filename(article)
|
| 553 |
+
|
| 554 |
+
# Migrate legacy [safe_name].mp4 to [safe_name]_middle.mp4 if it exists
|
| 555 |
+
legacy_video = os.path.join(article_path, f"{safe_name}.mp4")
|
| 556 |
+
migrated_video = os.path.join(article_path, f"{safe_name}_middle.mp4")
|
| 557 |
+
if os.path.exists(legacy_video) and not os.path.exists(migrated_video):
|
| 558 |
+
try:
|
| 559 |
+
shutil.move(legacy_video, migrated_video)
|
| 560 |
+
print(f"Migrated legacy video for {article} to _middle.mp4")
|
| 561 |
+
except Exception as me:
|
| 562 |
+
print(f"Warning: Failed to migrate legacy video: {me}")
|
| 563 |
+
|
| 564 |
+
# Find which of the sizes are missing
|
| 565 |
+
missing_sizes = []
|
| 566 |
+
for sz in ["middle", "short", "long"]:
|
| 567 |
+
if not os.path.exists(os.path.join(article_path, f"{safe_name}_{sz}.mp4")):
|
| 568 |
+
missing_sizes.append(sz)
|
| 569 |
+
|
| 570 |
+
if missing_sizes:
|
| 571 |
+
ready_articles.append({
|
| 572 |
+
"path": article_path,
|
| 573 |
+
"category": category,
|
| 574 |
+
"locale": locale,
|
| 575 |
+
"name": article,
|
| 576 |
+
"missing_sizes": missing_sizes
|
| 577 |
+
})
|
| 578 |
+
except Exception as e:
|
| 579 |
+
print(f"Warning: Failed to read {eval_path}: {e}")
|
| 580 |
+
|
| 581 |
+
# Prioritize Moscow Attacks and War/Military categories
|
| 582 |
+
def get_priority(art):
|
| 583 |
+
path_lower = art["path"].lower()
|
| 584 |
+
score = 0
|
| 585 |
+
if "en-us" in path_lower:
|
| 586 |
+
score += 10000
|
| 587 |
+
if "en-us" in path_lower and "moscow_attacks" in path_lower:
|
| 588 |
+
score += 1000
|
| 589 |
+
elif "moscow_attacks" in path_lower:
|
| 590 |
+
score += 500
|
| 591 |
+
elif "war_and_military" in path_lower:
|
| 592 |
+
score += 400
|
| 593 |
+
return score
|
| 594 |
+
|
| 595 |
+
ready_articles.sort(key=get_priority, reverse=True)
|
| 596 |
+
|
| 597 |
+
# 2. Check for completed videos in ComfyUI output directory and copy them
|
| 598 |
+
video_dir = os.path.join(COMFY_OUTPUT_DIR, "video")
|
| 599 |
+
if not os.path.exists(video_dir):
|
| 600 |
+
video_dir = os.path.join(r"C:\ComfyUI\output", "video")
|
| 601 |
+
|
| 602 |
+
copied_count = 0
|
| 603 |
+
if os.path.exists(video_dir):
|
| 604 |
+
for art in ready_articles:
|
| 605 |
+
safe_name = safe_filename(art["name"])
|
| 606 |
+
for sz in list(art["missing_sizes"]): # Use list copy to safely modify missing_sizes
|
| 607 |
+
try:
|
| 608 |
+
# ComfyUI output filenames will be prefixed with safe_name_sz
|
| 609 |
+
matching_files = [f for f in os.listdir(video_dir) if f.startswith(f"{safe_name}_{sz}") and f.endswith(".mp4")]
|
| 610 |
+
except OSError:
|
| 611 |
+
matching_files = []
|
| 612 |
+
if matching_files:
|
| 613 |
+
# Sort by modification time to get the latest
|
| 614 |
+
matching_files.sort(key=lambda f: os.path.getmtime(os.path.join(video_dir, f)), reverse=True)
|
| 615 |
+
latest_video = matching_files[0]
|
| 616 |
+
src_path = os.path.join(video_dir, latest_video)
|
| 617 |
+
dest_path = os.path.join(art["path"], f"{safe_name}_{sz}.mp4")
|
| 618 |
+
|
| 619 |
+
print(f"Found completed {sz} video for: {art['name']}")
|
| 620 |
+
print(f" Copying: {src_path} -> {dest_path}")
|
| 621 |
+
try:
|
| 622 |
+
shutil.copy2(src_path, dest_path)
|
| 623 |
+
print(" Successfully copied!")
|
| 624 |
+
package_youtube_assets(art["path"], src_path, safe_name, sz)
|
| 625 |
+
copied_count += 1
|
| 626 |
+
art["missing_sizes"].remove(sz)
|
| 627 |
+
except Exception as e:
|
| 628 |
+
print(f" Error copying file: {e}")
|
| 629 |
+
|
| 630 |
+
# Update ready list (exclude ones that have no missing sizes anymore)
|
| 631 |
+
if copied_count > 0:
|
| 632 |
+
ready_articles = [art for art in ready_articles if art["missing_sizes"]]
|
| 633 |
+
|
| 634 |
+
# Run sync script
|
| 635 |
+
copy_script = os.path.join(ROOT_DIR, "copy_passed_articles.py")
|
| 636 |
+
if os.path.exists(copy_script):
|
| 637 |
+
print("\nRunning copy_passed_articles.py to sync to workspace...")
|
| 638 |
+
try:
|
| 639 |
+
import subprocess
|
| 640 |
+
subprocess.run(["python", copy_script], check=True)
|
| 641 |
+
print("Sync completed successfully.")
|
| 642 |
+
except Exception as e:
|
| 643 |
+
print(f"Warning: Failed to sync: {e}")
|
| 644 |
+
|
| 645 |
+
# 3. Submit next job if ComfyUI is idle
|
| 646 |
+
if running_count == 0 and pending_count == 0:
|
| 647 |
+
if ready_articles:
|
| 648 |
+
# Check GPU utilization
|
| 649 |
+
if is_gpu_actually_busy(threshold_util=25):
|
| 650 |
+
print("ComfyUI queue is empty, but GPU is busy (possibly running TTS or other tasks). Suspending video generation job submission.")
|
| 651 |
+
sys.exit(0)
|
| 652 |
+
|
| 653 |
+
next_art = ready_articles[0]
|
| 654 |
+
# Select the highest priority missing size
|
| 655 |
+
script_type = next_art["missing_sizes"][0]
|
| 656 |
+
print(f"\nSubmitting next video generation job for: {next_art['name']} (Size: {script_type})")
|
| 657 |
+
|
| 658 |
+
# Find script and determine the matched script type
|
| 659 |
+
script_path = os.path.join(next_art["path"], f"script_{script_type}_clean.txt")
|
| 660 |
+
if not os.path.exists(script_path):
|
| 661 |
+
script_path = os.path.join(next_art["path"], f"script_{script_type}.md")
|
| 662 |
+
|
| 663 |
+
if not os.path.exists(script_path):
|
| 664 |
+
print(f" Error: No script file found for {script_type} in {next_art['path']}. Skipping.")
|
| 665 |
+
sys.exit(1)
|
| 666 |
+
|
| 667 |
+
try:
|
| 668 |
+
with open(script_path, 'r', encoding='utf-8') as f:
|
| 669 |
+
script_text = f.read().strip()
|
| 670 |
+
except Exception as e:
|
| 671 |
+
print(f" Error: Failed to read script file {script_path}: {e}")
|
| 672 |
+
sys.exit(1)
|
| 673 |
+
|
| 674 |
+
# Clean script text if md
|
| 675 |
+
if script_path.endswith('.md'):
|
| 676 |
+
lines = script_text.splitlines()
|
| 677 |
+
cleaned_lines = []
|
| 678 |
+
for line in lines:
|
| 679 |
+
line = line.strip()
|
| 680 |
+
if not line or line.startswith('#'):
|
| 681 |
+
continue
|
| 682 |
+
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
|
| 683 |
+
line = re.sub(r'\([^)]*\)', '', line)
|
| 684 |
+
line = re.sub(r'\[[^\]]*\]', '', line)
|
| 685 |
+
line = line.replace('**', '').replace('*', '').strip()
|
| 686 |
+
if line:
|
| 687 |
+
cleaned_lines.append(line)
|
| 688 |
+
script_text = "\n\n".join(cleaned_lines)
|
| 689 |
+
|
| 690 |
+
if not script_text:
|
| 691 |
+
print(" Error: Cleaned script text is empty. Skipping.")
|
| 692 |
+
sys.exit(1)
|
| 693 |
+
|
| 694 |
+
# Determine severity
|
| 695 |
+
cat_lower = str(next_art["category"]).lower()
|
| 696 |
+
is_severe = "military" in cat_lower or "conflict" in cat_lower or "severe" in cat_lower or "attack" in cat_lower
|
| 697 |
+
|
| 698 |
+
use_severe_workflow = False
|
| 699 |
+
if is_severe:
|
| 700 |
+
if check_severe_assets():
|
| 701 |
+
use_severe_workflow = True
|
| 702 |
+
print(" Using severe category settings.")
|
| 703 |
+
else:
|
| 704 |
+
print(" Severe assets missing in ComfyUI/input. Falling back to normal settings.")
|
| 705 |
+
|
| 706 |
+
workflow_filename = "flat_prompt_severe.json" if use_severe_workflow else "flat_prompt.json"
|
| 707 |
+
workflow_path = os.path.join(WORKSPACE_DIR, workflow_filename)
|
| 708 |
+
if not os.path.exists(workflow_path):
|
| 709 |
+
workflow_path = os.path.join(ROOT_DIR, workflow_filename)
|
| 710 |
+
|
| 711 |
+
if not os.path.exists(workflow_path):
|
| 712 |
+
print(f" Error: Workflow JSON not found at {workflow_path}.")
|
| 713 |
+
sys.exit(1)
|
| 714 |
+
|
| 715 |
+
try:
|
| 716 |
+
with open(workflow_path, 'r', encoding='utf-8') as f:
|
| 717 |
+
workflow = json.load(f)
|
| 718 |
+
except Exception as e:
|
| 719 |
+
print(f" Error: Failed to load workflow JSON {workflow_path}: {e}")
|
| 720 |
+
sys.exit(1)
|
| 721 |
+
|
| 722 |
+
workflow["42"]["inputs"]["text"] = script_text
|
| 723 |
+
|
| 724 |
+
# Find pre-generated voiceover audio in the article directory matching the script type
|
| 725 |
+
audio_files = [f for f in os.listdir(next_art["path"]) if f.lower().endswith(('.flac', '.wav', '.mp3'))]
|
| 726 |
+
if audio_files:
|
| 727 |
+
# Try to find a file matching the specific script type (short, long, or middle/standard)
|
| 728 |
+
audio_file = None
|
| 729 |
+
if script_type == "short":
|
| 730 |
+
matched = [f for f in audio_files if "_short_" in f.lower()]
|
| 731 |
+
if matched: audio_file = matched[0]
|
| 732 |
+
elif script_type == "long":
|
| 733 |
+
matched = [f for f in audio_files if "_long_" in f.lower()]
|
| 734 |
+
if matched: audio_file = matched[0]
|
| 735 |
+
else: # middle
|
| 736 |
+
matched = [f for f in audio_files if "_indextts" in f.lower() and "_short_" not in f.lower() and "_long_" not in f.lower()]
|
| 737 |
+
if matched: audio_file = matched[0]
|
| 738 |
+
|
| 739 |
+
# Fallback to any flac or audio file if specific match not found
|
| 740 |
+
if not audio_file:
|
| 741 |
+
main_audio = [f for f in audio_files if f.lower().endswith('.flac')]
|
| 742 |
+
if not main_audio:
|
| 743 |
+
main_audio = audio_files
|
| 744 |
+
audio_file = main_audio[0]
|
| 745 |
+
|
| 746 |
+
src_audio_path = os.path.join(next_art["path"], audio_file)
|
| 747 |
+
dest_audio_name = f"temp_ready_audio{os.path.splitext(audio_file)[1]}"
|
| 748 |
+
dest_audio_path = os.path.join(COMFY_INPUT_DIR, dest_audio_name)
|
| 749 |
+
|
| 750 |
+
print(f" Found pre-generated voiceover audio: {audio_file} (matched to {script_type} script)")
|
| 751 |
+
print(f" Copying: {src_audio_path} -> {dest_audio_path}")
|
| 752 |
+
try:
|
| 753 |
+
shutil.copy2(src_audio_path, dest_audio_path)
|
| 754 |
+
if "66_73" in workflow:
|
| 755 |
+
workflow["66_73"]["inputs"]["audio"] = dest_audio_name
|
| 756 |
+
print(f" Updated LoadAudio node to load: {dest_audio_name}")
|
| 757 |
+
elif "66:73" in workflow:
|
| 758 |
+
workflow["66:73"]["inputs"]["audio"] = dest_audio_name
|
| 759 |
+
print(f" Updated LoadAudio node to load: {dest_audio_name}")
|
| 760 |
+
else:
|
| 761 |
+
print(" Warning: LoadAudio node 66_73 (or 66:73) not found in workflow.")
|
| 762 |
+
except Exception as copy_err:
|
| 763 |
+
print(f" Warning: Failed to copy voiceover audio: {copy_err}")
|
| 764 |
+
else:
|
| 765 |
+
print(" Warning: No pre-generated voiceover audio found in article directory.")
|
| 766 |
+
|
| 767 |
+
safe_name = safe_filename(next_art["name"])
|
| 768 |
+
|
| 769 |
+
# Support both SaveVideo node ID 78 and 97
|
| 770 |
+
save_video_id = None
|
| 771 |
+
if "78" in workflow:
|
| 772 |
+
save_video_id = "78"
|
| 773 |
+
elif "97" in workflow:
|
| 774 |
+
save_video_id = "97"
|
| 775 |
+
|
| 776 |
+
if save_video_id:
|
| 777 |
+
workflow[save_video_id]["inputs"]["filename_prefix"] = f"video/{safe_name}_{script_type}"
|
| 778 |
+
print(f" Updated SaveVideo node {save_video_id} filename_prefix.")
|
| 779 |
+
else:
|
| 780 |
+
print(" Warning: SaveVideo node 78 or 97 not found in workflow.")
|
| 781 |
+
|
| 782 |
+
try:
|
| 783 |
+
res = queue_prompt(workflow)
|
| 784 |
+
prompt_id = res.get("prompt_id")
|
| 785 |
+
print(f" Success! Job queued in ComfyUI. Prompt ID: {prompt_id}")
|
| 786 |
+
except Exception as e:
|
| 787 |
+
print(f" Error submitting prompt to ComfyUI: {e}")
|
| 788 |
+
sys.exit(1)
|
| 789 |
+
else:
|
| 790 |
+
print("No articles are ready for video generation.")
|
| 791 |
+
else:
|
| 792 |
+
# Check if the running job has our client ID
|
| 793 |
+
running_prompts = [x[1] for x in running_jobs]
|
| 794 |
+
print(f"Active Job in ComfyUI: {running_prompts}")
|
| 795 |
+
|
| 796 |
+
if __name__ == "__main__":
|
| 797 |
+
main()
|
quality_gate_articles.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
import difflib
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import litert_lm
|
| 10 |
+
except ImportError:
|
| 11 |
+
litert_lm = None
|
| 12 |
+
|
| 13 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 14 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 15 |
+
|
| 16 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 17 |
+
SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json")
|
| 18 |
+
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
|
| 19 |
+
|
| 20 |
+
def get_existing_article_titles():
|
| 21 |
+
"""
|
| 22 |
+
Scan category directories under locales (en-US, en-EU, ja-JP) to collect
|
| 23 |
+
existing sanitized titles/folder names for duplicate detection.
|
| 24 |
+
"""
|
| 25 |
+
titles = set()
|
| 26 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 27 |
+
for locale in locales:
|
| 28 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 29 |
+
if not os.path.exists(loc_path):
|
| 30 |
+
continue
|
| 31 |
+
for cat in os.listdir(loc_path):
|
| 32 |
+
cat_path = os.path.join(loc_path, cat)
|
| 33 |
+
if not os.path.isdir(cat_path) or cat == "__pycache__":
|
| 34 |
+
continue
|
| 35 |
+
for art in os.listdir(cat_path):
|
| 36 |
+
art_path = os.path.join(cat_path, art)
|
| 37 |
+
if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]:
|
| 38 |
+
titles.add(art.lower())
|
| 39 |
+
titles.add(art.replace('_', ' ').lower())
|
| 40 |
+
return titles
|
| 41 |
+
|
| 42 |
+
def is_duplicate(new_title, existing_titles, current_batch_titles, threshold=0.8):
|
| 43 |
+
"""
|
| 44 |
+
Check if a new article title is a duplicate of past articles or current batch.
|
| 45 |
+
Uses SequenceMatcher ratio with a length-difference speed filter.
|
| 46 |
+
"""
|
| 47 |
+
new_title_clean = new_title.strip().lower()
|
| 48 |
+
|
| 49 |
+
# 1. Exact matches
|
| 50 |
+
if new_title_clean in existing_titles or new_title_clean in current_batch_titles:
|
| 51 |
+
return True, "Exact title match"
|
| 52 |
+
|
| 53 |
+
# 2. Similarity checks against existing articles
|
| 54 |
+
for ext_title in existing_titles:
|
| 55 |
+
# Fast optimization: skip if length difference is too large
|
| 56 |
+
if abs(len(new_title_clean) - len(ext_title)) > max(10, len(new_title_clean) * 0.4):
|
| 57 |
+
continue
|
| 58 |
+
ratio = difflib.SequenceMatcher(None, new_title_clean, ext_title).ratio()
|
| 59 |
+
if ratio >= threshold:
|
| 60 |
+
return True, f"High similarity ({int(ratio*100)}%) with existing article: '{ext_title}'"
|
| 61 |
+
|
| 62 |
+
# 3. Similarity checks against current batch
|
| 63 |
+
for cur_title in current_batch_titles:
|
| 64 |
+
if abs(len(new_title_clean) - len(cur_title)) > max(10, len(new_title_clean) * 0.4):
|
| 65 |
+
continue
|
| 66 |
+
ratio = difflib.SequenceMatcher(None, new_title_clean, cur_title).ratio()
|
| 67 |
+
if ratio >= threshold:
|
| 68 |
+
return True, f"High similarity ({int(ratio*100)}%) with another article in this batch: '{cur_title}'"
|
| 69 |
+
|
| 70 |
+
return False, ""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def clean_article_text(markdown_content):
|
| 74 |
+
"""
|
| 75 |
+
Remove markdown headers, metadata lines, image embeds, links, and common footers
|
| 76 |
+
to extract the pure body text of the article for similarity comparison.
|
| 77 |
+
"""
|
| 78 |
+
if not markdown_content:
|
| 79 |
+
return ""
|
| 80 |
+
|
| 81 |
+
lines = markdown_content.splitlines()
|
| 82 |
+
cleaned_lines = []
|
| 83 |
+
|
| 84 |
+
for line in lines:
|
| 85 |
+
line_strip = line.strip()
|
| 86 |
+
if not line_strip:
|
| 87 |
+
continue
|
| 88 |
+
if line_strip.startswith("#"):
|
| 89 |
+
continue
|
| 90 |
+
if line_strip.startswith("**Category:**") or line_strip.startswith("**Locale:**") or line_strip.startswith("**Source:**") or line_strip.startswith("**Date Collected:**"):
|
| 91 |
+
continue
|
| 92 |
+
if line_strip.startswith("!["):
|
| 93 |
+
continue
|
| 94 |
+
if line_strip == "---":
|
| 95 |
+
continue
|
| 96 |
+
if "*This article was automatically collected" in line_strip or "scraped" in line_strip.lower():
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
cleaned_lines.append(line_strip)
|
| 100 |
+
|
| 101 |
+
text = " ".join(cleaned_lines)
|
| 102 |
+
text = re.sub(r'<[^>]+>', '', text)
|
| 103 |
+
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
|
| 104 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 105 |
+
return text
|
| 106 |
+
|
| 107 |
+
def get_recent_article_bodies(max_per_category=30):
|
| 108 |
+
"""
|
| 109 |
+
Scan category directories under locales (en-US, en-EU, ja-JP) to collect
|
| 110 |
+
recent articles' markdown file paths, read their content, and return a dict of {title: cleaned_body}.
|
| 111 |
+
"""
|
| 112 |
+
recent_bodies = {}
|
| 113 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 114 |
+
for locale in locales:
|
| 115 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 116 |
+
if not os.path.exists(loc_path):
|
| 117 |
+
continue
|
| 118 |
+
for cat in os.listdir(loc_path):
|
| 119 |
+
cat_path = os.path.join(loc_path, cat)
|
| 120 |
+
if not os.path.isdir(cat_path) or cat == "__pycache__":
|
| 121 |
+
continue
|
| 122 |
+
|
| 123 |
+
articles = []
|
| 124 |
+
for art in os.listdir(cat_path):
|
| 125 |
+
art_path = os.path.join(cat_path, art)
|
| 126 |
+
if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]:
|
| 127 |
+
try:
|
| 128 |
+
mtime = os.path.getmtime(art_path)
|
| 129 |
+
articles.append((art, art_path, mtime))
|
| 130 |
+
except Exception:
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
articles.sort(key=lambda x: x[2], reverse=True)
|
| 134 |
+
for art, art_path, _ in articles[:max_per_category]:
|
| 135 |
+
md_file_name = f"{art}.md"
|
| 136 |
+
md_file_path = os.path.join(art_path, md_file_name)
|
| 137 |
+
if os.path.exists(md_file_path):
|
| 138 |
+
try:
|
| 139 |
+
with open(md_file_path, "r", encoding="utf-8") as f:
|
| 140 |
+
content = f.read()
|
| 141 |
+
cleaned = clean_article_text(content)
|
| 142 |
+
if cleaned:
|
| 143 |
+
recent_bodies[art.lower()] = cleaned
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"Error reading past article {md_file_path}: {e}")
|
| 146 |
+
return recent_bodies
|
| 147 |
+
|
| 148 |
+
def get_words(text):
|
| 149 |
+
"""
|
| 150 |
+
Extract alphanumeric words from text and normalize to lowercase.
|
| 151 |
+
For Japanese, extract character bi-grams (2-character pairs) to improve similarity precision.
|
| 152 |
+
"""
|
| 153 |
+
text_lower = text.lower()
|
| 154 |
+
is_ja = any(ord(char) > 0x3000 for char in text_lower)
|
| 155 |
+
if is_ja:
|
| 156 |
+
cleaned_chars = [char for char in text_lower if char.isalnum() and not char.isspace()]
|
| 157 |
+
bigrams = set()
|
| 158 |
+
for i in range(len(cleaned_chars) - 1):
|
| 159 |
+
bigrams.add(cleaned_chars[i] + cleaned_chars[i+1])
|
| 160 |
+
return bigrams
|
| 161 |
+
else:
|
| 162 |
+
return set(re.findall(r'\b[a-z0-9]+\b', text_lower))
|
| 163 |
+
|
| 164 |
+
def is_content_duplicate(new_text, existing_bodies, current_batch_bodies, jaccard_threshold=0.65, seq_threshold=0.70):
|
| 165 |
+
"""
|
| 166 |
+
Check if the cleaned new_text is a duplicate of existing articles or current batch.
|
| 167 |
+
Uses Jaccard word/bigram similarity as a fast pre-filter, followed by SequenceMatcher on prefix.
|
| 168 |
+
"""
|
| 169 |
+
new_cleaned = clean_article_text(new_text)
|
| 170 |
+
if not new_cleaned:
|
| 171 |
+
return False, ""
|
| 172 |
+
|
| 173 |
+
new_words = get_words(new_cleaned)
|
| 174 |
+
if not new_words:
|
| 175 |
+
return False, ""
|
| 176 |
+
|
| 177 |
+
# Check against existing articles
|
| 178 |
+
for ext_title, ext_body in existing_bodies.items():
|
| 179 |
+
ext_words = get_words(ext_body)
|
| 180 |
+
if not ext_words:
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
intersection = new_words.intersection(ext_words)
|
| 184 |
+
union = new_words.union(ext_words)
|
| 185 |
+
jaccard = len(intersection) / len(union) if union else 0.0
|
| 186 |
+
|
| 187 |
+
# Fast early-exit: Jaccard similarity must be at least 0.35 to be a candidate
|
| 188 |
+
if jaccard < 0.35:
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
new_prefix = new_cleaned[:1000]
|
| 192 |
+
ext_prefix = ext_body[:1000]
|
| 193 |
+
ratio = difflib.SequenceMatcher(None, new_prefix, ext_prefix).ratio()
|
| 194 |
+
|
| 195 |
+
# Strict AND condition to minimize false positives
|
| 196 |
+
if jaccard >= jaccard_threshold and ratio >= seq_threshold:
|
| 197 |
+
reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with existing article: '{ext_title}'"
|
| 198 |
+
return True, reason
|
| 199 |
+
|
| 200 |
+
# Check against current batch
|
| 201 |
+
for cur_title, cur_body in current_batch_bodies.items():
|
| 202 |
+
cur_words = get_words(cur_body)
|
| 203 |
+
if not cur_words:
|
| 204 |
+
continue
|
| 205 |
+
|
| 206 |
+
intersection = new_words.intersection(cur_words)
|
| 207 |
+
union = new_words.union(cur_words)
|
| 208 |
+
jaccard = len(intersection) / len(union) if union else 0.0
|
| 209 |
+
|
| 210 |
+
# Fast early-exit
|
| 211 |
+
if jaccard < 0.35:
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
new_prefix = new_cleaned[:1000]
|
| 215 |
+
cur_prefix = cur_body[:1000]
|
| 216 |
+
ratio = difflib.SequenceMatcher(None, new_prefix, cur_prefix).ratio()
|
| 217 |
+
|
| 218 |
+
# Strict AND condition
|
| 219 |
+
if jaccard >= jaccard_threshold and ratio >= seq_threshold:
|
| 220 |
+
reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with another article in this batch: '{cur_title}'"
|
| 221 |
+
return True, reason
|
| 222 |
+
|
| 223 |
+
return False, ""
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def load_json(path, default):
|
| 228 |
+
if os.path.exists(path):
|
| 229 |
+
try:
|
| 230 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 231 |
+
return json.load(f)
|
| 232 |
+
except Exception as e:
|
| 233 |
+
print(f"Failed to load JSON {path}: {e}")
|
| 234 |
+
return default
|
| 235 |
+
|
| 236 |
+
def save_json(path, data):
|
| 237 |
+
try:
|
| 238 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 239 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 240 |
+
except Exception as e:
|
| 241 |
+
print(f"Failed to save JSON {path}: {e}")
|
| 242 |
+
|
| 243 |
+
def evaluate_raw_markdown(markdown_content):
|
| 244 |
+
"""
|
| 245 |
+
Perform fast, hard-coded checks before sending to LLM.
|
| 246 |
+
Returns (is_valid: bool, reason: str)
|
| 247 |
+
"""
|
| 248 |
+
# 1. Length check
|
| 249 |
+
if len(markdown_content) < 150:
|
| 250 |
+
return False, "Article is too short (< 150 chars). Likely a scraping error or stub."
|
| 251 |
+
|
| 252 |
+
# 2. Regex Check: Scraping Errors
|
| 253 |
+
error_patterns = [
|
| 254 |
+
r"403\s+forbidden",
|
| 255 |
+
r"access\s+denied",
|
| 256 |
+
r"enable\s+javascript",
|
| 257 |
+
r"please\s+enable\s+cookies",
|
| 258 |
+
r"cloudflare",
|
| 259 |
+
r"captcha",
|
| 260 |
+
r"are\s+you\s+a\s+robot"
|
| 261 |
+
]
|
| 262 |
+
for pattern in error_patterns:
|
| 263 |
+
if re.search(pattern, markdown_content, re.IGNORECASE):
|
| 264 |
+
return False, f"Matches scraping error signature: '{pattern}'"
|
| 265 |
+
|
| 266 |
+
return True, "Pass"
|
| 267 |
+
|
| 268 |
+
def build_proofread_prompt(article_markdown):
|
| 269 |
+
prompt = f"""You are a strict News Quality Gatekeeper and Proofreader.
|
| 270 |
+
Your task is to evaluate the following scraped text.
|
| 271 |
+
|
| 272 |
+
Instructions:
|
| 273 |
+
1. If the text is an error page, a privacy policy, a captcha request, or pure spam, reply strictly and ONLY with the text: "REJECT: [Reason]".
|
| 274 |
+
2. If it is a valid news article, review it for grammatical correctness, natural flow, and factual consistency.
|
| 275 |
+
3. PRESERVE the exact formatting of the article, including Markdown headings (#, ##), bullets, and the footer section ("---" and below containing Author and Sources).
|
| 276 |
+
4. Output ONLY the corrected markdown text or the REJECT signal. Do not include any introductory or concluding remarks.
|
| 277 |
+
|
| 278 |
+
Article to evaluate:
|
| 279 |
+
{article_markdown}
|
| 280 |
+
"""
|
| 281 |
+
return prompt
|
| 282 |
+
|
| 283 |
+
def main():
|
| 284 |
+
print(f"Starting Quality Gate (READY_FOR_NEWS Evaluation) at {datetime.now().isoformat()}")
|
| 285 |
+
|
| 286 |
+
synthesis_data = load_json(SYNTHESIS_FILE, [])
|
| 287 |
+
if not synthesis_data:
|
| 288 |
+
print("No synthesis data found. Exiting Quality Gate.")
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
print(f"Total articles pending evaluation: {len(synthesis_data)}")
|
| 292 |
+
|
| 293 |
+
if not litert_lm:
|
| 294 |
+
print("litert_lm module not found. Falling back to hard-filters only.")
|
| 295 |
+
engine = None
|
| 296 |
+
else:
|
| 297 |
+
print(f"Loading LiteRT-LM engine for deep evaluation: {LITERT_MODEL_PATH}")
|
| 298 |
+
try:
|
| 299 |
+
engine = litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.CPU, max_num_tokens=8192)
|
| 300 |
+
except Exception as e:
|
| 301 |
+
print(f"LiteRT-LM Engine failure: {e}. Falling back to hard-filters only.")
|
| 302 |
+
engine = None
|
| 303 |
+
|
| 304 |
+
filtered_synthesis_data = []
|
| 305 |
+
rejected_count = 0
|
| 306 |
+
passed_count = 0
|
| 307 |
+
|
| 308 |
+
# Collect existing titles and bodies once at start
|
| 309 |
+
existing_titles = get_existing_article_titles()
|
| 310 |
+
print("Loading recent article bodies for content duplication check...")
|
| 311 |
+
existing_bodies = get_recent_article_bodies(max_per_category=30)
|
| 312 |
+
print(f"Loaded {len(existing_bodies)} recent article bodies.")
|
| 313 |
+
current_batch_processed_titles = set()
|
| 314 |
+
current_batch_processed_bodies = {} # {title: cleaned_body}
|
| 315 |
+
|
| 316 |
+
try:
|
| 317 |
+
for item in synthesis_data:
|
| 318 |
+
title = item.get("title", "Unknown Title")
|
| 319 |
+
markdown_content = item.get("markdown", "")
|
| 320 |
+
|
| 321 |
+
if not markdown_content:
|
| 322 |
+
print(f"REJECTED '{title}': Empty markdown content.")
|
| 323 |
+
rejected_count += 1
|
| 324 |
+
continue
|
| 325 |
+
|
| 326 |
+
print(f"Evaluating article: '{title}'...")
|
| 327 |
+
|
| 328 |
+
# Step 0: Duplicate Checks
|
| 329 |
+
is_dup, dup_reason = is_duplicate(title, existing_titles, current_batch_processed_titles)
|
| 330 |
+
if is_dup:
|
| 331 |
+
print(f" [REJECTED - Duplicate Title] {dup_reason}")
|
| 332 |
+
rejected_count += 1
|
| 333 |
+
continue
|
| 334 |
+
|
| 335 |
+
is_content_dup, content_dup_reason = is_content_duplicate(
|
| 336 |
+
markdown_content, existing_bodies, current_batch_processed_bodies
|
| 337 |
+
)
|
| 338 |
+
if is_content_dup:
|
| 339 |
+
print(f" [REJECTED - Duplicate Content] {content_dup_reason}")
|
| 340 |
+
rejected_count += 1
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
# Step 1: Hard Filters
|
| 344 |
+
is_valid, reason = evaluate_raw_markdown(markdown_content)
|
| 345 |
+
if not is_valid:
|
| 346 |
+
print(f" [REJECTED by Hard Filter] {reason}")
|
| 347 |
+
rejected_count += 1
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
# Truncate if ridiculously long, but 8192 tokens should be enough
|
| 351 |
+
if len(markdown_content) > 15000:
|
| 352 |
+
print(f" [FLAG] Article is extremely long. Skipping LLM proofread but passing through.")
|
| 353 |
+
item["status"] = "READY_FOR_NEWS"
|
| 354 |
+
filtered_synthesis_data.append(item)
|
| 355 |
+
passed_count += 1
|
| 356 |
+
continue
|
| 357 |
+
|
| 358 |
+
# Step 2: LLM Evaluation
|
| 359 |
+
if engine:
|
| 360 |
+
prompt = build_proofread_prompt(markdown_content)
|
| 361 |
+
try:
|
| 362 |
+
with engine.create_conversation() as conversation:
|
| 363 |
+
response = conversation.send_message(prompt)
|
| 364 |
+
output = response["content"][0]["text"].strip()
|
| 365 |
+
|
| 366 |
+
if output.startswith("REJECT:"):
|
| 367 |
+
print(f" [REJECTED by LLM] {output[7:].strip()}")
|
| 368 |
+
rejected_count += 1
|
| 369 |
+
continue
|
| 370 |
+
|
| 371 |
+
# Basic safety check: if model outputs something extremely short, keep original
|
| 372 |
+
if len(output) > len(markdown_content) * 0.5:
|
| 373 |
+
item["markdown"] = output
|
| 374 |
+
print(f" [PASS] Successfully evaluated and proofread.")
|
| 375 |
+
else:
|
| 376 |
+
print(f" [PASS with Warning] Corrected output seems too short. Using original.")
|
| 377 |
+
|
| 378 |
+
except Exception as model_err:
|
| 379 |
+
print(f" [PASS with Warning] Error during LLM evaluation: {model_err}. Using original text.")
|
| 380 |
+
else:
|
| 381 |
+
print(" [PASS] Evaluated via hard-filter only (LLM offline).")
|
| 382 |
+
|
| 383 |
+
item["status"] = "READY_FOR_NEWS"
|
| 384 |
+
filtered_synthesis_data.append(item)
|
| 385 |
+
current_batch_processed_titles.add(title.strip().lower())
|
| 386 |
+
|
| 387 |
+
# Store cleaned body for future comparisons in the same batch
|
| 388 |
+
cleaned_body = clean_article_text(markdown_content)
|
| 389 |
+
current_batch_processed_bodies[title.strip().lower()] = cleaned_body
|
| 390 |
+
|
| 391 |
+
passed_count += 1
|
| 392 |
+
|
| 393 |
+
finally:
|
| 394 |
+
if engine:
|
| 395 |
+
engine.close()
|
| 396 |
+
|
| 397 |
+
# Save the filtered results, dropping the rejected articles
|
| 398 |
+
if passed_count > 0 or rejected_count > 0:
|
| 399 |
+
save_json(SYNTHESIS_FILE, filtered_synthesis_data)
|
| 400 |
+
print("\n" + "="*40)
|
| 401 |
+
print("Quality Gate (READY_FOR_NEWS) Finished.")
|
| 402 |
+
print(f"Articles Passed: {passed_count}")
|
| 403 |
+
print(f"Articles Rejected & Dropped: {rejected_count}")
|
| 404 |
+
print(f"Filtered data saved to {SYNTHESIS_FILE}")
|
| 405 |
+
print("="*40)
|
| 406 |
+
else:
|
| 407 |
+
print("\nQuality Gate finished.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
import argparse
|
| 6 |
+
import subprocess
|
| 7 |
+
import logging
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import numpy as np
|
| 10 |
+
from PIL import Image, ImageFilter
|
| 11 |
+
|
| 12 |
+
# Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows
|
| 13 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 14 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 15 |
+
|
| 16 |
+
# Logging setup
|
| 17 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 18 |
+
logger = logging.getLogger("quality_gate_broll")
|
| 19 |
+
|
| 20 |
+
def validate_image_asset(img_path, min_width=500, min_height=300):
|
| 21 |
+
"""
|
| 22 |
+
Perform deep validation of a B-roll image file.
|
| 23 |
+
Checks: file existence, PIL verification, resolution, aspect ratio, blankness, and watermarks.
|
| 24 |
+
Returns: (bool, str) -> (is_valid, reason)
|
| 25 |
+
"""
|
| 26 |
+
path = Path(img_path)
|
| 27 |
+
if not path.exists():
|
| 28 |
+
return False, "File does not exist"
|
| 29 |
+
|
| 30 |
+
# Check minimum file size (e.g. 5KB)
|
| 31 |
+
try:
|
| 32 |
+
size = path.stat().st_size
|
| 33 |
+
if size < 5120:
|
| 34 |
+
return False, f"File size is too small ({size} bytes). Likely a corrupt download or placeholder."
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return False, f"Failed to get file stats: {e}"
|
| 37 |
+
|
| 38 |
+
# 1. PIL opening and integrity check
|
| 39 |
+
try:
|
| 40 |
+
with Image.open(path) as img:
|
| 41 |
+
img.verify() # verify integrity of the file container
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return False, f"Image container is corrupted or invalid: {e}"
|
| 44 |
+
|
| 45 |
+
# Re-open because verify() makes the file handle unusable
|
| 46 |
+
try:
|
| 47 |
+
with Image.open(path) as img:
|
| 48 |
+
w, h = img.size
|
| 49 |
+
|
| 50 |
+
# 2. Resolution check
|
| 51 |
+
if w < min_width or h < min_height:
|
| 52 |
+
return False, f"Resolution too low ({w}x{h}). Minimum required is {min_width}x{min_height}."
|
| 53 |
+
|
| 54 |
+
# 3. Aspect Ratio check
|
| 55 |
+
aspect = w / h
|
| 56 |
+
# Normal landscape should be around 1.33 to 1.78.
|
| 57 |
+
# Reject vertical portrait (aspect < 0.75) and extreme panoramas (aspect > 2.5)
|
| 58 |
+
if aspect < 0.75:
|
| 59 |
+
return False, f"Asset is vertical / portrait (aspect ratio: {aspect:.2f}). 16:9 crop will lose context."
|
| 60 |
+
if aspect > 2.5:
|
| 61 |
+
return False, f"Asset is too wide / panoramic (aspect ratio: {aspect:.2f}). 16:9 crop will look extremely stretched or cropped."
|
| 62 |
+
|
| 63 |
+
# 4. Blank screen / Solid color check
|
| 64 |
+
# Convert to grayscale to simplify calculation
|
| 65 |
+
gray_img = img.convert("L")
|
| 66 |
+
arr = np.array(gray_img, dtype=np.float32)
|
| 67 |
+
std_dev = np.std(arr)
|
| 68 |
+
# A standard deviation < 5.0 indicates almost zero contrast (solid color / blank / broken download)
|
| 69 |
+
if std_dev < 5.0:
|
| 70 |
+
return False, f"Blank or solid color image detected (standard deviation: {std_dev:.2f})."
|
| 71 |
+
|
| 72 |
+
# 5. Watermark / logo detection
|
| 73 |
+
detected = detect_watermarks(img_path)
|
| 74 |
+
if detected:
|
| 75 |
+
return False, f"Watermark or logo pattern detected in regions: {detected}."
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return False, f"Unexpected error during visual analysis: {e}"
|
| 79 |
+
|
| 80 |
+
return True, "Pass"
|
| 81 |
+
|
| 82 |
+
def detect_watermarks(img_path):
|
| 83 |
+
"""
|
| 84 |
+
Scan the corners and central-right/bottom-center of the image and return a list of regions that contain watermarks.
|
| 85 |
+
"""
|
| 86 |
+
path = Path(img_path)
|
| 87 |
+
if not path.exists():
|
| 88 |
+
return []
|
| 89 |
+
|
| 90 |
+
# Check if the filename contains stock/news keywords for adaptive thresholding
|
| 91 |
+
path_lower = str(path).lower()
|
| 92 |
+
is_stock_source = any(x in path_lower for x in ["getty", "alamy", "stock", "shutter", "anadolu", "reuters", "exclusive", "refinery"])
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
with Image.open(path) as img:
|
| 96 |
+
w, h = img.size
|
| 97 |
+
gray_img = img.convert("L")
|
| 98 |
+
arr = np.array(gray_img, dtype=np.float32)
|
| 99 |
+
|
| 100 |
+
diff_x = np.abs(arr[:, 1:] - arr[:, :-1])
|
| 101 |
+
diff_y = np.abs(arr[1:, :] - arr[:-1, :])
|
| 102 |
+
edges = np.zeros_like(arr)
|
| 103 |
+
edges[:, :-1] += diff_x
|
| 104 |
+
edges[:-1, :] += diff_y
|
| 105 |
+
|
| 106 |
+
cw = int(w * 0.15)
|
| 107 |
+
ch = int(h * 0.15)
|
| 108 |
+
cw = max(cw, 10)
|
| 109 |
+
ch = max(ch, 10)
|
| 110 |
+
|
| 111 |
+
regions = {
|
| 112 |
+
"top_left": (0, 0, cw, ch),
|
| 113 |
+
"top_right": (w-cw, 0, w, ch),
|
| 114 |
+
"bottom_left": (0, h-ch, cw, h),
|
| 115 |
+
"bottom_right": (w-cw, h-ch, w, h),
|
| 116 |
+
"center_right": (int(w * 0.55), int(h * 0.45), int(w * 0.98), int(h * 0.80)),
|
| 117 |
+
"bottom_center": (int(w * 0.20), int(h * 0.82), int(w * 0.80), h),
|
| 118 |
+
"center": (int(w * 0.30), int(h * 0.30), int(w * 0.70), int(h * 0.70))
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
detected = []
|
| 122 |
+
for name, (x1, y1, x2, y2) in regions.items():
|
| 123 |
+
region = edges[y1:y2, x1:x2]
|
| 124 |
+
if region.size == 0:
|
| 125 |
+
continue
|
| 126 |
+
mean_edge = np.mean(region)
|
| 127 |
+
max_edge = np.max(region)
|
| 128 |
+
|
| 129 |
+
# Corner heuristics (normally low texture, so strict threshold)
|
| 130 |
+
if name in ["top_left", "top_right", "bottom_left", "bottom_right"]:
|
| 131 |
+
if mean_edge > 15.0 and max_edge > 150.0:
|
| 132 |
+
detected.append(name)
|
| 133 |
+
# Central/Bottom heuristics (higher natural texture, adaptive check to avoid false positives)
|
| 134 |
+
else:
|
| 135 |
+
if is_stock_source:
|
| 136 |
+
high_contrast_pixels = np.sum(region > 120.0)
|
| 137 |
+
# Detect even if the mean edge is diluted in a large region, as long as strong local edges exist
|
| 138 |
+
if (mean_edge > 5.0 and max_edge > 80.0 and high_contrast_pixels > 15) or (high_contrast_pixels > 40):
|
| 139 |
+
detected.append(name)
|
| 140 |
+
else:
|
| 141 |
+
if mean_edge > 20.0 and max_edge > 200.0:
|
| 142 |
+
high_contrast_pixels = np.sum(region > 200.0)
|
| 143 |
+
if high_contrast_pixels > 30:
|
| 144 |
+
detected.append(name)
|
| 145 |
+
return detected
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logger.error(f"Error checking watermarks for {img_path}: {e}")
|
| 148 |
+
return []
|
| 149 |
+
|
| 150 |
+
def generate_watermark_mask(img_path, output_mask_path, detected_corners=None):
|
| 151 |
+
"""
|
| 152 |
+
Generate a binary mask where detected watermark pixels are white (255) and dilated.
|
| 153 |
+
"""
|
| 154 |
+
path = Path(img_path)
|
| 155 |
+
if not path.exists():
|
| 156 |
+
return False
|
| 157 |
+
|
| 158 |
+
if detected_corners is None:
|
| 159 |
+
detected_corners = detect_watermarks(img_path)
|
| 160 |
+
|
| 161 |
+
if not detected_corners:
|
| 162 |
+
# Create empty mask if no corners detected
|
| 163 |
+
try:
|
| 164 |
+
with Image.open(path) as img:
|
| 165 |
+
mask = Image.new("L", img.size, color=0)
|
| 166 |
+
mask.save(output_mask_path, "JPEG")
|
| 167 |
+
return True
|
| 168 |
+
except Exception as e:
|
| 169 |
+
logger.error(f"Failed to create empty mask: {e}")
|
| 170 |
+
return False
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
with Image.open(path) as img:
|
| 174 |
+
w, h = img.size
|
| 175 |
+
gray_img = img.convert("L")
|
| 176 |
+
arr = np.array(gray_img, dtype=np.float32)
|
| 177 |
+
|
| 178 |
+
# Recompute edges to find watermark pixels
|
| 179 |
+
diff_x = np.abs(arr[:, 1:] - arr[:, :-1])
|
| 180 |
+
diff_y = np.abs(arr[1:, :] - arr[:-1, :])
|
| 181 |
+
edges = np.zeros_like(arr)
|
| 182 |
+
edges[:, :-1] += diff_x
|
| 183 |
+
edges[:-1, :] += diff_y
|
| 184 |
+
|
| 185 |
+
# Create a base black mask
|
| 186 |
+
mask_arr = np.zeros((h, w), dtype=np.uint8)
|
| 187 |
+
|
| 188 |
+
cw = int(w * 0.15)
|
| 189 |
+
ch = int(h * 0.15)
|
| 190 |
+
cw = max(cw, 10)
|
| 191 |
+
ch = max(ch, 10)
|
| 192 |
+
|
| 193 |
+
regions = {
|
| 194 |
+
"top_left": (0, 0, cw, ch),
|
| 195 |
+
"top_right": (w-cw, 0, w, ch),
|
| 196 |
+
"bottom_left": (0, h-ch, cw, h),
|
| 197 |
+
"bottom_right": (w-cw, h-ch, w, h),
|
| 198 |
+
"center_right": (int(w * 0.55), int(h * 0.45), int(w * 0.98), int(h * 0.80)),
|
| 199 |
+
"bottom_center": (int(w * 0.20), int(h * 0.82), int(w * 0.80), h),
|
| 200 |
+
"center": (int(w * 0.30), int(h * 0.30), int(w * 0.70), int(h * 0.70))
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
for name in detected_corners:
|
| 204 |
+
if name not in regions:
|
| 205 |
+
continue
|
| 206 |
+
x1, y1, x2, y2 = regions[name]
|
| 207 |
+
# In the region, pixels with edge strength > 15 are likely watermark strokes
|
| 208 |
+
region_edges = edges[y1:y2, x1:x2]
|
| 209 |
+
mask_region = np.zeros_like(region_edges, dtype=np.uint8)
|
| 210 |
+
mask_region[region_edges > 15.0] = 255
|
| 211 |
+
mask_arr[y1:y2, x1:x2] = mask_region
|
| 212 |
+
|
| 213 |
+
mask_img = Image.fromarray(mask_arr)
|
| 214 |
+
|
| 215 |
+
# Dilate the mask using PIL's MaxFilter to cover surrounding pixels of the watermark text/logo
|
| 216 |
+
dilated_mask = mask_img.filter(ImageFilter.MaxFilter(size=9))
|
| 217 |
+
|
| 218 |
+
# Save mask
|
| 219 |
+
dilated_mask.save(output_mask_path, "JPEG")
|
| 220 |
+
return True
|
| 221 |
+
|
| 222 |
+
except Exception as e:
|
| 223 |
+
logger.error(f"Error generating mask for {img_path}: {e}")
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
def remove_watermark_with_lama(img_path, output_path=None):
|
| 227 |
+
"""
|
| 228 |
+
Detect, mask, and inpaint watermark/logo out of the image using LaMa.
|
| 229 |
+
Then re-validate the result.
|
| 230 |
+
Returns: (bool, str) -> (success, reason)
|
| 231 |
+
"""
|
| 232 |
+
path = Path(img_path)
|
| 233 |
+
if not path.exists():
|
| 234 |
+
return False, "File does not exist"
|
| 235 |
+
|
| 236 |
+
if output_path is None:
|
| 237 |
+
output_path = img_path
|
| 238 |
+
|
| 239 |
+
detected_corners = detect_watermarks(img_path)
|
| 240 |
+
if not detected_corners:
|
| 241 |
+
return True, "No watermark detected"
|
| 242 |
+
|
| 243 |
+
logger.info(f"Watermark detected in corners {detected_corners} of {path.name}. Initiating removal...")
|
| 244 |
+
|
| 245 |
+
# Paths for temporary mask and temporary output
|
| 246 |
+
temp_mask_path = path.parent / f".temp_mask_{path.stem}.jpg"
|
| 247 |
+
temp_out_path = path.parent / f".temp_out_{path.stem}.jpg"
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
# 1. Generate mask
|
| 251 |
+
if not generate_watermark_mask(path, temp_mask_path, detected_corners):
|
| 252 |
+
return False, "Failed to generate watermark mask"
|
| 253 |
+
|
| 254 |
+
# 2. Run LaMa inpainting
|
| 255 |
+
lama_script = r"C:\Roaming\.agents\skills\lama-inpainting\lama_inpaint.py"
|
| 256 |
+
if not os.path.exists(lama_script):
|
| 257 |
+
return False, f"LaMa script not found at {lama_script}"
|
| 258 |
+
|
| 259 |
+
cmd = [
|
| 260 |
+
sys.executable,
|
| 261 |
+
lama_script,
|
| 262 |
+
"--image", str(path),
|
| 263 |
+
"--mask", str(temp_mask_path),
|
| 264 |
+
"--output", str(temp_out_path),
|
| 265 |
+
"--device", "cpu"
|
| 266 |
+
]
|
| 267 |
+
|
| 268 |
+
logger.info(f"Running LaMa inpainting: {' '.join(cmd)}")
|
| 269 |
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
|
| 270 |
+
|
| 271 |
+
if res.returncode != 0:
|
| 272 |
+
return False, f"LaMa inpainting script failed: {res.stderr.strip()}"
|
| 273 |
+
|
| 274 |
+
if not temp_out_path.exists():
|
| 275 |
+
return False, "LaMa script returned 0 but output file was not created"
|
| 276 |
+
|
| 277 |
+
# 3. Re-validate the output image
|
| 278 |
+
ok, reason = validate_image_asset(temp_out_path)
|
| 279 |
+
if not ok:
|
| 280 |
+
# If it failed because of watermark again, it means the removal failed or was incomplete
|
| 281 |
+
return False, f"Watermark removal validation failed: {reason}"
|
| 282 |
+
|
| 283 |
+
# 4. Overwrite/Save to target destination
|
| 284 |
+
out_path = Path(output_path)
|
| 285 |
+
if out_path.exists():
|
| 286 |
+
out_path.unlink()
|
| 287 |
+
temp_out_path.rename(out_path)
|
| 288 |
+
|
| 289 |
+
logger.info(f"Watermark successfully removed and verified for {path.name}")
|
| 290 |
+
return True, "Pass"
|
| 291 |
+
|
| 292 |
+
except subprocess.TimeoutExpired:
|
| 293 |
+
return False, "LaMa inpainting execution timed out"
|
| 294 |
+
except Exception as e:
|
| 295 |
+
logger.error(f"Unexpected error during watermark removal: {e}")
|
| 296 |
+
return False, f"Unexpected error during removal: {e}"
|
| 297 |
+
finally:
|
| 298 |
+
# Cleanup temp files
|
| 299 |
+
if temp_mask_path.exists():
|
| 300 |
+
temp_mask_path.unlink(missing_ok=True)
|
| 301 |
+
if temp_out_path.exists():
|
| 302 |
+
temp_out_path.unlink(missing_ok=True)
|
| 303 |
+
|
| 304 |
+
def validate_video_asset(video_path):
|
| 305 |
+
"""
|
| 306 |
+
Perform validation of a B-roll video file (Ken-Burns clip).
|
| 307 |
+
Checks: file existence, size, and container integrity using ffprobe.
|
| 308 |
+
Returns: (bool, str) -> (is_valid, reason)
|
| 309 |
+
"""
|
| 310 |
+
path = Path(video_path)
|
| 311 |
+
if not path.exists():
|
| 312 |
+
return False, "File does not exist"
|
| 313 |
+
|
| 314 |
+
try:
|
| 315 |
+
size = path.stat().st_size
|
| 316 |
+
if size < 10240: # 10KB minimum
|
| 317 |
+
return False, f"File size is too small ({size} bytes). Likely a failed render."
|
| 318 |
+
except Exception as e:
|
| 319 |
+
return False, f"Failed to get file stats: {e}"
|
| 320 |
+
|
| 321 |
+
# Use ffprobe to verify video integrity
|
| 322 |
+
ffprobe = os.environ.get("VIDEO_AGENT_FFPROBE", "ffprobe")
|
| 323 |
+
cmd = [
|
| 324 |
+
ffprobe, "-v", "error",
|
| 325 |
+
"-show_entries", "format=duration,size:stream=codec_type",
|
| 326 |
+
"-of", "json",
|
| 327 |
+
str(path)
|
| 328 |
+
]
|
| 329 |
+
try:
|
| 330 |
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
| 331 |
+
if res.returncode != 0:
|
| 332 |
+
return False, f"ffprobe container validation failed: {res.stderr.strip()}"
|
| 333 |
+
|
| 334 |
+
data = json.loads(res.stdout)
|
| 335 |
+
|
| 336 |
+
# Check duration
|
| 337 |
+
duration_str = data.get("format", {}).get("duration")
|
| 338 |
+
if not duration_str:
|
| 339 |
+
return False, "No duration found in video container metadata"
|
| 340 |
+
duration = float(duration_str)
|
| 341 |
+
if duration <= 0:
|
| 342 |
+
return False, f"Invalid video duration: {duration}s"
|
| 343 |
+
|
| 344 |
+
# Check for video stream
|
| 345 |
+
streams = data.get("streams", [])
|
| 346 |
+
has_video_stream = any(s.get("codec_type") == "video" for s in streams)
|
| 347 |
+
if not has_video_stream:
|
| 348 |
+
return False, "No video stream found in the container"
|
| 349 |
+
|
| 350 |
+
except subprocess.TimeoutExpired:
|
| 351 |
+
return False, "ffprobe container validation timed out"
|
| 352 |
+
except Exception as e:
|
| 353 |
+
return False, f"Failed to validate video container via ffprobe: {e}"
|
| 354 |
+
|
| 355 |
+
return True, "Pass"
|
| 356 |
+
|
| 357 |
+
def scan_and_cleanup_broll_database(db_path, dry_run=False):
|
| 358 |
+
"""
|
| 359 |
+
Scan the local SQLite DB, validate all registered B-roll video and source image assets,
|
| 360 |
+
delete failed ones, and clean up database records.
|
| 361 |
+
"""
|
| 362 |
+
if not os.path.exists(db_path):
|
| 363 |
+
logger.error(f"Database {db_path} does not exist.")
|
| 364 |
+
return {"error": "DB not found"}
|
| 365 |
+
|
| 366 |
+
conn = sqlite3.connect(db_path)
|
| 367 |
+
cursor = conn.cursor()
|
| 368 |
+
|
| 369 |
+
try:
|
| 370 |
+
cursor.execute("SELECT id, title, query, image_url, local_path FROM broll_assets")
|
| 371 |
+
rows = cursor.fetchall()
|
| 372 |
+
except Exception as e:
|
| 373 |
+
logger.error(f"Failed to query database: {e}")
|
| 374 |
+
conn.close()
|
| 375 |
+
return {"error": str(e)}
|
| 376 |
+
|
| 377 |
+
logger.info(f"Scanning {len(rows)} registered B-roll records...")
|
| 378 |
+
|
| 379 |
+
scanned = 0
|
| 380 |
+
passed = 0
|
| 381 |
+
failed_video = 0
|
| 382 |
+
failed_image = 0
|
| 383 |
+
missing_files = 0
|
| 384 |
+
deleted_records = []
|
| 385 |
+
|
| 386 |
+
# We will track which images are associated with which videos to locate the source images.
|
| 387 |
+
# The source images are typically in C:\ComfyUI\Broll\images with a name derived from URL hash and title.
|
| 388 |
+
# The database local_path points to the video (.mp4).
|
| 389 |
+
for row_id, title, query, url, local_path_str in rows:
|
| 390 |
+
scanned += 1
|
| 391 |
+
|
| 392 |
+
if not local_path_str:
|
| 393 |
+
logger.warning(f"Record ID {row_id} has empty local_path. Removing record.")
|
| 394 |
+
deleted_records.append(row_id)
|
| 395 |
+
missing_files += 1
|
| 396 |
+
continue
|
| 397 |
+
|
| 398 |
+
video_path = Path(local_path_str)
|
| 399 |
+
|
| 400 |
+
# Locate corresponding source image in ComfyUI\Broll\images
|
| 401 |
+
# The filename of the video is [hash]_[title].mp4 and the image is [hash]_[title].jpg
|
| 402 |
+
video_name = video_path.name
|
| 403 |
+
img_name = video_name.replace(".mp4", ".jpg")
|
| 404 |
+
img_path = Path(r"C:\ComfyUI\Broll\images") / img_name
|
| 405 |
+
|
| 406 |
+
# 1. Check file existence
|
| 407 |
+
if not video_path.exists():
|
| 408 |
+
logger.warning(f"Video file missing: {video_path}. Removing record.")
|
| 409 |
+
deleted_records.append(row_id)
|
| 410 |
+
missing_files += 1
|
| 411 |
+
# Clean up image if it exists
|
| 412 |
+
if img_path.exists() and not dry_run:
|
| 413 |
+
img_path.unlink()
|
| 414 |
+
continue
|
| 415 |
+
|
| 416 |
+
# 2. Validate Video
|
| 417 |
+
vid_ok, vid_reason = validate_video_asset(video_path)
|
| 418 |
+
if not vid_ok:
|
| 419 |
+
logger.warning(f"Video {video_name} failed Quality Gate: {vid_reason}")
|
| 420 |
+
failed_video += 1
|
| 421 |
+
deleted_records.append(row_id)
|
| 422 |
+
if not dry_run:
|
| 423 |
+
video_path.unlink(missing_ok=True)
|
| 424 |
+
if img_path.exists():
|
| 425 |
+
img_path.unlink(missing_ok=True)
|
| 426 |
+
continue
|
| 427 |
+
|
| 428 |
+
# 3. Validate Source Image (if exists)
|
| 429 |
+
if img_path.exists():
|
| 430 |
+
img_ok, img_reason = validate_image_asset(img_path)
|
| 431 |
+
if not img_ok:
|
| 432 |
+
# If failed because of watermark, try to remove it
|
| 433 |
+
if "Watermark" in img_reason:
|
| 434 |
+
logger.info(f"Source image {img_name} has watermark. Attempting automatic removal...")
|
| 435 |
+
if not dry_run:
|
| 436 |
+
removed, remove_reason = remove_watermark_with_lama(img_path)
|
| 437 |
+
if removed:
|
| 438 |
+
# Re-generate video because the old video has the watermark
|
| 439 |
+
logger.info(f"Watermark removed from image. Regenerating video clip {video_name}...")
|
| 440 |
+
try:
|
| 441 |
+
from collect_broll_agent import generate_ken_burns_clip
|
| 442 |
+
# Delete old video
|
| 443 |
+
video_path.unlink(missing_ok=True)
|
| 444 |
+
if generate_ken_burns_clip(img_path, video_path):
|
| 445 |
+
logger.info(f"Video regenerated successfully: {video_name}")
|
| 446 |
+
img_ok = True
|
| 447 |
+
else:
|
| 448 |
+
logger.error(f"Failed to regenerate video {video_name} from restored image")
|
| 449 |
+
except Exception as ex:
|
| 450 |
+
logger.error(f"Error during video regeneration: {ex}")
|
| 451 |
+
else:
|
| 452 |
+
logger.warning(f"Watermark removal failed for {img_name}: {remove_reason}")
|
| 453 |
+
|
| 454 |
+
if not img_ok:
|
| 455 |
+
logger.warning(f"Source image {img_name} failed Quality Gate: {img_reason}")
|
| 456 |
+
failed_image += 1
|
| 457 |
+
deleted_records.append(row_id)
|
| 458 |
+
if not dry_run:
|
| 459 |
+
video_path.unlink(missing_ok=True)
|
| 460 |
+
img_path.unlink(missing_ok=True)
|
| 461 |
+
continue
|
| 462 |
+
else:
|
| 463 |
+
# If the source image is missing but the video exists and is valid, we let it pass
|
| 464 |
+
# because the video is already compiled and good to go.
|
| 465 |
+
pass
|
| 466 |
+
|
| 467 |
+
passed += 1
|
| 468 |
+
|
| 469 |
+
# Apply database deletions
|
| 470 |
+
if deleted_records and not dry_run:
|
| 471 |
+
logger.info(f"Removing {len(deleted_records)} failed/missing records from database...")
|
| 472 |
+
try:
|
| 473 |
+
# SQLite supports up to 999 variables, chunk if needed
|
| 474 |
+
for i in range(0, len(deleted_records), 500):
|
| 475 |
+
chunk = deleted_records[i:i+500]
|
| 476 |
+
cursor.execute(f"DELETE FROM broll_assets WHERE id IN ({','.join('?' for _ in chunk)})", chunk)
|
| 477 |
+
conn.commit()
|
| 478 |
+
except Exception as e:
|
| 479 |
+
logger.error(f"Failed to delete records from DB: {e}")
|
| 480 |
+
|
| 481 |
+
conn.close()
|
| 482 |
+
|
| 483 |
+
summary = {
|
| 484 |
+
"scanned": scanned,
|
| 485 |
+
"passed": passed,
|
| 486 |
+
"failed_video": failed_video,
|
| 487 |
+
"failed_image": failed_image,
|
| 488 |
+
"missing_files": missing_files,
|
| 489 |
+
"deleted_records_count": len(deleted_records)
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
logger.info(f"Cleanup finished. Summary: {summary}")
|
| 493 |
+
return summary
|
| 494 |
+
|
| 495 |
+
def main():
|
| 496 |
+
parser = argparse.ArgumentParser(description="B-roll Quality Gate Scanner & Cleaner")
|
| 497 |
+
parser.add_argument("--db-path", type=str, default=r"C:\ComfyUI\Articles\broll_assets.db", help="Path to SQLite DB")
|
| 498 |
+
parser.add_argument("--cleanup", action="store_true", help="Perform database scanning and cleanup.")
|
| 499 |
+
parser.add_argument("--dry-run", action="store_true", help="Scan only, do not delete files or DB records.")
|
| 500 |
+
parser.add_argument("--image", type=str, help="Validate a single image file.")
|
| 501 |
+
parser.add_argument("--remove-watermark", action="store_true", help="Remove watermark from single image (must specify --image)")
|
| 502 |
+
parser.add_argument("--video", type=str, help="Validate a single video file.")
|
| 503 |
+
args = parser.parse_args()
|
| 504 |
+
|
| 505 |
+
if args.image:
|
| 506 |
+
if args.remove_watermark:
|
| 507 |
+
ok, reason = remove_watermark_with_lama(args.image)
|
| 508 |
+
print(f"Watermark removal for {args.image}: {'PASS' if ok else 'FAIL'}")
|
| 509 |
+
if not ok:
|
| 510 |
+
print(f"Reason: {reason}")
|
| 511 |
+
sys.exit(0 if ok else 1)
|
| 512 |
+
else:
|
| 513 |
+
ok, reason = validate_image_asset(args.image)
|
| 514 |
+
print(f"Image validation for {args.image}: {'PASS' if ok else 'FAIL'}")
|
| 515 |
+
if not ok:
|
| 516 |
+
print(f"Reason: {reason}")
|
| 517 |
+
sys.exit(0 if ok else 1)
|
| 518 |
+
|
| 519 |
+
if args.video:
|
| 520 |
+
ok, reason = validate_video_asset(args.video)
|
| 521 |
+
print(f"Video validation for {args.video}: {'PASS' if ok else 'FAIL'}")
|
| 522 |
+
if not ok:
|
| 523 |
+
print(f"Reason: {reason}")
|
| 524 |
+
sys.exit(0 if ok else 1)
|
| 525 |
+
|
| 526 |
+
if args.cleanup:
|
| 527 |
+
summary = scan_and_cleanup_broll_database(args.db_path, dry_run=args.dry_run)
|
| 528 |
+
print("\n=== Cleanup Scan Report ===")
|
| 529 |
+
print(json.dumps(summary, indent=4))
|
| 530 |
+
sys.exit(0)
|
| 531 |
+
|
| 532 |
+
parser.print_help()
|
| 533 |
+
|
| 534 |
+
if __name__ == "__main__":
|
| 535 |
+
main()
|
quality_gate_newsvideo.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import logging
|
| 8 |
+
import argparse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from fractions import Fraction
|
| 12 |
+
|
| 13 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 14 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 15 |
+
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
+
logger = logging.getLogger("quality_gate_newsvideo")
|
| 18 |
+
|
| 19 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 20 |
+
WORKSPACE_DIR = r"C:\Users\eggof\Desktop\Android Times"
|
| 21 |
+
NEWSVIDEO_DIR = r"C:\Android Times\newsvideo"
|
| 22 |
+
|
| 23 |
+
YT_MAX_FILE_SIZE_BYTES = 256 * 1024 * 1024 * 1024
|
| 24 |
+
YT_MAX_DURATION_SECONDS = 12 * 60 * 60
|
| 25 |
+
YT_MIN_FILE_SIZE_BYTES = 10240
|
| 26 |
+
YT_ACCEPTED_VIDEO_CODECS = {"h264", "hevc", "h265", "vp9", "av1", "vp8", "mpeg4", "mpeg2video", "mpeg1video", "prores", "dnxhd"}
|
| 27 |
+
YT_PREFERRED_VIDEO_CODEC = "h264"
|
| 28 |
+
YT_ACCEPTED_AUDIO_CODECS = {"aac", "mp3", "vorbis", "opus", "pcm_s16le", "pcm_s24le", "flac", "ac3", "eac3"}
|
| 29 |
+
YT_PREFERRED_AUDIO_CODEC = "aac"
|
| 30 |
+
YT_STANDARD_FRAME_RATES = {24, 25, 30, 48, 50, 60}
|
| 31 |
+
|
| 32 |
+
def extract_main_word(title):
|
| 33 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 34 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 35 |
+
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)
|
| 36 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 37 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 38 |
+
def is_valid(word):
|
| 39 |
+
if not word:
|
| 40 |
+
return False
|
| 41 |
+
return word.strip().lower() not in blacklisted
|
| 42 |
+
|
| 43 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 44 |
+
for q in quotes_ja:
|
| 45 |
+
if is_valid(q):
|
| 46 |
+
return q
|
| 47 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 48 |
+
for q in quotes_en:
|
| 49 |
+
if len(q) < 25 and is_valid(q):
|
| 50 |
+
return q
|
| 51 |
+
|
| 52 |
+
known_keywords = [
|
| 53 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 54 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 55 |
+
]
|
| 56 |
+
for kw in known_keywords:
|
| 57 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 58 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 59 |
+
if m:
|
| 60 |
+
return m.group(0)
|
| 61 |
+
if is_ja:
|
| 62 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 63 |
+
for k in katakana:
|
| 64 |
+
if is_valid(k):
|
| 65 |
+
return k
|
| 66 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 67 |
+
for k in kanji:
|
| 68 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 69 |
+
return k
|
| 70 |
+
if kanji:
|
| 71 |
+
for k in kanji:
|
| 72 |
+
if is_valid(k):
|
| 73 |
+
return k
|
| 74 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 75 |
+
for a in alpha:
|
| 76 |
+
if is_valid(a):
|
| 77 |
+
return a
|
| 78 |
+
else:
|
| 79 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 80 |
+
if words:
|
| 81 |
+
for w in words:
|
| 82 |
+
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):
|
| 83 |
+
return w
|
| 84 |
+
for w in words:
|
| 85 |
+
if is_valid(w):
|
| 86 |
+
return w
|
| 87 |
+
first_token = re.search(r'\w+', cleaned)
|
| 88 |
+
if first_token and is_valid(first_token.group(0)):
|
| 89 |
+
return first_token.group(0)
|
| 90 |
+
return ""
|
| 91 |
+
|
| 92 |
+
def safe_filename(name, max_len=40):
|
| 93 |
+
main_word = extract_main_word(name).strip()
|
| 94 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 95 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'`\(\)\[\]]', ' ', cleaned)
|
| 96 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 97 |
+
if main_word:
|
| 98 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 99 |
+
final_title = cleaned
|
| 100 |
+
else:
|
| 101 |
+
final_title = f"{main_word} {cleaned}"
|
| 102 |
+
else:
|
| 103 |
+
final_title = cleaned
|
| 104 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 105 |
+
if len(final_title) > max_len:
|
| 106 |
+
final_title = final_title[:max_len].strip()
|
| 107 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 108 |
+
return final_title
|
| 109 |
+
|
| 110 |
+
def _parse_frame_rate(r_frame_rate_str):
|
| 111 |
+
if not r_frame_rate_str:
|
| 112 |
+
return None
|
| 113 |
+
try:
|
| 114 |
+
if '/' in r_frame_rate_str:
|
| 115 |
+
num, den = r_frame_rate_str.split('/')
|
| 116 |
+
den = int(den)
|
| 117 |
+
if den == 0:
|
| 118 |
+
return None
|
| 119 |
+
return float(int(num)) / den
|
| 120 |
+
return float(r_frame_rate_str)
|
| 121 |
+
except (ValueError, ZeroDivisionError):
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
def validate_video(video_path):
|
| 125 |
+
path = Path(video_path)
|
| 126 |
+
details = {}
|
| 127 |
+
warnings = []
|
| 128 |
+
|
| 129 |
+
if not path.exists():
|
| 130 |
+
return False, "File does not exist", details, warnings
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
file_size = path.stat().st_size
|
| 134 |
+
details["file_size_bytes"] = file_size
|
| 135 |
+
details["file_size_mb"] = round(file_size / (1024 * 1024), 2)
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return False, f"Failed to get file stats: {e}", details, warnings
|
| 138 |
+
|
| 139 |
+
if file_size < YT_MIN_FILE_SIZE_BYTES:
|
| 140 |
+
return False, f"File size too small ({file_size} bytes). Likely a failed render.", details, warnings
|
| 141 |
+
|
| 142 |
+
if file_size > YT_MAX_FILE_SIZE_BYTES:
|
| 143 |
+
return False, f"File size ({details['file_size_mb']} MB) exceeds maximum of 256 GB", details, warnings
|
| 144 |
+
|
| 145 |
+
ffprobe = os.environ.get("VIDEO_AGENT_FFPROBE", "ffprobe")
|
| 146 |
+
cmd = [
|
| 147 |
+
ffprobe, "-v", "error",
|
| 148 |
+
"-show_entries",
|
| 149 |
+
"format=duration,size,bit_rate"
|
| 150 |
+
":stream=codec_type,codec_name,width,height,r_frame_rate,field_order,sample_rate,channels,bit_rate",
|
| 151 |
+
"-of", "json",
|
| 152 |
+
str(path)
|
| 153 |
+
]
|
| 154 |
+
try:
|
| 155 |
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 156 |
+
if res.returncode != 0:
|
| 157 |
+
return False, f"ffprobe validation failed: {res.stderr.strip()}", details, warnings
|
| 158 |
+
data = json.loads(res.stdout)
|
| 159 |
+
except subprocess.TimeoutExpired:
|
| 160 |
+
return False, "ffprobe validation timed out (30s)", details, warnings
|
| 161 |
+
except json.JSONDecodeError as e:
|
| 162 |
+
return False, f"ffprobe returned invalid JSON: {e}", details, warnings
|
| 163 |
+
except Exception as e:
|
| 164 |
+
return False, f"Failed to run ffprobe: {e}", details, warnings
|
| 165 |
+
|
| 166 |
+
fmt = data.get("format", {})
|
| 167 |
+
streams = data.get("streams", [])
|
| 168 |
+
|
| 169 |
+
duration_str = fmt.get("duration")
|
| 170 |
+
if not duration_str:
|
| 171 |
+
return False, "No duration found in container metadata", details, warnings
|
| 172 |
+
try:
|
| 173 |
+
duration = float(duration_str)
|
| 174 |
+
except ValueError:
|
| 175 |
+
return False, f"Invalid duration value: {duration_str}", details, warnings
|
| 176 |
+
|
| 177 |
+
details["duration_s"] = round(duration, 2)
|
| 178 |
+
|
| 179 |
+
if duration <= 0:
|
| 180 |
+
return False, f"Invalid video duration: {duration}s", details, warnings
|
| 181 |
+
if duration > YT_MAX_DURATION_SECONDS:
|
| 182 |
+
return False, f"Duration ({duration/3600:.1f}h) exceeds maximum of 12 hours", details, warnings
|
| 183 |
+
|
| 184 |
+
video_streams = [s for s in streams if s.get("codec_type") == "video"]
|
| 185 |
+
if not video_streams:
|
| 186 |
+
return False, "No video stream found", details, warnings
|
| 187 |
+
|
| 188 |
+
vs = video_streams[0]
|
| 189 |
+
|
| 190 |
+
video_codec = vs.get("codec_name", "unknown")
|
| 191 |
+
details["video_codec"] = video_codec
|
| 192 |
+
if video_codec not in YT_ACCEPTED_VIDEO_CODECS:
|
| 193 |
+
warnings.append(f"Video codec '{video_codec}' may not be accepted")
|
| 194 |
+
|
| 195 |
+
width = vs.get("width")
|
| 196 |
+
height = vs.get("height")
|
| 197 |
+
if width and height:
|
| 198 |
+
details["resolution"] = f"{width}x{height}"
|
| 199 |
+
|
| 200 |
+
r_frame_rate = vs.get("r_frame_rate")
|
| 201 |
+
fps = _parse_frame_rate(r_frame_rate)
|
| 202 |
+
if fps:
|
| 203 |
+
details["fps"] = round(fps, 2)
|
| 204 |
+
|
| 205 |
+
field_order = vs.get("field_order", "")
|
| 206 |
+
details["scan_type"] = field_order if field_order else "progressive"
|
| 207 |
+
|
| 208 |
+
audio_streams = [s for s in streams if s.get("codec_type") == "audio"]
|
| 209 |
+
if not audio_streams:
|
| 210 |
+
return False, "No audio stream found", details, warnings
|
| 211 |
+
|
| 212 |
+
aus = audio_streams[0]
|
| 213 |
+
|
| 214 |
+
audio_codec = aus.get("codec_name", "unknown")
|
| 215 |
+
details["audio_codec"] = audio_codec
|
| 216 |
+
|
| 217 |
+
sample_rate = aus.get("sample_rate")
|
| 218 |
+
if sample_rate:
|
| 219 |
+
details["audio_sample_rate"] = int(sample_rate)
|
| 220 |
+
|
| 221 |
+
channels = aus.get("channels")
|
| 222 |
+
if channels:
|
| 223 |
+
details["audio_channels"] = channels
|
| 224 |
+
|
| 225 |
+
bitrate_str = fmt.get("bit_rate")
|
| 226 |
+
if bitrate_str:
|
| 227 |
+
try:
|
| 228 |
+
bitrate_kbps = int(bitrate_str) // 1000
|
| 229 |
+
details["bitrate_kbps"] = bitrate_kbps
|
| 230 |
+
except (ValueError, TypeError):
|
| 231 |
+
pass
|
| 232 |
+
|
| 233 |
+
return True, "Pass", details, warnings
|
| 234 |
+
|
| 235 |
+
def evaluate_newsvideo_ready(article_dir, force=False, dry_run=False):
|
| 236 |
+
if not os.path.exists(article_dir):
|
| 237 |
+
logger.warning(f"Directory {article_dir} does not exist.")
|
| 238 |
+
return "REJECTED"
|
| 239 |
+
|
| 240 |
+
result_path = os.path.join(article_dir, "evaluation_result.json")
|
| 241 |
+
if not os.path.exists(result_path):
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
try:
|
| 245 |
+
with open(result_path, 'r', encoding='utf-8') as f:
|
| 246 |
+
results = json.load(f)
|
| 247 |
+
except Exception as e:
|
| 248 |
+
logger.error(f"Failed to read evaluation result from {result_path}: {e}")
|
| 249 |
+
return None
|
| 250 |
+
|
| 251 |
+
current_status = results.get("status", "")
|
| 252 |
+
if not force and current_status in ["READY_FOR_NEWSVIDEO", "YOUTUBE_READY"]:
|
| 253 |
+
return current_status
|
| 254 |
+
|
| 255 |
+
if current_status not in ["READY_FOR_VIDEO", "READY_FOR_NEWSVIDEO", "NEWSVIDEO_GATE_FAILED", "YOUTUBE_GATE_FAILED", "YOUTUBE_READY"]:
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
safe_name = safe_filename(os.path.basename(article_dir))
|
| 259 |
+
sizes = ["short", "middle", "long"]
|
| 260 |
+
|
| 261 |
+
# Check if videos actually exist before processing this gate
|
| 262 |
+
# If videos don't exist yet, it's likely they are still being generated, so skip for now.
|
| 263 |
+
videos_exist = True
|
| 264 |
+
for size in sizes:
|
| 265 |
+
video_file = f"{safe_name}_{size}.mp4"
|
| 266 |
+
video_path = os.path.join(article_dir, video_file)
|
| 267 |
+
if not os.path.exists(video_path):
|
| 268 |
+
video_path = os.path.join(NEWSVIDEO_DIR, video_file)
|
| 269 |
+
if not os.path.exists(video_path):
|
| 270 |
+
videos_exist = False
|
| 271 |
+
break
|
| 272 |
+
|
| 273 |
+
if not videos_exist:
|
| 274 |
+
# Videos are not all present, assume generation is pending. Do not fail the gate yet.
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
logger.info(f"Evaluating NewsVideo Gate for: {os.path.basename(article_dir)}")
|
| 278 |
+
|
| 279 |
+
if "checks" not in results:
|
| 280 |
+
results["checks"] = {}
|
| 281 |
+
|
| 282 |
+
results["checks"]["newsvideo_gate"] = {
|
| 283 |
+
"timestamp": datetime.now().isoformat(),
|
| 284 |
+
"status": "PENDING",
|
| 285 |
+
"video": {"status": "PENDING", "reason": "", "details": {}},
|
| 286 |
+
"warnings": []
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
if "reject_reasons" not in results:
|
| 290 |
+
results["reject_reasons"] = []
|
| 291 |
+
|
| 292 |
+
results["reject_reasons"] = [r for r in results["reject_reasons"] if not r.startswith("[NEWSVIDEO_GATE]")]
|
| 293 |
+
|
| 294 |
+
all_warnings = []
|
| 295 |
+
video_failures = []
|
| 296 |
+
video_details_all = {}
|
| 297 |
+
|
| 298 |
+
for size in sizes:
|
| 299 |
+
video_file = f"{safe_name}_{size}.mp4"
|
| 300 |
+
video_path = os.path.join(article_dir, video_file)
|
| 301 |
+
if not os.path.exists(video_path):
|
| 302 |
+
video_path = os.path.join(NEWSVIDEO_DIR, video_file)
|
| 303 |
+
ok, reason, details, warns = validate_video(video_path)
|
| 304 |
+
video_details_all[size] = details
|
| 305 |
+
if not ok:
|
| 306 |
+
video_failures.append(f"{size}: {reason}")
|
| 307 |
+
for w in warns:
|
| 308 |
+
all_warnings.append(f"{size} video: {w}")
|
| 309 |
+
|
| 310 |
+
if video_failures:
|
| 311 |
+
results["checks"]["newsvideo_gate"]["video"] = {
|
| 312 |
+
"status": "FAIL",
|
| 313 |
+
"reason": "; ".join(video_failures),
|
| 314 |
+
"details": video_details_all
|
| 315 |
+
}
|
| 316 |
+
else:
|
| 317 |
+
results["checks"]["newsvideo_gate"]["video"] = {
|
| 318 |
+
"status": "PASS",
|
| 319 |
+
"reason": "All sizes (short, middle, long) videos pass requirements",
|
| 320 |
+
"details": video_details_all
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
results["checks"]["newsvideo_gate"]["warnings"] = all_warnings
|
| 324 |
+
|
| 325 |
+
gate_ok = True
|
| 326 |
+
gate_reasons = []
|
| 327 |
+
|
| 328 |
+
sub_status = results["checks"]["newsvideo_gate"]["video"]["status"]
|
| 329 |
+
sub_reason = results["checks"]["newsvideo_gate"]["video"]["reason"]
|
| 330 |
+
if sub_status == "FAIL":
|
| 331 |
+
gate_ok = False
|
| 332 |
+
gate_reasons.append(f"[NEWSVIDEO_GATE] VIDEO FAIL: {sub_reason}")
|
| 333 |
+
|
| 334 |
+
if gate_ok:
|
| 335 |
+
results["checks"]["newsvideo_gate"]["status"] = "PASS"
|
| 336 |
+
results["status"] = "READY_FOR_NEWSVIDEO"
|
| 337 |
+
warn_summary = f" ({len(all_warnings)} warnings)" if all_warnings else ""
|
| 338 |
+
logger.info(f" -> Final Status: READY_FOR_NEWSVIDEO{warn_summary}")
|
| 339 |
+
else:
|
| 340 |
+
results["checks"]["newsvideo_gate"]["status"] = "FAIL"
|
| 341 |
+
results["status"] = "NEWSVIDEO_GATE_FAILED"
|
| 342 |
+
results["reject_reasons"].extend(gate_reasons)
|
| 343 |
+
logger.warning(f" -> Final Status: NEWSVIDEO_GATE_FAILED (Reasons: {gate_reasons})")
|
| 344 |
+
|
| 345 |
+
if not dry_run:
|
| 346 |
+
try:
|
| 347 |
+
with open(result_path, 'w', encoding='utf-8') as f:
|
| 348 |
+
json.dump(results, f, indent=4, ensure_ascii=False)
|
| 349 |
+
except Exception as e:
|
| 350 |
+
logger.error(f"Failed to save evaluation result to {result_path}: {e}")
|
| 351 |
+
else:
|
| 352 |
+
logger.info(f"[DRY-RUN] Would save evaluation result to {result_path}")
|
| 353 |
+
|
| 354 |
+
return results["status"]
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def main():
|
| 358 |
+
parser = argparse.ArgumentParser(
|
| 359 |
+
description="NewsVideo Ready Quality Gate — validates output news videos."
|
| 360 |
+
)
|
| 361 |
+
parser.add_argument("--locale", type=str, default=None, help="Locale to evaluate (default: all)")
|
| 362 |
+
parser.add_argument("--category", type=str, default=None, help="Category to evaluate")
|
| 363 |
+
parser.add_argument("--dry-run", action="store_true", help="Evaluate only, do not save status")
|
| 364 |
+
parser.add_argument("--force", action="store_true", help="Force evaluation even if already READY_FOR_NEWSVIDEO")
|
| 365 |
+
args = parser.parse_args()
|
| 366 |
+
|
| 367 |
+
locales = [args.locale] if args.locale else ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 368 |
+
|
| 369 |
+
article_dirs = []
|
| 370 |
+
for locale in locales:
|
| 371 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 372 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 373 |
+
continue
|
| 374 |
+
try:
|
| 375 |
+
categories = [args.category] if args.category else os.listdir(locale_path)
|
| 376 |
+
except OSError as e:
|
| 377 |
+
logger.error(f"Error listing categories in {locale_path}: {e}")
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
for category in categories:
|
| 381 |
+
cat_path = os.path.join(locale_path, category)
|
| 382 |
+
if not os.path.isdir(cat_path) or category == "__pycache__":
|
| 383 |
+
continue
|
| 384 |
+
try:
|
| 385 |
+
articles = os.listdir(cat_path)
|
| 386 |
+
except OSError:
|
| 387 |
+
continue
|
| 388 |
+
for article in articles:
|
| 389 |
+
article_dir = os.path.join(cat_path, article)
|
| 390 |
+
if os.path.isdir(article_dir) and article not in ["images", "sources", "__pycache__"]:
|
| 391 |
+
article_dirs.append(article_dir)
|
| 392 |
+
|
| 393 |
+
if not article_dirs:
|
| 394 |
+
logger.info("No articles found to evaluate.")
|
| 395 |
+
return
|
| 396 |
+
|
| 397 |
+
processed_count = 0
|
| 398 |
+
passed_count = 0
|
| 399 |
+
failed_count = 0
|
| 400 |
+
|
| 401 |
+
for idx, article_dir in enumerate(article_dirs):
|
| 402 |
+
status = evaluate_newsvideo_ready(article_dir, force=args.force, dry_run=args.dry_run)
|
| 403 |
+
if status:
|
| 404 |
+
processed_count += 1
|
| 405 |
+
if status == "READY_FOR_NEWSVIDEO":
|
| 406 |
+
passed_count += 1
|
| 407 |
+
elif status == "NEWSVIDEO_GATE_FAILED":
|
| 408 |
+
failed_count += 1
|
| 409 |
+
|
| 410 |
+
logger.info(f"Evaluation complete. Processed {processed_count} relevant articles.")
|
| 411 |
+
logger.info(f"Passed: {passed_count}, Failed: {failed_count}")
|
| 412 |
+
|
| 413 |
+
if __name__ == "__main__":
|
| 414 |
+
main()
|
quality_gate_youtube.py
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import logging
|
| 8 |
+
import argparse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from fractions import Fraction
|
| 13 |
+
|
| 14 |
+
# Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows
|
| 15 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 16 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 17 |
+
|
| 18 |
+
# Logging setup
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 20 |
+
logger = logging.getLogger("quality_gate_youtube")
|
| 21 |
+
|
| 22 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 23 |
+
WORKSPACE_DIR = r"C:\Users\eggof\Desktop\Android Times"
|
| 24 |
+
YOUTUBE_DIR = os.path.join(WORKSPACE_DIR, "Youtube")
|
| 25 |
+
|
| 26 |
+
# ============================================================================
|
| 27 |
+
# YouTube Official Specifications (from YouTube Data API v3 documentation
|
| 28 |
+
# and https://support.google.com/youtube/answer/1722171)
|
| 29 |
+
# ============================================================================
|
| 30 |
+
|
| 31 |
+
# Maximum file size: 256 GB
|
| 32 |
+
YT_MAX_FILE_SIZE_BYTES = 256 * 1024 * 1024 * 1024 # 256 GB
|
| 33 |
+
|
| 34 |
+
# Maximum duration: 12 hours (43200 seconds)
|
| 35 |
+
YT_MAX_DURATION_SECONDS = 12 * 60 * 60 # 43200s
|
| 36 |
+
|
| 37 |
+
# Minimum file size threshold for valid renders
|
| 38 |
+
YT_MIN_FILE_SIZE_BYTES = 10240 # 10 KB
|
| 39 |
+
|
| 40 |
+
# Accepted video codecs (YouTube re-encodes all uploads; H.264 preferred input)
|
| 41 |
+
YT_ACCEPTED_VIDEO_CODECS = {"h264", "hevc", "h265", "vp9", "av1", "vp8", "mpeg4", "mpeg2video", "mpeg1video", "prores", "dnxhd"}
|
| 42 |
+
YT_PREFERRED_VIDEO_CODEC = "h264"
|
| 43 |
+
|
| 44 |
+
# Accepted audio codecs (AAC-LC preferred at 48kHz, 192kbps+)
|
| 45 |
+
YT_ACCEPTED_AUDIO_CODECS = {"aac", "mp3", "vorbis", "opus", "pcm_s16le", "pcm_s24le", "flac", "ac3", "eac3"}
|
| 46 |
+
YT_PREFERRED_AUDIO_CODEC = "aac"
|
| 47 |
+
|
| 48 |
+
# Standard frame rates accepted by YouTube
|
| 49 |
+
YT_STANDARD_FRAME_RATES = {24, 25, 30, 48, 50, 60}
|
| 50 |
+
|
| 51 |
+
# YouTube recommended bitrates for SDR H.264 (kbps), keyed by vertical resolution
|
| 52 |
+
# Values are for standard frame rate (24/25/30); high frame rate values are ~1.5x
|
| 53 |
+
YT_RECOMMENDED_BITRATES_KBPS = {
|
| 54 |
+
2160: 35000, # 4K: 35-45 Mbps
|
| 55 |
+
1440: 16000, # 2K: 16 Mbps
|
| 56 |
+
1080: 8000, # 1080p: 8 Mbps
|
| 57 |
+
720: 5000, # 720p: 5 Mbps
|
| 58 |
+
480: 2500, # 480p: 2.5 Mbps
|
| 59 |
+
360: 1000, # 360p: 1 Mbps
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# Thumbnail specifications
|
| 63 |
+
YT_THUMB_MAX_SIZE_BYTES = 2 * 1024 * 1024 # 2 MB
|
| 64 |
+
YT_THUMB_RECOMMENDED_WIDTH = 1280
|
| 65 |
+
YT_THUMB_RECOMMENDED_HEIGHT = 720
|
| 66 |
+
YT_THUMB_MIN_WIDTH = 640
|
| 67 |
+
YT_THUMB_ACCEPTED_FORMATS = {"JPEG", "PNG", "GIF", "BMP"}
|
| 68 |
+
|
| 69 |
+
# Metadata character limits
|
| 70 |
+
YT_TITLE_MAX_CHARS = 100
|
| 71 |
+
YT_DESCRIPTION_MAX_CHARS = 5000
|
| 72 |
+
YT_TAGS_MAX_CHARS = 500
|
| 73 |
+
YT_BANNED_CHARS = {'<', '>'}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ============================================================================
|
| 77 |
+
# Utility functions
|
| 78 |
+
# ============================================================================
|
| 79 |
+
|
| 80 |
+
def extract_main_word(title):
|
| 81 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 82 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 83 |
+
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)
|
| 84 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 85 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 86 |
+
def is_valid(word):
|
| 87 |
+
if not word:
|
| 88 |
+
return False
|
| 89 |
+
return word.strip().lower() not in blacklisted
|
| 90 |
+
|
| 91 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 92 |
+
for q in quotes_ja:
|
| 93 |
+
if is_valid(q):
|
| 94 |
+
return q
|
| 95 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 96 |
+
for q in quotes_en:
|
| 97 |
+
if len(q) < 25 and is_valid(q):
|
| 98 |
+
return q
|
| 99 |
+
|
| 100 |
+
known_keywords = [
|
| 101 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 102 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 103 |
+
]
|
| 104 |
+
for kw in known_keywords:
|
| 105 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 106 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 107 |
+
if m:
|
| 108 |
+
return m.group(0)
|
| 109 |
+
if is_ja:
|
| 110 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 111 |
+
for k in katakana:
|
| 112 |
+
if is_valid(k):
|
| 113 |
+
return k
|
| 114 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 115 |
+
for k in kanji:
|
| 116 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 117 |
+
return k
|
| 118 |
+
if kanji:
|
| 119 |
+
for k in kanji:
|
| 120 |
+
if is_valid(k):
|
| 121 |
+
return k
|
| 122 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 123 |
+
for a in alpha:
|
| 124 |
+
if is_valid(a):
|
| 125 |
+
return a
|
| 126 |
+
else:
|
| 127 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 128 |
+
if words:
|
| 129 |
+
for w in words:
|
| 130 |
+
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):
|
| 131 |
+
return w
|
| 132 |
+
for w in words:
|
| 133 |
+
if is_valid(w):
|
| 134 |
+
return w
|
| 135 |
+
first_token = re.search(r'\w+', cleaned)
|
| 136 |
+
if first_token and is_valid(first_token.group(0)):
|
| 137 |
+
return first_token.group(0)
|
| 138 |
+
return ""
|
| 139 |
+
|
| 140 |
+
def safe_filename(name, max_len=40):
|
| 141 |
+
main_word = extract_main_word(name).strip()
|
| 142 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 143 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'`\(\)\[\]]', ' ', cleaned)
|
| 144 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 145 |
+
if main_word:
|
| 146 |
+
if cleaned.lower().startswith(main_word.lower()):
|
| 147 |
+
final_title = cleaned
|
| 148 |
+
else:
|
| 149 |
+
final_title = f"{main_word} {cleaned}"
|
| 150 |
+
else:
|
| 151 |
+
final_title = cleaned
|
| 152 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 153 |
+
if len(final_title) > max_len:
|
| 154 |
+
final_title = final_title[:max_len].strip()
|
| 155 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 156 |
+
return final_title
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _parse_frame_rate(r_frame_rate_str):
|
| 160 |
+
"""Parse ffprobe r_frame_rate string (e.g. '30/1', '30000/1001') into a float."""
|
| 161 |
+
if not r_frame_rate_str:
|
| 162 |
+
return None
|
| 163 |
+
try:
|
| 164 |
+
if '/' in r_frame_rate_str:
|
| 165 |
+
num, den = r_frame_rate_str.split('/')
|
| 166 |
+
den = int(den)
|
| 167 |
+
if den == 0:
|
| 168 |
+
return None
|
| 169 |
+
return float(int(num)) / den
|
| 170 |
+
return float(r_frame_rate_str)
|
| 171 |
+
except (ValueError, ZeroDivisionError):
|
| 172 |
+
return None
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _get_recommended_bitrate(height, fps):
|
| 176 |
+
"""Get YouTube recommended minimum bitrate (kbps) for given resolution and frame rate."""
|
| 177 |
+
# Find the closest matching resolution tier
|
| 178 |
+
tiers = sorted(YT_RECOMMENDED_BITRATES_KBPS.keys())
|
| 179 |
+
matched_tier = tiers[0]
|
| 180 |
+
for tier in tiers:
|
| 181 |
+
if height >= tier:
|
| 182 |
+
matched_tier = tier
|
| 183 |
+
base_bitrate = YT_RECOMMENDED_BITRATES_KBPS[matched_tier]
|
| 184 |
+
# High frame rate (>30fps) recommended bitrates are ~1.5x
|
| 185 |
+
if fps and fps > 30:
|
| 186 |
+
return int(base_bitrate * 1.5)
|
| 187 |
+
return base_bitrate
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ============================================================================
|
| 191 |
+
# Validation functions — based on YouTube Data API v3 official specs
|
| 192 |
+
# ============================================================================
|
| 193 |
+
|
| 194 |
+
def validate_video(video_path):
|
| 195 |
+
"""
|
| 196 |
+
Validate a video file against YouTube's official upload requirements.
|
| 197 |
+
|
| 198 |
+
Returns: (passed: bool, reason: str, details: dict, warnings: list[str])
|
| 199 |
+
|
| 200 |
+
Checks based on YouTube Data API v3 and encoding recommendations:
|
| 201 |
+
- File existence and minimum size
|
| 202 |
+
- File size <= 256 GB (YouTube maximum)
|
| 203 |
+
- Container readability (ffprobe)
|
| 204 |
+
- Video stream present (required)
|
| 205 |
+
- Audio stream present (required — YouTube rejects video-only uploads)
|
| 206 |
+
- Duration > 0 and <= 12 hours
|
| 207 |
+
- Video codec in accepted list (H.264 preferred)
|
| 208 |
+
- Audio codec in accepted list (AAC-LC preferred)
|
| 209 |
+
- Frame rate is standard (24/25/30/48/50/60 fps)
|
| 210 |
+
- Progressive scan (not interlaced)
|
| 211 |
+
- Bitrate vs YouTube recommended minimums
|
| 212 |
+
"""
|
| 213 |
+
path = Path(video_path)
|
| 214 |
+
details = {}
|
| 215 |
+
warnings = []
|
| 216 |
+
|
| 217 |
+
# --- File existence ---
|
| 218 |
+
if not path.exists():
|
| 219 |
+
return False, "File does not exist", details, warnings
|
| 220 |
+
|
| 221 |
+
# --- File size checks ---
|
| 222 |
+
try:
|
| 223 |
+
file_size = path.stat().st_size
|
| 224 |
+
details["file_size_bytes"] = file_size
|
| 225 |
+
details["file_size_mb"] = round(file_size / (1024 * 1024), 2)
|
| 226 |
+
except Exception as e:
|
| 227 |
+
return False, f"Failed to get file stats: {e}", details, warnings
|
| 228 |
+
|
| 229 |
+
if file_size < YT_MIN_FILE_SIZE_BYTES:
|
| 230 |
+
return False, f"File size too small ({file_size} bytes). Likely a failed render.", details, warnings
|
| 231 |
+
|
| 232 |
+
if file_size > YT_MAX_FILE_SIZE_BYTES:
|
| 233 |
+
return False, f"File size ({details['file_size_mb']} MB) exceeds YouTube maximum of 256 GB", details, warnings
|
| 234 |
+
|
| 235 |
+
# --- ffprobe deep inspection ---
|
| 236 |
+
ffprobe = os.environ.get("VIDEO_AGENT_FFPROBE", "ffprobe")
|
| 237 |
+
cmd = [
|
| 238 |
+
ffprobe, "-v", "error",
|
| 239 |
+
"-show_entries",
|
| 240 |
+
"format=duration,size,bit_rate"
|
| 241 |
+
":stream=codec_type,codec_name,width,height,r_frame_rate,field_order,sample_rate,channels,bit_rate",
|
| 242 |
+
"-of", "json",
|
| 243 |
+
str(path)
|
| 244 |
+
]
|
| 245 |
+
try:
|
| 246 |
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 247 |
+
if res.returncode != 0:
|
| 248 |
+
return False, f"ffprobe validation failed: {res.stderr.strip()}", details, warnings
|
| 249 |
+
data = json.loads(res.stdout)
|
| 250 |
+
except subprocess.TimeoutExpired:
|
| 251 |
+
return False, "ffprobe validation timed out (30s)", details, warnings
|
| 252 |
+
except json.JSONDecodeError as e:
|
| 253 |
+
return False, f"ffprobe returned invalid JSON: {e}", details, warnings
|
| 254 |
+
except Exception as e:
|
| 255 |
+
return False, f"Failed to run ffprobe: {e}", details, warnings
|
| 256 |
+
|
| 257 |
+
fmt = data.get("format", {})
|
| 258 |
+
streams = data.get("streams", [])
|
| 259 |
+
|
| 260 |
+
# --- Duration check (YouTube max: 12 hours) ---
|
| 261 |
+
duration_str = fmt.get("duration")
|
| 262 |
+
if not duration_str:
|
| 263 |
+
return False, "No duration found in container metadata", details, warnings
|
| 264 |
+
try:
|
| 265 |
+
duration = float(duration_str)
|
| 266 |
+
except ValueError:
|
| 267 |
+
return False, f"Invalid duration value: {duration_str}", details, warnings
|
| 268 |
+
|
| 269 |
+
details["duration_s"] = round(duration, 2)
|
| 270 |
+
|
| 271 |
+
if duration <= 0:
|
| 272 |
+
return False, f"Invalid video duration: {duration}s", details, warnings
|
| 273 |
+
if duration > YT_MAX_DURATION_SECONDS:
|
| 274 |
+
return False, f"Duration ({duration/3600:.1f}h) exceeds YouTube maximum of 12 hours", details, warnings
|
| 275 |
+
|
| 276 |
+
# --- Video stream check (required) ---
|
| 277 |
+
video_streams = [s for s in streams if s.get("codec_type") == "video"]
|
| 278 |
+
if not video_streams:
|
| 279 |
+
return False, "No video stream found — YouTube requires a video stream", details, warnings
|
| 280 |
+
|
| 281 |
+
vs = video_streams[0] # Primary video stream
|
| 282 |
+
|
| 283 |
+
# Video codec
|
| 284 |
+
video_codec = vs.get("codec_name", "unknown")
|
| 285 |
+
details["video_codec"] = video_codec
|
| 286 |
+
if video_codec not in YT_ACCEPTED_VIDEO_CODECS:
|
| 287 |
+
warnings.append(f"Video codec '{video_codec}' may not be accepted by YouTube (preferred: {YT_PREFERRED_VIDEO_CODEC})")
|
| 288 |
+
elif video_codec != YT_PREFERRED_VIDEO_CODEC:
|
| 289 |
+
warnings.append(f"Video codec '{video_codec}' is accepted but '{YT_PREFERRED_VIDEO_CODEC}' is preferred by YouTube")
|
| 290 |
+
|
| 291 |
+
# Resolution
|
| 292 |
+
width = vs.get("width")
|
| 293 |
+
height = vs.get("height")
|
| 294 |
+
if width and height:
|
| 295 |
+
details["resolution"] = f"{width}x{height}"
|
| 296 |
+
if height < 240:
|
| 297 |
+
warnings.append(f"Resolution {width}x{height} is very low — minimum practical is 240p")
|
| 298 |
+
|
| 299 |
+
# Frame rate
|
| 300 |
+
r_frame_rate = vs.get("r_frame_rate")
|
| 301 |
+
fps = _parse_frame_rate(r_frame_rate)
|
| 302 |
+
if fps:
|
| 303 |
+
details["fps"] = round(fps, 2)
|
| 304 |
+
# Check if close to a standard frame rate
|
| 305 |
+
closest_std = min(YT_STANDARD_FRAME_RATES, key=lambda x: abs(x - fps))
|
| 306 |
+
if abs(fps - closest_std) > 1.0:
|
| 307 |
+
warnings.append(f"Frame rate {fps:.2f} fps is non-standard (YouTube standard: {sorted(YT_STANDARD_FRAME_RATES)})")
|
| 308 |
+
|
| 309 |
+
# Progressive scan check (interlaced is not recommended)
|
| 310 |
+
field_order = vs.get("field_order", "")
|
| 311 |
+
if field_order and field_order not in ("progressive", "unknown", ""):
|
| 312 |
+
warnings.append(f"Video appears interlaced (field_order='{field_order}'). YouTube recommends progressive scan.")
|
| 313 |
+
details["scan_type"] = field_order if field_order else "progressive"
|
| 314 |
+
|
| 315 |
+
# --- Audio stream check (REQUIRED — YouTube rejects video-only uploads) ---
|
| 316 |
+
audio_streams = [s for s in streams if s.get("codec_type") == "audio"]
|
| 317 |
+
if not audio_streams:
|
| 318 |
+
return False, "No audio stream found — YouTube requires both video AND audio streams", details, warnings
|
| 319 |
+
|
| 320 |
+
aus = audio_streams[0] # Primary audio stream
|
| 321 |
+
|
| 322 |
+
# Audio codec
|
| 323 |
+
audio_codec = aus.get("codec_name", "unknown")
|
| 324 |
+
details["audio_codec"] = audio_codec
|
| 325 |
+
if audio_codec not in YT_ACCEPTED_AUDIO_CODECS:
|
| 326 |
+
warnings.append(f"Audio codec '{audio_codec}' may not be accepted by YouTube (preferred: {YT_PREFERRED_AUDIO_CODEC})")
|
| 327 |
+
elif audio_codec != YT_PREFERRED_AUDIO_CODEC:
|
| 328 |
+
warnings.append(f"Audio codec '{audio_codec}' is accepted but '{YT_PREFERRED_AUDIO_CODEC}' is preferred")
|
| 329 |
+
|
| 330 |
+
# Audio sample rate (YouTube recommends 48kHz)
|
| 331 |
+
sample_rate = aus.get("sample_rate")
|
| 332 |
+
if sample_rate:
|
| 333 |
+
details["audio_sample_rate"] = int(sample_rate)
|
| 334 |
+
if int(sample_rate) < 44100:
|
| 335 |
+
warnings.append(f"Audio sample rate {sample_rate}Hz is low (YouTube recommends 48000Hz)")
|
| 336 |
+
|
| 337 |
+
# Audio channels
|
| 338 |
+
channels = aus.get("channels")
|
| 339 |
+
if channels:
|
| 340 |
+
details["audio_channels"] = channels
|
| 341 |
+
|
| 342 |
+
# --- Overall bitrate check ---
|
| 343 |
+
bitrate_str = fmt.get("bit_rate")
|
| 344 |
+
if bitrate_str:
|
| 345 |
+
try:
|
| 346 |
+
bitrate_kbps = int(bitrate_str) // 1000
|
| 347 |
+
details["bitrate_kbps"] = bitrate_kbps
|
| 348 |
+
if height:
|
| 349 |
+
recommended = _get_recommended_bitrate(height, fps)
|
| 350 |
+
details["yt_recommended_bitrate_kbps"] = recommended
|
| 351 |
+
if bitrate_kbps < recommended * 0.5:
|
| 352 |
+
warnings.append(
|
| 353 |
+
f"Bitrate {bitrate_kbps} kbps is well below YouTube's recommended "
|
| 354 |
+
f"{recommended} kbps for {height}p — may result in poor quality"
|
| 355 |
+
)
|
| 356 |
+
except (ValueError, TypeError):
|
| 357 |
+
pass
|
| 358 |
+
|
| 359 |
+
# --- Aspect ratio info ---
|
| 360 |
+
if width and height:
|
| 361 |
+
gcd_val = Fraction(width, height)
|
| 362 |
+
details["aspect_ratio"] = f"{gcd_val.numerator}:{gcd_val.denominator}"
|
| 363 |
+
# Not a FAIL, just informational warning if not 16:9
|
| 364 |
+
if not (abs(width / height - 16/9) < 0.05):
|
| 365 |
+
warnings.append(f"Aspect ratio {gcd_val.numerator}:{gcd_val.denominator} is not 16:9 — YouTube may add letterboxing/pillarboxing")
|
| 366 |
+
|
| 367 |
+
return True, "Pass", details, warnings
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def validate_thumbnail(thumb_path):
|
| 371 |
+
"""
|
| 372 |
+
Validate a thumbnail image against YouTube's official thumbnail requirements.
|
| 373 |
+
|
| 374 |
+
Returns: (passed: bool, reason: str, details: dict, warnings: list[str])
|
| 375 |
+
|
| 376 |
+
YouTube thumbnail specs (from API docs and support.google.com/youtube/answer/72431):
|
| 377 |
+
- Dimensions: 1280x720 (recommended), minimum width 640px
|
| 378 |
+
- File size: <= 2 MB
|
| 379 |
+
- Formats: JPG, PNG, GIF (non-animated), BMP
|
| 380 |
+
- Aspect ratio: 16:9
|
| 381 |
+
"""
|
| 382 |
+
path = Path(thumb_path)
|
| 383 |
+
details = {}
|
| 384 |
+
warnings = []
|
| 385 |
+
|
| 386 |
+
if not path.exists():
|
| 387 |
+
return False, "Thumbnail file not found", details, warnings
|
| 388 |
+
|
| 389 |
+
# --- File size check (YouTube max: 2 MB) ---
|
| 390 |
+
try:
|
| 391 |
+
file_size = path.stat().st_size
|
| 392 |
+
details["file_size_bytes"] = file_size
|
| 393 |
+
details["file_size_kb"] = round(file_size / 1024, 1)
|
| 394 |
+
except Exception as e:
|
| 395 |
+
return False, f"Failed to get thumbnail file stats: {e}", details, warnings
|
| 396 |
+
|
| 397 |
+
if file_size > YT_THUMB_MAX_SIZE_BYTES:
|
| 398 |
+
return False, f"Thumbnail file size ({details['file_size_kb']} KB) exceeds YouTube maximum of 2 MB", details, warnings
|
| 399 |
+
|
| 400 |
+
# --- Image validation ---
|
| 401 |
+
try:
|
| 402 |
+
with Image.open(path) as img:
|
| 403 |
+
width, height = img.size
|
| 404 |
+
img_format = img.format # e.g. "JPEG", "PNG", "GIF", "BMP"
|
| 405 |
+
details["width"] = width
|
| 406 |
+
details["height"] = height
|
| 407 |
+
details["format"] = img_format
|
| 408 |
+
|
| 409 |
+
# Format check
|
| 410 |
+
if img_format not in YT_THUMB_ACCEPTED_FORMATS:
|
| 411 |
+
return False, f"Thumbnail format '{img_format}' is not accepted by YouTube (accepted: {', '.join(YT_THUMB_ACCEPTED_FORMATS)})", details, warnings
|
| 412 |
+
|
| 413 |
+
# Minimum width check (YouTube requires >= 640px)
|
| 414 |
+
if width < YT_THUMB_MIN_WIDTH:
|
| 415 |
+
return False, f"Thumbnail width {width}px is below YouTube minimum of {YT_THUMB_MIN_WIDTH}px", details, warnings
|
| 416 |
+
|
| 417 |
+
# Recommended dimensions check
|
| 418 |
+
if width != YT_THUMB_RECOMMENDED_WIDTH or height != YT_THUMB_RECOMMENDED_HEIGHT:
|
| 419 |
+
warnings.append(f"Thumbnail is {width}x{height} — YouTube recommends {YT_THUMB_RECOMMENDED_WIDTH}x{YT_THUMB_RECOMMENDED_HEIGHT}")
|
| 420 |
+
|
| 421 |
+
# Aspect ratio check (16:9)
|
| 422 |
+
if width > 0 and height > 0:
|
| 423 |
+
ratio = width / height
|
| 424 |
+
if abs(ratio - 16/9) > 0.05:
|
| 425 |
+
aspect = Fraction(width, height)
|
| 426 |
+
warnings.append(f"Thumbnail aspect ratio {aspect.numerator}:{aspect.denominator} is not 16:9 — YouTube may add black bars")
|
| 427 |
+
|
| 428 |
+
# Verify image integrity
|
| 429 |
+
img.verify()
|
| 430 |
+
|
| 431 |
+
except Exception as e:
|
| 432 |
+
return False, f"Thumbnail is corrupted or unreadable: {e}", details, warnings
|
| 433 |
+
|
| 434 |
+
reason_parts = [f"{width}x{height}"]
|
| 435 |
+
reason_parts.append(f"{details['file_size_kb']}KB")
|
| 436 |
+
reason_parts.append(img_format)
|
| 437 |
+
return True, f"Pass ({', '.join(reason_parts)})", details, warnings
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def validate_metadata(metadata_path):
|
| 441 |
+
"""
|
| 442 |
+
Validate YouTube metadata file against YouTube Data API v3 requirements.
|
| 443 |
+
|
| 444 |
+
Returns: (passed: bool, reason: str, details: dict, warnings: list[str])
|
| 445 |
+
|
| 446 |
+
YouTube API metadata constraints (from developers.google.com/youtube/v3):
|
| 447 |
+
- Title: 1-100 characters, no < or > characters
|
| 448 |
+
- Description: <= 5000 characters, no < or > characters
|
| 449 |
+
- Tags: total <= 500 characters
|
| 450 |
+
- Source attribution must be present
|
| 451 |
+
"""
|
| 452 |
+
path = Path(metadata_path)
|
| 453 |
+
details = {}
|
| 454 |
+
warnings = []
|
| 455 |
+
|
| 456 |
+
if not path.exists():
|
| 457 |
+
return False, "youtube_metadata.txt file not found", details, warnings
|
| 458 |
+
|
| 459 |
+
try:
|
| 460 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 461 |
+
content = f.read()
|
| 462 |
+
except Exception as e:
|
| 463 |
+
return False, f"Failed to read metadata file: {e}", details, warnings
|
| 464 |
+
|
| 465 |
+
failures = []
|
| 466 |
+
|
| 467 |
+
# --- TITLE validation ---
|
| 468 |
+
if "SUGGESTED TITLE:" not in content:
|
| 469 |
+
failures.append("Missing SUGGESTED TITLE section")
|
| 470 |
+
else:
|
| 471 |
+
title_match = re.search(r"SUGGESTED TITLE:\s*(.+)", content)
|
| 472 |
+
if not title_match or not title_match.group(1).strip():
|
| 473 |
+
failures.append("Suggested title is empty")
|
| 474 |
+
else:
|
| 475 |
+
title = title_match.group(1).strip()
|
| 476 |
+
details["title"] = title
|
| 477 |
+
details["title_length"] = len(title)
|
| 478 |
+
|
| 479 |
+
# YouTube API: Title max 100 characters
|
| 480 |
+
if len(title) > YT_TITLE_MAX_CHARS:
|
| 481 |
+
failures.append(f"Title is {len(title)} characters — YouTube maximum is {YT_TITLE_MAX_CHARS}")
|
| 482 |
+
|
| 483 |
+
# YouTube API: < and > are banned in titles
|
| 484 |
+
banned_in_title = [c for c in title if c in YT_BANNED_CHARS]
|
| 485 |
+
if banned_in_title:
|
| 486 |
+
failures.append(f"Title contains banned characters: {banned_in_title} — YouTube rejects < and > in titles")
|
| 487 |
+
|
| 488 |
+
# --- DESCRIPTION validation ---
|
| 489 |
+
if "=== DESCRIPTION ===" not in content:
|
| 490 |
+
failures.append("Missing DESCRIPTION section")
|
| 491 |
+
else:
|
| 492 |
+
desc_parts = content.split("=== DESCRIPTION ===")
|
| 493 |
+
if len(desc_parts) < 2 or not desc_parts[1].strip():
|
| 494 |
+
failures.append("Description section is empty")
|
| 495 |
+
else:
|
| 496 |
+
# Extract description text (up to the next section marker or end of file)
|
| 497 |
+
desc_text = desc_parts[1]
|
| 498 |
+
# The description that gets uploaded is everything between === DESCRIPTION === and --- Video Transcript ---
|
| 499 |
+
transcript_marker = "--- Video Transcript ---"
|
| 500 |
+
if transcript_marker in desc_text:
|
| 501 |
+
desc_text = desc_text.split(transcript_marker)[0]
|
| 502 |
+
desc_text = desc_text.strip()
|
| 503 |
+
|
| 504 |
+
details["description_length"] = len(desc_text)
|
| 505 |
+
|
| 506 |
+
# YouTube API: Description max 5000 characters
|
| 507 |
+
if len(desc_text) > YT_DESCRIPTION_MAX_CHARS:
|
| 508 |
+
failures.append(f"Description is {len(desc_text)} characters — YouTube maximum is {YT_DESCRIPTION_MAX_CHARS}")
|
| 509 |
+
|
| 510 |
+
# YouTube API: < and > are banned in descriptions
|
| 511 |
+
banned_in_desc = [c for c in desc_text if c in YT_BANNED_CHARS]
|
| 512 |
+
if banned_in_desc:
|
| 513 |
+
failures.append(f"Description contains {len(banned_in_desc)} banned character(s) (< or >) — YouTube rejects these")
|
| 514 |
+
|
| 515 |
+
# --- SOURCE attribution check ---
|
| 516 |
+
if "Source:" not in content:
|
| 517 |
+
failures.append("Missing Source (attribution) information in description")
|
| 518 |
+
else:
|
| 519 |
+
details["has_source"] = True
|
| 520 |
+
|
| 521 |
+
# --- TAGS validation (if tags section exists) ---
|
| 522 |
+
hashtag_matches = re.findall(r'#\w+', content)
|
| 523 |
+
if hashtag_matches:
|
| 524 |
+
total_tag_chars = sum(len(tag) - 1 for tag in hashtag_matches) # Subtract # prefix
|
| 525 |
+
details["tags_count"] = len(hashtag_matches)
|
| 526 |
+
details["tags_total_chars"] = total_tag_chars
|
| 527 |
+
if total_tag_chars > YT_TAGS_MAX_CHARS:
|
| 528 |
+
warnings.append(f"Tags total {total_tag_chars} characters — YouTube maximum is {YT_TAGS_MAX_CHARS}")
|
| 529 |
+
|
| 530 |
+
if failures:
|
| 531 |
+
return False, "; ".join(failures), details, warnings
|
| 532 |
+
|
| 533 |
+
reason_parts = []
|
| 534 |
+
if "title_length" in details:
|
| 535 |
+
reason_parts.append(f"Title: {details['title_length']} chars")
|
| 536 |
+
if "description_length" in details:
|
| 537 |
+
reason_parts.append(f"Desc: {details['description_length']} chars")
|
| 538 |
+
reason_parts.append("Source: present")
|
| 539 |
+
|
| 540 |
+
return True, f"Pass ({', '.join(reason_parts)})", details, warnings
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
# ============================================================================
|
| 544 |
+
# Main evaluation function
|
| 545 |
+
# ============================================================================
|
| 546 |
+
|
| 547 |
+
def evaluate_youtube_ready(article_dir, force=False, dry_run=False):
|
| 548 |
+
"""
|
| 549 |
+
Evaluate whether an article's video assets are ready for YouTube upload.
|
| 550 |
+
|
| 551 |
+
Checks video, thumbnail, metadata, and package integrity against
|
| 552 |
+
YouTube Data API v3 official requirements.
|
| 553 |
+
"""
|
| 554 |
+
if not os.path.exists(article_dir):
|
| 555 |
+
logger.warning(f"Directory {article_dir} does not exist.")
|
| 556 |
+
return "REJECTED"
|
| 557 |
+
|
| 558 |
+
result_path = os.path.join(article_dir, "evaluation_result.json")
|
| 559 |
+
if not os.path.exists(result_path):
|
| 560 |
+
logger.info(f"Skipping {os.path.basename(article_dir)}: No evaluation_result.json found.")
|
| 561 |
+
return None
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
with open(result_path, 'r', encoding='utf-8') as f:
|
| 565 |
+
results = json.load(f)
|
| 566 |
+
except Exception as e:
|
| 567 |
+
logger.error(f"Failed to read evaluation result from {result_path}: {e}")
|
| 568 |
+
return None
|
| 569 |
+
|
| 570 |
+
current_status = results.get("status", "")
|
| 571 |
+
if not force and current_status == "YOUTUBE_READY":
|
| 572 |
+
logger.info(f"Skipping {os.path.basename(article_dir)}: Already YOUTUBE_READY.")
|
| 573 |
+
return "YOUTUBE_READY"
|
| 574 |
+
|
| 575 |
+
if current_status not in ["READY_FOR_NEWSVIDEO", "READY_FOR_VIDEO", "YOUTUBE_READY", "YOUTUBE_GATE_FAILED"]:
|
| 576 |
+
logger.info(f"Skipping {os.path.basename(article_dir)}: Status is '{current_status}', not ready for YouTube gate.")
|
| 577 |
+
return None
|
| 578 |
+
|
| 579 |
+
logger.info(f"Evaluating YouTube Gate for: {os.path.basename(article_dir)}")
|
| 580 |
+
|
| 581 |
+
# Initialize/reset YouTube gate checks with enhanced structure
|
| 582 |
+
results["checks"]["youtube_gate"] = {
|
| 583 |
+
"timestamp": datetime.now().isoformat(),
|
| 584 |
+
"status": "PENDING",
|
| 585 |
+
"video": {"status": "PENDING", "reason": "", "details": {}},
|
| 586 |
+
"thumbnail": {"status": "PENDING", "reason": "", "details": {}},
|
| 587 |
+
"metadata": {"status": "PENDING", "reason": "", "details": {}},
|
| 588 |
+
"package": {"status": "PENDING", "reason": ""},
|
| 589 |
+
"warnings": []
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
if "reject_reasons" not in results:
|
| 593 |
+
results["reject_reasons"] = []
|
| 594 |
+
|
| 595 |
+
# Clean old YouTube gate reject reasons
|
| 596 |
+
results["reject_reasons"] = [r for r in results["reject_reasons"] if not r.startswith("[YOUTUBE_GATE]")]
|
| 597 |
+
|
| 598 |
+
safe_name = safe_filename(os.path.basename(article_dir))
|
| 599 |
+
all_warnings = []
|
| 600 |
+
|
| 601 |
+
# ===== 1. VIDEO CHECK =====
|
| 602 |
+
sizes = ["short", "middle", "long"]
|
| 603 |
+
video_failures = []
|
| 604 |
+
video_details_all = {}
|
| 605 |
+
|
| 606 |
+
for size in sizes:
|
| 607 |
+
video_file = f"{safe_name}_{size}.mp4"
|
| 608 |
+
video_path = os.path.join(article_dir, video_file)
|
| 609 |
+
ok, reason, details, warns = validate_video(video_path)
|
| 610 |
+
video_details_all[size] = details
|
| 611 |
+
if not ok:
|
| 612 |
+
video_failures.append(f"{size}: {reason}")
|
| 613 |
+
for w in warns:
|
| 614 |
+
all_warnings.append(f"{size} video: {w}")
|
| 615 |
+
|
| 616 |
+
if video_failures:
|
| 617 |
+
results["checks"]["youtube_gate"]["video"] = {
|
| 618 |
+
"status": "FAIL",
|
| 619 |
+
"reason": "; ".join(video_failures),
|
| 620 |
+
"details": video_details_all
|
| 621 |
+
}
|
| 622 |
+
else:
|
| 623 |
+
results["checks"]["youtube_gate"]["video"] = {
|
| 624 |
+
"status": "PASS",
|
| 625 |
+
"reason": "All sizes (short, middle, long) videos pass YouTube requirements",
|
| 626 |
+
"details": video_details_all
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
# ===== 2. PACKAGE CHECK (video + thumbnail in package) =====
|
| 630 |
+
package_failures = []
|
| 631 |
+
|
| 632 |
+
for size in sizes:
|
| 633 |
+
pkg_dir = os.path.join(YOUTUBE_DIR, f"{safe_name}_{size}")
|
| 634 |
+
if not os.path.exists(pkg_dir):
|
| 635 |
+
package_failures.append(f"Package directory for {size} missing")
|
| 636 |
+
continue
|
| 637 |
+
|
| 638 |
+
# Check video in package
|
| 639 |
+
pkg_video = os.path.join(pkg_dir, f"{safe_name}_{size}.mp4")
|
| 640 |
+
ok, reason, _, _ = validate_video(pkg_video)
|
| 641 |
+
if not ok:
|
| 642 |
+
package_failures.append(f"{size} package video: {reason}")
|
| 643 |
+
|
| 644 |
+
# Check thumbnail in package (with YouTube specs)
|
| 645 |
+
pkg_thumb = os.path.join(pkg_dir, "thumbnail.png")
|
| 646 |
+
ok, reason, thumb_details, thumb_warns = validate_thumbnail(pkg_thumb)
|
| 647 |
+
if not ok:
|
| 648 |
+
package_failures.append(f"{size} package thumbnail: {reason}")
|
| 649 |
+
for w in thumb_warns:
|
| 650 |
+
all_warnings.append(f"{size} package thumbnail: {w}")
|
| 651 |
+
|
| 652 |
+
# Store thumbnail details from one package for reporting
|
| 653 |
+
if thumb_details and "details" not in results["checks"]["youtube_gate"]["thumbnail"]:
|
| 654 |
+
results["checks"]["youtube_gate"]["thumbnail"]["details"] = thumb_details
|
| 655 |
+
|
| 656 |
+
if package_failures:
|
| 657 |
+
results["checks"]["youtube_gate"]["package"] = {
|
| 658 |
+
"status": "FAIL",
|
| 659 |
+
"reason": "; ".join(package_failures)
|
| 660 |
+
}
|
| 661 |
+
else:
|
| 662 |
+
results["checks"]["youtube_gate"]["package"] = {
|
| 663 |
+
"status": "PASS",
|
| 664 |
+
"reason": "All packages have valid video and thumbnail meeting YouTube specs"
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
# ===== 3. THUMBNAIL CHECK (dedicated — from package) =====
|
| 668 |
+
# Use the first available package's thumbnail for the primary check
|
| 669 |
+
thumb_checked = False
|
| 670 |
+
for size in sizes:
|
| 671 |
+
pkg_dir = os.path.join(YOUTUBE_DIR, f"{safe_name}_{size}")
|
| 672 |
+
pkg_thumb = os.path.join(pkg_dir, "thumbnail.png")
|
| 673 |
+
if os.path.exists(pkg_thumb):
|
| 674 |
+
ok, reason, thumb_details, thumb_warns = validate_thumbnail(pkg_thumb)
|
| 675 |
+
results["checks"]["youtube_gate"]["thumbnail"] = {
|
| 676 |
+
"status": "PASS" if ok else "FAIL",
|
| 677 |
+
"reason": reason,
|
| 678 |
+
"details": thumb_details
|
| 679 |
+
}
|
| 680 |
+
for w in thumb_warns:
|
| 681 |
+
all_warnings.append(f"thumbnail: {w}")
|
| 682 |
+
thumb_checked = True
|
| 683 |
+
break
|
| 684 |
+
|
| 685 |
+
if not thumb_checked:
|
| 686 |
+
results["checks"]["youtube_gate"]["thumbnail"] = {
|
| 687 |
+
"status": "FAIL",
|
| 688 |
+
"reason": "No thumbnail found in any package directory",
|
| 689 |
+
"details": {}
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
# ===== 4. METADATA CHECK =====
|
| 693 |
+
metadata_failures = []
|
| 694 |
+
metadata_details_all = {}
|
| 695 |
+
|
| 696 |
+
for size in sizes:
|
| 697 |
+
pkg_dir = os.path.join(YOUTUBE_DIR, f"{safe_name}_{size}")
|
| 698 |
+
pkg_meta = os.path.join(pkg_dir, "youtube_metadata.txt")
|
| 699 |
+
ok, reason, meta_details, meta_warns = validate_metadata(pkg_meta)
|
| 700 |
+
metadata_details_all[size] = meta_details
|
| 701 |
+
if not ok:
|
| 702 |
+
metadata_failures.append(f"{size}: {reason}")
|
| 703 |
+
for w in meta_warns:
|
| 704 |
+
all_warnings.append(f"{size} metadata: {w}")
|
| 705 |
+
|
| 706 |
+
if metadata_failures:
|
| 707 |
+
results["checks"]["youtube_gate"]["metadata"] = {
|
| 708 |
+
"status": "FAIL",
|
| 709 |
+
"reason": "; ".join(metadata_failures),
|
| 710 |
+
"details": metadata_details_all
|
| 711 |
+
}
|
| 712 |
+
else:
|
| 713 |
+
results["checks"]["youtube_gate"]["metadata"] = {
|
| 714 |
+
"status": "PASS",
|
| 715 |
+
"reason": "All metadata passes YouTube API requirements",
|
| 716 |
+
"details": metadata_details_all
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
+
# ===== Store all warnings =====
|
| 720 |
+
results["checks"]["youtube_gate"]["warnings"] = all_warnings
|
| 721 |
+
|
| 722 |
+
# ===== Determine overall gate status =====
|
| 723 |
+
gate_ok = True
|
| 724 |
+
gate_reasons = []
|
| 725 |
+
|
| 726 |
+
for subcheck in ["video", "thumbnail", "metadata", "package"]:
|
| 727 |
+
sub_status = results["checks"]["youtube_gate"][subcheck]["status"]
|
| 728 |
+
sub_reason = results["checks"]["youtube_gate"][subcheck]["reason"]
|
| 729 |
+
if sub_status == "FAIL":
|
| 730 |
+
gate_ok = False
|
| 731 |
+
gate_reasons.append(f"[YOUTUBE_GATE] {subcheck.upper()} FAIL: {sub_reason}")
|
| 732 |
+
|
| 733 |
+
if gate_ok:
|
| 734 |
+
results["checks"]["youtube_gate"]["status"] = "PASS"
|
| 735 |
+
results["status"] = "YOUTUBE_READY"
|
| 736 |
+
warn_summary = f" ({len(all_warnings)} warnings)" if all_warnings else ""
|
| 737 |
+
logger.info(f" -> Final Status: YOUTUBE_READY{warn_summary}")
|
| 738 |
+
else:
|
| 739 |
+
results["checks"]["youtube_gate"]["status"] = "FAIL"
|
| 740 |
+
results["status"] = "YOUTUBE_GATE_FAILED"
|
| 741 |
+
results["reject_reasons"].extend(gate_reasons)
|
| 742 |
+
logger.warning(f" -> Final Status: YOUTUBE_GATE_FAILED (Reasons: {gate_reasons})")
|
| 743 |
+
|
| 744 |
+
# Save results
|
| 745 |
+
if not dry_run:
|
| 746 |
+
try:
|
| 747 |
+
with open(result_path, 'w', encoding='utf-8') as f:
|
| 748 |
+
json.dump(results, f, indent=4, ensure_ascii=False)
|
| 749 |
+
except Exception as e:
|
| 750 |
+
logger.error(f"Failed to save evaluation result to {result_path}: {e}")
|
| 751 |
+
else:
|
| 752 |
+
logger.info(f"[DRY-RUN] Would save evaluation result to {result_path}")
|
| 753 |
+
|
| 754 |
+
return results["status"]
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
# ============================================================================
|
| 758 |
+
# CLI entry point
|
| 759 |
+
# ============================================================================
|
| 760 |
+
|
| 761 |
+
def main():
|
| 762 |
+
parser = argparse.ArgumentParser(
|
| 763 |
+
description="YouTube Ready Quality Gate — validates video assets against YouTube Data API v3 requirements."
|
| 764 |
+
)
|
| 765 |
+
parser.add_argument("--locale", type=str, default=None, help="Locale to evaluate (default: all)")
|
| 766 |
+
parser.add_argument("--category", type=str, default=None, help="Category to evaluate")
|
| 767 |
+
parser.add_argument("--dry-run", action="store_true", help="Evaluate only, do not save status")
|
| 768 |
+
parser.add_argument("--force", action="store_true", help="Force evaluation even if already YOUTUBE_READY")
|
| 769 |
+
parser.add_argument("--verbose", action="store_true", help="Show detailed validation info per article")
|
| 770 |
+
args = parser.parse_args()
|
| 771 |
+
|
| 772 |
+
locales = [args.locale] if args.locale else ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 773 |
+
|
| 774 |
+
article_dirs = []
|
| 775 |
+
for locale in locales:
|
| 776 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 777 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 778 |
+
continue
|
| 779 |
+
try:
|
| 780 |
+
categories = [args.category] if args.category else os.listdir(locale_path)
|
| 781 |
+
except OSError as e:
|
| 782 |
+
logger.error(f"Error listing categories in {locale_path}: {e}")
|
| 783 |
+
continue
|
| 784 |
+
|
| 785 |
+
for category in categories:
|
| 786 |
+
cat_path = os.path.join(locale_path, category)
|
| 787 |
+
if not os.path.isdir(cat_path) or category == "__pycache__":
|
| 788 |
+
continue
|
| 789 |
+
try:
|
| 790 |
+
articles = os.listdir(cat_path)
|
| 791 |
+
except OSError:
|
| 792 |
+
continue
|
| 793 |
+
for article in articles:
|
| 794 |
+
article_dir = os.path.join(cat_path, article)
|
| 795 |
+
if os.path.isdir(article_dir) and article not in ["images", "sources", "__pycache__"]:
|
| 796 |
+
article_dirs.append(article_dir)
|
| 797 |
+
|
| 798 |
+
if not article_dirs:
|
| 799 |
+
logger.info("No articles found to evaluate.")
|
| 800 |
+
return
|
| 801 |
+
|
| 802 |
+
logger.info(f"Found {len(article_dirs)} articles to scan for YouTube Quality Gate.")
|
| 803 |
+
logger.info("Validating against YouTube Data API v3 specifications:")
|
| 804 |
+
logger.info(f" Video: codec, audio stream, duration ≤{YT_MAX_DURATION_SECONDS}s, file size ≤256GB")
|
| 805 |
+
logger.info(f" Thumbnail: ≥{YT_THUMB_MIN_WIDTH}px width, ≤{YT_THUMB_MAX_SIZE_BYTES // (1024*1024)}MB, 16:9")
|
| 806 |
+
logger.info(f" Metadata: title ≤{YT_TITLE_MAX_CHARS} chars, description ≤{YT_DESCRIPTION_MAX_CHARS} chars, no <> chars")
|
| 807 |
+
|
| 808 |
+
stats = {"YOUTUBE_READY": 0, "YOUTUBE_GATE_FAILED": 0, "SKIPPED": 0, "WARNINGS": 0}
|
| 809 |
+
|
| 810 |
+
for art_dir in article_dirs:
|
| 811 |
+
res = evaluate_youtube_ready(art_dir, force=args.force, dry_run=args.dry_run)
|
| 812 |
+
if res == "YOUTUBE_READY":
|
| 813 |
+
stats["YOUTUBE_READY"] += 1
|
| 814 |
+
elif res == "YOUTUBE_GATE_FAILED":
|
| 815 |
+
stats["YOUTUBE_GATE_FAILED"] += 1
|
| 816 |
+
else:
|
| 817 |
+
stats["SKIPPED"] += 1
|
| 818 |
+
|
| 819 |
+
print("\n" + "="*60)
|
| 820 |
+
print("YouTube Quality Gate Scan Complete!")
|
| 821 |
+
print(f" Specs: YouTube Data API v3 + Encoding Recommendations")
|
| 822 |
+
print("-"*60)
|
| 823 |
+
print(f" Total articles scanned: {len(article_dirs)}")
|
| 824 |
+
print(f" YOUTUBE_READY: {stats['YOUTUBE_READY']}")
|
| 825 |
+
print(f" YOUTUBE_GATE_FAILED: {stats['YOUTUBE_GATE_FAILED']}")
|
| 826 |
+
print(f" SKIPPED: {stats['SKIPPED']}")
|
| 827 |
+
print("="*60)
|
| 828 |
+
|
| 829 |
+
if __name__ == "__main__":
|
| 830 |
+
main()
|
recover_missing_images.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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(encoding='utf-8')
|
| 10 |
+
|
| 11 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 12 |
+
|
| 13 |
+
# Dynamic path for importing WatermarkRemover
|
| 14 |
+
sys.path.insert(0, r"C:\Roaming\scripts")
|
| 15 |
+
try:
|
| 16 |
+
from news_collector.watermark_remover import WatermarkRemover
|
| 17 |
+
HAS_REMOVER = True
|
| 18 |
+
except ImportError:
|
| 19 |
+
HAS_REMOVER = False
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from curl_cffi import requests as requests_cffi
|
| 23 |
+
HAS_CURL_CFFI = True
|
| 24 |
+
except ImportError:
|
| 25 |
+
HAS_CURL_CFFI = False
|
| 26 |
+
|
| 27 |
+
def download_file(url, dest_path):
|
| 28 |
+
headers = {
|
| 29 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 30 |
+
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
|
| 31 |
+
"Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
|
| 32 |
+
"Referer": "https://news.google.com/"
|
| 33 |
+
}
|
| 34 |
+
try:
|
| 35 |
+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
|
| 36 |
+
if HAS_CURL_CFFI:
|
| 37 |
+
response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=30)
|
| 38 |
+
else:
|
| 39 |
+
response = requests.get(url, headers=headers, timeout=30)
|
| 40 |
+
response.raise_for_status()
|
| 41 |
+
with open(dest_path, 'wb') as f:
|
| 42 |
+
f.write(response.content)
|
| 43 |
+
return True
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f" Failed to download image {url}: {e}")
|
| 46 |
+
if os.path.exists(dest_path):
|
| 47 |
+
try:
|
| 48 |
+
os.remove(dest_path)
|
| 49 |
+
except:
|
| 50 |
+
pass
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
def is_valid_image(img_url, img_path):
|
| 54 |
+
# 1. URL Substring Check
|
| 55 |
+
url_lower = img_url.lower()
|
| 56 |
+
|
| 57 |
+
# Generic keywords indicating logos, default fallback pictures, ads, etc.
|
| 58 |
+
blacklist_keywords = [
|
| 59 |
+
"logo", "avatar", "favicon", "icon", "placeholder", "default", "fallback",
|
| 60 |
+
"dummy", "spacer", "pixel", "header", "footer", "ad-", "ads-",
|
| 61 |
+
"advertisement", "newsletter", "subscribe", "sign-up", "social-share",
|
| 62 |
+
"facebook-share", "twitter-share", "share-icon", "share-logo",
|
| 63 |
+
"app-store", "play-store", "transparent", "blank", "branding"
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
# Also block specific generic image names commonly used by news outlets
|
| 67 |
+
# e.g., Yahoo, Reuters, AP, Bloomberg, BBC, etc. logos or generic graphics
|
| 68 |
+
generic_patterns = [
|
| 69 |
+
"reuters-logo", "reuters_logo", "nytimes-logo", "nytimes_logo",
|
| 70 |
+
"ap-logo", "ap_logo", "bbc-logo", "bbc_logo", "cnn-logo", "cnn_logo",
|
| 71 |
+
"bloomberg-logo", "bloomberg_logo", "yahoo-logo", "yahoo_logo",
|
| 72 |
+
"wsj_logo", "wsj-logo", "guardian-logo", "guardian_logo"
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
for kw in blacklist_keywords:
|
| 76 |
+
if kw in url_lower:
|
| 77 |
+
print(f" Rejecting image URL (matches blacklist keyword '{kw}'): {img_url}")
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
for pat in generic_patterns:
|
| 81 |
+
if pat in url_lower:
|
| 82 |
+
print(f" Rejecting image URL (matches generic logo pattern '{pat}'): {img_url}")
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
# 2. Image Content Check (using Pillow)
|
| 86 |
+
if not os.path.exists(img_path):
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
from PIL import Image, ImageStat
|
| 91 |
+
with Image.open(img_path) as img:
|
| 92 |
+
width, height = img.size
|
| 93 |
+
|
| 94 |
+
# Aspect Ratio
|
| 95 |
+
aspect_ratio = width / height
|
| 96 |
+
|
| 97 |
+
# Minimum dimension requirements
|
| 98 |
+
min_width = 300
|
| 99 |
+
min_height = 200
|
| 100 |
+
|
| 101 |
+
if width < min_width or height < min_height:
|
| 102 |
+
print(f" Rejecting image (too small: {width}x{height}, required min {min_width}x{min_height})")
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
# Aspect Ratio Check (block extremely wide/tall banner or ad layout blocks)
|
| 106 |
+
if aspect_ratio < 0.5 or aspect_ratio > 3.0:
|
| 107 |
+
print(f" Rejecting image (extreme aspect ratio: {aspect_ratio:.2f})")
|
| 108 |
+
return False
|
| 109 |
+
|
| 110 |
+
# Perfect square check (width == height) for small images (usually logos/avatars)
|
| 111 |
+
if width == height and width < 450:
|
| 112 |
+
print(f" Rejecting image (square logo/avatar heuristic: {width}x{height})")
|
| 113 |
+
return False
|
| 114 |
+
|
| 115 |
+
# Standard Deviation check (blank or solid color placeholder images)
|
| 116 |
+
# A natural photograph typically has standard deviation > 10.
|
| 117 |
+
# Spacer GIFs or blank images will have standard deviation near 0.
|
| 118 |
+
stat = ImageStat.Stat(img)
|
| 119 |
+
# Check standard deviation of all bands (RGB / RGBA / L)
|
| 120 |
+
std_devs = stat.stddev
|
| 121 |
+
if std_devs and all(sd < 3.0 for sd in std_devs):
|
| 122 |
+
print(f" Rejecting image (low variance / solid color placeholder: stddev={std_devs})")
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
except ImportError:
|
| 126 |
+
print(" Warning: Pillow (PIL) is not installed. Skipping image dimension and content validation.")
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f" Warning: Failed to validate image content properties: {e}")
|
| 129 |
+
|
| 130 |
+
return True
|
| 131 |
+
|
| 132 |
+
def extract_og_image(url):
|
| 133 |
+
headers = {
|
| 134 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 135 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 136 |
+
"Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
|
| 137 |
+
"Referer": "https://news.google.com/"
|
| 138 |
+
}
|
| 139 |
+
try:
|
| 140 |
+
if HAS_CURL_CFFI:
|
| 141 |
+
response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=15)
|
| 142 |
+
else:
|
| 143 |
+
response = requests.get(url, headers=headers, timeout=15)
|
| 144 |
+
response.raise_for_status()
|
| 145 |
+
html = response.text
|
| 146 |
+
m = re.search(r'<meta[^>]*property=[\'"]og:image[\'"][^>]*content=[\'"]([^\'"]+)[\'"]', html, re.I)
|
| 147 |
+
if m:
|
| 148 |
+
return m.group(1)
|
| 149 |
+
m2 = re.search(r'<meta[^>]*content=[\'"]([^\'"]+)[\'"][^>]*property=[\'"]og:image[\']', html, re.I)
|
| 150 |
+
if m2:
|
| 151 |
+
return m2.group(1)
|
| 152 |
+
except Exception as e:
|
| 153 |
+
print(f" Failed to fetch og:image from {url}: {e}")
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
def extract_source_url(md_content):
|
| 157 |
+
# Try finding the link in "Sources & Citations:" section at bottom
|
| 158 |
+
# e.g., - [Article Title](https://...)
|
| 159 |
+
urls = re.findall(r'-\s+\[[^\]]+\]\((https?://[^\)]+)\)', md_content)
|
| 160 |
+
if urls:
|
| 161 |
+
return urls[0]
|
| 162 |
+
|
| 163 |
+
# Fallback to metadata block
|
| 164 |
+
m = re.search(r'\*\*Source:\*\*\s*\[[^\]]+\]\((https?://[^\)]+)\)', md_content)
|
| 165 |
+
if m:
|
| 166 |
+
return m.group(1)
|
| 167 |
+
|
| 168 |
+
# Simple regex for any URL in parentheses
|
| 169 |
+
urls_any = re.findall(r'\((https?://[^\)]+)\)', md_content)
|
| 170 |
+
if urls_any:
|
| 171 |
+
return urls_any[0]
|
| 172 |
+
|
| 173 |
+
return None
|
| 174 |
+
|
| 175 |
+
def inject_carousel_to_md(md_path, img_paths):
|
| 176 |
+
try:
|
| 177 |
+
with open(md_path, 'r', encoding='utf-8') as f:
|
| 178 |
+
content = f.read()
|
| 179 |
+
|
| 180 |
+
# If carousel already exists, do not duplicate
|
| 181 |
+
if "```carousel" in content:
|
| 182 |
+
return
|
| 183 |
+
|
| 184 |
+
lines = content.splitlines()
|
| 185 |
+
title_idx = -1
|
| 186 |
+
for i, line in enumerate(lines):
|
| 187 |
+
if line.strip().startswith("# "):
|
| 188 |
+
title_idx = i
|
| 189 |
+
break
|
| 190 |
+
|
| 191 |
+
date_idx = -1
|
| 192 |
+
if title_idx != -1:
|
| 193 |
+
for i in range(title_idx + 1, len(lines)):
|
| 194 |
+
if lines[i].strip():
|
| 195 |
+
date_idx = i
|
| 196 |
+
break
|
| 197 |
+
|
| 198 |
+
insert_idx = -1
|
| 199 |
+
if date_idx != -1:
|
| 200 |
+
insert_idx = date_idx + 1
|
| 201 |
+
elif title_idx != -1:
|
| 202 |
+
insert_idx = title_idx + 1
|
| 203 |
+
|
| 204 |
+
if insert_idx != -1:
|
| 205 |
+
carousel_lines = ["", "```carousel"]
|
| 206 |
+
for j, img_path in enumerate(img_paths, 1):
|
| 207 |
+
# Clean path relative to ROOT_DIR
|
| 208 |
+
rel_path = os.path.relpath(img_path, ROOT_DIR).replace(os.sep, '/')
|
| 209 |
+
if j > 1:
|
| 210 |
+
carousel_lines.append("<!-- slide -->")
|
| 211 |
+
carousel_lines.append(f"")
|
| 212 |
+
carousel_lines.append("```")
|
| 213 |
+
carousel_lines.append("")
|
| 214 |
+
|
| 215 |
+
lines = lines[:insert_idx] + carousel_lines + lines[insert_idx:]
|
| 216 |
+
new_content = "\n".join(lines)
|
| 217 |
+
|
| 218 |
+
with open(md_path, 'w', encoding='utf-8') as f:
|
| 219 |
+
f.write(new_content)
|
| 220 |
+
print(f" Injected image carousel into markdown.")
|
| 221 |
+
except Exception as e:
|
| 222 |
+
print(f" Failed to update markdown file: {e}")
|
| 223 |
+
|
| 224 |
+
def main():
|
| 225 |
+
print("Starting recovery of missing article images...")
|
| 226 |
+
locales = ["en-US", "ja-JP", "en-EU", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 227 |
+
remover = WatermarkRemover(Path(ROOT_DIR)) if HAS_REMOVER else None
|
| 228 |
+
|
| 229 |
+
recovered_count = 0
|
| 230 |
+
failed_count = 0
|
| 231 |
+
limit = 300 # Expand processing limit to 300 for mass recovery
|
| 232 |
+
|
| 233 |
+
article_dirs = []
|
| 234 |
+
|
| 235 |
+
# Scan all directories
|
| 236 |
+
for locale in locales:
|
| 237 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 238 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 239 |
+
continue
|
| 240 |
+
for cat in os.listdir(locale_path):
|
| 241 |
+
cat_path = os.path.join(locale_path, cat)
|
| 242 |
+
if not os.path.isdir(cat_path) or cat == "__pycache__":
|
| 243 |
+
continue
|
| 244 |
+
for art in os.listdir(cat_path):
|
| 245 |
+
art_path = os.path.join(cat_path, art)
|
| 246 |
+
if not os.path.isdir(art_path) or art in ["__pycache__", "images", "sources"]:
|
| 247 |
+
continue
|
| 248 |
+
article_dirs.append((art_path, art))
|
| 249 |
+
|
| 250 |
+
print(f"Total articles found: {len(article_dirs)}")
|
| 251 |
+
|
| 252 |
+
# Filter for articles missing images
|
| 253 |
+
missing_images_dirs = []
|
| 254 |
+
for art_path, art in article_dirs:
|
| 255 |
+
has_img = False
|
| 256 |
+
img_dir = os.path.join(art_path, "images")
|
| 257 |
+
if os.path.exists(img_dir):
|
| 258 |
+
imgs = [f for f in os.listdir(img_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 259 |
+
if imgs:
|
| 260 |
+
has_img = True
|
| 261 |
+
else:
|
| 262 |
+
imgs = [f for f in os.listdir(art_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 263 |
+
if imgs:
|
| 264 |
+
has_img = True
|
| 265 |
+
|
| 266 |
+
if not has_img:
|
| 267 |
+
missing_images_dirs.append((art_path, art))
|
| 268 |
+
|
| 269 |
+
print(f"Articles missing images: {len(missing_images_dirs)}")
|
| 270 |
+
|
| 271 |
+
if not missing_images_dirs:
|
| 272 |
+
print("No articles are missing images. All clear!")
|
| 273 |
+
return
|
| 274 |
+
|
| 275 |
+
to_process = missing_images_dirs[:limit]
|
| 276 |
+
print(f"Processing first {len(to_process)} articles missing images...")
|
| 277 |
+
|
| 278 |
+
for art_path, art in to_process:
|
| 279 |
+
print(f"\nProcessing: {art}")
|
| 280 |
+
|
| 281 |
+
# Find main markdown file
|
| 282 |
+
md_files = [f for f in os.listdir(art_path) if f.endswith(".md") and not f.endswith(("script_short.md", "script_middle.md", "script_long.md", "script_normal.md", "script.md"))]
|
| 283 |
+
if not md_files:
|
| 284 |
+
print(" Warning: No main article markdown file found.")
|
| 285 |
+
continue
|
| 286 |
+
|
| 287 |
+
md_path = os.path.join(art_path, md_files[0])
|
| 288 |
+
try:
|
| 289 |
+
with open(md_path, 'r', encoding='utf-8') as f:
|
| 290 |
+
md_content = f.read()
|
| 291 |
+
except Exception as e:
|
| 292 |
+
print(f" Error reading markdown file: {e}")
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
source_url = extract_source_url(md_content)
|
| 296 |
+
if not source_url:
|
| 297 |
+
print(" Warning: Could not extract source URL from markdown.")
|
| 298 |
+
continue
|
| 299 |
+
|
| 300 |
+
print(f" Source URL: {source_url}")
|
| 301 |
+
|
| 302 |
+
# Decode Google News link
|
| 303 |
+
decoded_url = source_url
|
| 304 |
+
if "news.google.com" in source_url:
|
| 305 |
+
try:
|
| 306 |
+
res = new_decoderv1(source_url, interval=1)
|
| 307 |
+
if res.get("status"):
|
| 308 |
+
decoded_url = res["decoded_url"]
|
| 309 |
+
print(f" Decoded URL: {decoded_url}")
|
| 310 |
+
except Exception as e:
|
| 311 |
+
print(f" Warning: Failed to decode Google News URL: {e}")
|
| 312 |
+
|
| 313 |
+
# Extract og:image
|
| 314 |
+
img_url = extract_og_image(decoded_url)
|
| 315 |
+
if not img_url:
|
| 316 |
+
print(" Warning: No og:image found on site.")
|
| 317 |
+
failed_count += 1
|
| 318 |
+
continue
|
| 319 |
+
|
| 320 |
+
print(f" Found Image URL: {img_url}")
|
| 321 |
+
|
| 322 |
+
# Create images folder
|
| 323 |
+
images_dir = os.path.join(art_path, "images")
|
| 324 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 325 |
+
|
| 326 |
+
img_dest = os.path.join(images_dir, f"{art}_img1.jpg")
|
| 327 |
+
success = download_file(img_url, img_dest)
|
| 328 |
+
|
| 329 |
+
if success:
|
| 330 |
+
if not is_valid_image(img_url, img_dest):
|
| 331 |
+
print(" Rejected downloaded image as unrelated.")
|
| 332 |
+
if os.path.exists(img_dest):
|
| 333 |
+
try:
|
| 334 |
+
os.remove(img_dest)
|
| 335 |
+
except:
|
| 336 |
+
pass
|
| 337 |
+
failed_count += 1
|
| 338 |
+
continue
|
| 339 |
+
|
| 340 |
+
print(" Image downloaded and validated successfully.")
|
| 341 |
+
# Remove watermark
|
| 342 |
+
if remover:
|
| 343 |
+
try:
|
| 344 |
+
remover.remove_watermark(Path(img_dest), decoded_url)
|
| 345 |
+
except Exception as rem_err:
|
| 346 |
+
print(f" Failed to remove watermark: {rem_err}")
|
| 347 |
+
|
| 348 |
+
# Inject into markdown
|
| 349 |
+
inject_carousel_to_md(md_path, [img_dest])
|
| 350 |
+
recovered_count += 1
|
| 351 |
+
else:
|
| 352 |
+
failed_count += 1
|
| 353 |
+
|
| 354 |
+
print(f"\nImage recovery run finished.")
|
| 355 |
+
print(f"Successfully recovered images for: {recovered_count} articles")
|
| 356 |
+
print(f"Failed to recover for: {failed_count} articles")
|
| 357 |
+
print(f"Remaining articles missing images: {len(missing_images_dirs) - recovered_count}")
|
| 358 |
+
|
| 359 |
+
if __name__ == "__main__":
|
| 360 |
+
main()
|
run_generator_silent.vbs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Set WshShell = CreateObject("WScript.Shell")
|
| 2 |
+
WshShell.Run "cmd.exe /c cd /d C:\ComfyUI\Articles && C:\Users\eggof\AppData\Local\Programs\Python\Python313\python.exe generate_scripts_all.py --locale en-US --limit 5 --gpu >> generator_service.log 2>&1", 0, True
|
| 3 |
+
|
run_pipeline_safely.ps1
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# run_pipeline_safely.ps1
|
| 2 |
+
# Runs script generation, media collection, and quality gate copying for all locales sequentially,
|
| 3 |
+
# and sleeps between batches to allow TTS/Video generation on GPU to proceed.
|
| 4 |
+
|
| 5 |
+
$limit = 20
|
| 6 |
+
$sleepSeconds = 90 # Give plenty of time for TTS/video generation to run when GPU is idle
|
| 7 |
+
|
| 8 |
+
Write-Host "=== Safe Coordinated Sequential Pipeline Loop Started ==="
|
| 9 |
+
|
| 10 |
+
while ($true) {
|
| 11 |
+
$locales = @("en-US", "en-EU", "ja-JP")
|
| 12 |
+
$any_remaining = $false
|
| 13 |
+
|
| 14 |
+
foreach ($locale in $locales) {
|
| 15 |
+
Write-Host ""
|
| 16 |
+
Write-Host "========================================"
|
| 17 |
+
Write-Host "Processing Locale: $locale at $(Get-Date -Format 'HH:mm:ss')"
|
| 18 |
+
Write-Host "========================================"
|
| 19 |
+
|
| 20 |
+
# 1. Check remaining count first
|
| 21 |
+
$check = python -c "
|
| 22 |
+
import os
|
| 23 |
+
ROOT_DIR = r'C:\ComfyUI\Articles'
|
| 24 |
+
locale = '$locale'
|
| 25 |
+
loc_path = os.path.join(ROOT_DIR, locale)
|
| 26 |
+
article_dirs = []
|
| 27 |
+
if os.path.exists(loc_path):
|
| 28 |
+
for cat in os.listdir(loc_path):
|
| 29 |
+
if cat == '__pycache__': continue
|
| 30 |
+
cat_path = os.path.join(loc_path, cat)
|
| 31 |
+
if os.path.isdir(cat_path):
|
| 32 |
+
for art in os.listdir(cat_path):
|
| 33 |
+
if art in ['__pycache__', 'images', 'sources']: continue
|
| 34 |
+
art_path = os.path.join(cat_path, art)
|
| 35 |
+
if os.path.isdir(art_path):
|
| 36 |
+
md_files = [f for f in os.listdir(art_path) if f.endswith('.md')]
|
| 37 |
+
if md_files:
|
| 38 |
+
article_dirs.append(art_path)
|
| 39 |
+
dirs_to_process = []
|
| 40 |
+
for d in article_dirs:
|
| 41 |
+
all_exist = True
|
| 42 |
+
for length in ['short', 'middle', 'long']:
|
| 43 |
+
script_path = os.path.join(d, f'script_{length}.md')
|
| 44 |
+
txt_path = os.path.join(d, f'script_{length}_clean.txt')
|
| 45 |
+
if not os.path.exists(script_path) or not os.path.exists(txt_path):
|
| 46 |
+
all_exist = False
|
| 47 |
+
break
|
| 48 |
+
if not all_exist:
|
| 49 |
+
dirs_to_process.append(d)
|
| 50 |
+
print(len(dirs_to_process))
|
| 51 |
+
"
|
| 52 |
+
$remaining = [int]($check.Trim())
|
| 53 |
+
Write-Host "Remaining articles needing scripts in $($locale): $remaining"
|
| 54 |
+
|
| 55 |
+
if ($remaining -gt 0) {
|
| 56 |
+
$any_remaining = $true
|
| 57 |
+
|
| 58 |
+
Write-Host "1. Running script generation (limit $limit, GPU)..."
|
| 59 |
+
$process = Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\generate_scripts_all.py --locale $locale --limit $limit --gpu" -NoNewWindow -PassThru -Wait
|
| 60 |
+
|
| 61 |
+
Write-Host "2. Running media collection..."
|
| 62 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\collect_media_parallel.py --locale $locale" -NoNewWindow -PassThru -Wait
|
| 63 |
+
|
| 64 |
+
Write-Host "3. Running quality gate evaluation and copy..."
|
| 65 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\copy_passed_articles.py --locale $locale" -NoNewWindow -PassThru -Wait
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
if (-not $any_remaining) {
|
| 70 |
+
Write-Host "All locales have 100% of their scripts drafted!"
|
| 71 |
+
# We can still sleep and check again later, or sleep a long time.
|
| 72 |
+
Write-Host "Sleeping for 5 minutes before next check..."
|
| 73 |
+
Start-Sleep -Seconds 300
|
| 74 |
+
} else {
|
| 75 |
+
# Sleep to let the GPU run TTS and video generation
|
| 76 |
+
Write-Host "Cycle complete at $(Get-Date -Format 'HH:mm:ss'). Sleeping for $sleepSeconds seconds to let ComfyUI process TTS and videos..."
|
| 77 |
+
Start-Sleep -Seconds $sleepSeconds
|
| 78 |
+
}
|
| 79 |
+
}
|
run_scripts_safely.ps1
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param (
|
| 2 |
+
[string]$locale = "en-EU",
|
| 3 |
+
[string]$category = "",
|
| 4 |
+
[int]$limit = 10,
|
| 5 |
+
[switch]$gpu
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
Write-Host "Starting safe script generation loop for locale: $locale, category: $category, limit: $limit, GPU: $gpu"
|
| 9 |
+
|
| 10 |
+
$cmdArgs = "--locale $locale --limit $limit"
|
| 11 |
+
if ($gpu) {
|
| 12 |
+
$cmdArgs = $cmdArgs + " --gpu"
|
| 13 |
+
}
|
| 14 |
+
if ($category -ne "") {
|
| 15 |
+
$cmdArgs = $cmdArgs + " --category " + $category
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# Infinite loop running generate_scripts_all.py
|
| 19 |
+
while ($true) {
|
| 20 |
+
Write-Host "Running next batch (limit $limit)..."
|
| 21 |
+
|
| 22 |
+
# Run the script and capture both stdout and stderr
|
| 23 |
+
$process = Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\generate_scripts_all.py $cmdArgs" -NoNewWindow -PassThru -Wait
|
| 24 |
+
|
| 25 |
+
$exitCode = $process.ExitCode
|
| 26 |
+
Write-Host "Process finished with exit code: $exitCode"
|
| 27 |
+
|
| 28 |
+
Write-Host "Running media collection..."
|
| 29 |
+
$mediaArgs = "--locale $locale"
|
| 30 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\collect_media_parallel.py $mediaArgs" -NoNewWindow -PassThru -Wait
|
| 31 |
+
|
| 32 |
+
Write-Host "Running quality gate evaluation and copy..."
|
| 33 |
+
$copyArgs = "--locale $locale"
|
| 34 |
+
if ($category -ne "") {
|
| 35 |
+
$copyArgs = $copyArgs + " --category " + $category
|
| 36 |
+
}
|
| 37 |
+
Start-Process -FilePath "python" -ArgumentList "C:\ComfyUI\Articles\copy_passed_articles.py $copyArgs" -NoNewWindow -PassThru -Wait
|
| 38 |
+
|
| 39 |
+
# Wait a bit to prevent tight loop if something is fundamentally broken
|
| 40 |
+
Start-Sleep -Seconds 3
|
| 41 |
+
|
| 42 |
+
# Verify if there are any remaining articles by doing a quick run that will check status
|
| 43 |
+
# We can run with --limit 0 (if supported) or just check the output of a test check.
|
| 44 |
+
# To keep it simple, we run a check logic:
|
| 45 |
+
# If the process completed successfully but processed 0 count, it means we are done.
|
| 46 |
+
# We can inspect history or files, but running the script and checking if it skips immediately is easiest.
|
| 47 |
+
# Let's run a dry run check via python inline
|
| 48 |
+
$check = python -c "
|
| 49 |
+
import os
|
| 50 |
+
ROOT_DIR = r'C:\ComfyUI\Articles'
|
| 51 |
+
locale = '$locale'
|
| 52 |
+
category = '$category' if '$category' else None
|
| 53 |
+
locales = [locale]
|
| 54 |
+
article_dirs = []
|
| 55 |
+
for loc in locales:
|
| 56 |
+
loc_path = os.path.join(ROOT_DIR, loc)
|
| 57 |
+
if not os.path.exists(loc_path): continue
|
| 58 |
+
cats = [category] if category else os.listdir(loc_path)
|
| 59 |
+
for cat in cats:
|
| 60 |
+
if cat == '__pycache__': continue
|
| 61 |
+
cat_path = os.path.join(loc_path, cat)
|
| 62 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path): continue
|
| 63 |
+
for art in os.listdir(cat_path):
|
| 64 |
+
if art in ['__pycache__', 'images', 'sources']: continue
|
| 65 |
+
art_path = os.path.join(cat_path, art)
|
| 66 |
+
if os.path.isdir(art_path):
|
| 67 |
+
md_files = [f for f in os.listdir(art_path) if f.endswith('.md')]
|
| 68 |
+
if md_files:
|
| 69 |
+
article_dirs.append(art_path)
|
| 70 |
+
|
| 71 |
+
dirs_to_process = []
|
| 72 |
+
for d in article_dirs:
|
| 73 |
+
all_exist = True
|
| 74 |
+
for length in ['short', 'middle', 'long']:
|
| 75 |
+
script_path = os.path.join(d, f'script_{length}.md')
|
| 76 |
+
txt_path = os.path.join(d, f'script_{length}_clean.txt')
|
| 77 |
+
if not os.path.exists(script_path) or not os.path.exists(txt_path):
|
| 78 |
+
all_exist = False
|
| 79 |
+
break
|
| 80 |
+
if not all_exist:
|
| 81 |
+
dirs_to_process.append(d)
|
| 82 |
+
|
| 83 |
+
print(len(dirs_to_process))
|
| 84 |
+
"
|
| 85 |
+
|
| 86 |
+
$remaining = [int]($check.Trim())
|
| 87 |
+
Write-Host "Remaining articles requiring scripts: $remaining"
|
| 88 |
+
|
| 89 |
+
if ($remaining -eq 0) {
|
| 90 |
+
Write-Host "Success! All articles in $locale (category: $category) have scripts generated."
|
| 91 |
+
break
|
| 92 |
+
}
|
| 93 |
+
}
|
run_silent.vbs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Set WshShell = CreateObject("WScript.Shell")
|
| 2 |
+
WshShell.Run "cmd.exe /c cd /d C:\ComfyUI\Articles && C:\Users\eggof\AppData\Local\Programs\Python\Python313\python.exe collect_news_service.py >> service.log 2>&1", 0, True
|
| 3 |
+
|
run_tts_silent.vbs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Set WshShell = CreateObject("WScript.Shell")
|
| 2 |
+
WshShell.Run "cmd.exe /c C:\Users\eggof\AppData\Local\Programs\Python\Python313\python.exe -u C:\ComfyUI\Articles\auto_tts_on_idle.py --all-lengths >> C:\ComfyUI\Articles\auto_tts_stdout.log 2>> C:\ComfyUI\Articles\auto_tts_stderr.log", 0, False
|
| 3 |
+
|
run_video_watcher.ps1
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# C:\ComfyUI\Articles\run_video_watcher.ps1
|
| 2 |
+
# Runs process_ready_videos_step.py in a loop to copy completed videos and queue next jobs when ComfyUI is idle.
|
| 3 |
+
|
| 4 |
+
Write-Host "=== Continuous Video Pipeline Watcher Loop Started ==="
|
| 5 |
+
|
| 6 |
+
while ($true) {
|
| 7 |
+
Write-Host ""
|
| 8 |
+
Write-Host "========================================"
|
| 9 |
+
Write-Host "Running video step check at $(Get-Date -Format 'HH:mm:ss')"
|
| 10 |
+
Write-Host "========================================"
|
| 11 |
+
|
| 12 |
+
# Clean up duplicate PowerShell and Python processes to prevent resource contention/OOM
|
| 13 |
+
C:\Python313\python.exe C:\ComfyUI\Articles\cleanup_duplicates.py
|
| 14 |
+
|
| 15 |
+
C:\Python313\python.exe C:\ComfyUI\Articles\evaluate_for_video.py --locale en-US --skip-llm
|
| 16 |
+
# C:\Python313\python.exe C:\ComfyUI\Articles\evaluate_for_video.py --locale en-EU --skip-llm
|
| 17 |
+
# C:\Python313\python.exe C:\ComfyUI\Articles\evaluate_for_video.py --locale ja-JP --skip-llm
|
| 18 |
+
|
| 19 |
+
C:\Python313\python.exe C:\ComfyUI\Articles\process_ready_videos_step.py
|
| 20 |
+
|
| 21 |
+
# Sleep for 60 seconds before next check
|
| 22 |
+
Start-Sleep -Seconds 60
|
| 23 |
+
}
|
| 24 |
+
|
script_long.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"importance": 8,
|
| 3 |
+
"urgency": 8,
|
| 4 |
+
"tier": 1
|
| 5 |
+
}
|
script_long.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Good evening. Tonight, we delve into a fascinating development in the world of media analysis and content verification. A recent report highlights an intriguing phenomenon: high-contrast corner patterns in images flagged as potentially containing logos or text embedded within them.
|
| 2 |
+
|
| 3 |
+
The report reveals that over 900 images were scanned, with a significant portion flagged for further investigation. This raises questions about the potential use of watermarks and their impact on image authenticity. The report highlights specific examples where these high-contrast corners, often associated with watermarks, have been identified as a cause for concern.
|
| 4 |
+
|
| 5 |
+
The report details several images from BBC News, specifically focusing on articles related to the South African migrant crisis. These images showcase prominent watermarks in the bottom left corner. The report reveals that the presence of such watermarks is flagged as a potential indicator of manipulation or alteration.
|
| 6 |
+
|
| 7 |
+
These findings raise important questions about the integrity of online content and the need for robust verification practices. As we move forward, it's crucial to understand how these techniques are used and what measures can be taken to ensure the accuracy and authenticity of information shared online.
|
script_long.rag_ingested
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"doc_id": "7c0992c4ac379025", "ingested_at": "2026-06-30T08:25:13.843281", "content_hash": "7c0992c4ac379025"}
|