[UPLOAD] Sync Android Times articles archive
Browse files- .gitattributes +1 -0
- AndroidTimesDashboard.bat +10 -0
- auto_tts_on_idle.py +534 -0
- batch_remove_watermarks.py +342 -0
- broll_assets.db +3 -0
- bypass_denoise_and_tts.py +253 -0
- check_watermarks.py +219 -0
- cleanup_duplicates.py +100 -0
- collect_broll_agent.py +988 -0
- collect_media_parallel.py +148 -0
- collect_news_service.py +524 -0
- copy_completed_videos.py +326 -0
- copy_passed_articles.py +197 -0
- create_perplexity_article.py +99 -0
- cron_processor.py +62 -0
.gitattributes
CHANGED
|
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
docs/AI_Computer_Vision/arxiv-cs-cv-20250405-20260405.md filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
docs/AI_Computer_Vision/arxiv-cs-cv-20250405-20260405.md filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
broll_assets.db filter=lfs diff=lfs merge=lfs -text
|
AndroidTimesDashboard.bat
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
cd /d "C:\Users\eggof\Desktop\Android Times\articles-viewer"
|
| 3 |
+
echo Starting AndroidTimesDashboard...
|
| 4 |
+
target\release\AndroidTimesDashboard.exe
|
| 5 |
+
if %errorlevel% neq 0 (
|
| 6 |
+
echo.
|
| 7 |
+
echo Application exited with error code %errorlevel%.
|
| 8 |
+
echo If you see a graphics-related error, you may need to update your GPU drivers or run with a different graphics backend.
|
| 9 |
+
pause
|
| 10 |
+
)
|
auto_tts_on_idle.py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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()
|
batch_remove_watermarks.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import shutil
|
| 5 |
+
import time
|
| 6 |
+
import socket
|
| 7 |
+
import urllib.request
|
| 8 |
+
import json
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image, ImageDraw
|
| 13 |
+
|
| 14 |
+
REPORT_PATH = r"C:\ComfyUI\Articles\watermark_scan_report.md"
|
| 15 |
+
LAMA_MODEL_PATH = os.path.join(os.path.expanduser("~"), ".cache", "torch", "hub", "checkpoints", "big-lama.pt")
|
| 16 |
+
|
| 17 |
+
COMFYUI_URL = "http://127.0.0.1:7777"
|
| 18 |
+
COMFYUI_INPUT_DIR = r"C:\ComfyUI\input"
|
| 19 |
+
COMFYUI_OUTPUT_DIR = r"C:\ComfyUI\output"
|
| 20 |
+
WORKFLOW_PATH = r"C:\ComfyUI\Articles\watermark_inpaint_workflow.json"
|
| 21 |
+
|
| 22 |
+
def is_port_open(host, port):
|
| 23 |
+
try:
|
| 24 |
+
with socket.create_connection((host, port), timeout=1):
|
| 25 |
+
return True
|
| 26 |
+
except OSError:
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
def check_comfy_online():
|
| 30 |
+
return is_port_open("127.0.0.1", 7777)
|
| 31 |
+
|
| 32 |
+
def create_mask(image_path, flagged_corners, mask_path):
|
| 33 |
+
img = Image.open(image_path)
|
| 34 |
+
w, h = img.size
|
| 35 |
+
|
| 36 |
+
# Create black image
|
| 37 |
+
mask = Image.new("L", (w, h), 0)
|
| 38 |
+
|
| 39 |
+
# Detect if Guardian to use larger mask
|
| 40 |
+
is_guardian = "guardian" in image_path.lower()
|
| 41 |
+
|
| 42 |
+
if is_guardian:
|
| 43 |
+
# Guardian banner is massive in bottom right
|
| 44 |
+
rect_w = int(w * 0.38)
|
| 45 |
+
rect_h = int(h * 0.35)
|
| 46 |
+
else:
|
| 47 |
+
# 25% width, 15% height is usually enough for standard watermarks
|
| 48 |
+
rect_w = int(w * 0.25)
|
| 49 |
+
rect_h = int(h * 0.15)
|
| 50 |
+
|
| 51 |
+
draw = ImageDraw.Draw(mask)
|
| 52 |
+
|
| 53 |
+
for corner in flagged_corners:
|
| 54 |
+
if corner == 'top_left':
|
| 55 |
+
draw.rectangle([0, 0, rect_w, rect_h], fill=255)
|
| 56 |
+
elif corner == 'top_right':
|
| 57 |
+
draw.rectangle([w - rect_w, 0, w, rect_h], fill=255)
|
| 58 |
+
elif corner == 'bottom_left':
|
| 59 |
+
draw.rectangle([0, h - rect_h, rect_w, h], fill=255)
|
| 60 |
+
elif corner == 'bottom_right':
|
| 61 |
+
draw.rectangle([w - rect_w, h - rect_h, w, h], fill=255)
|
| 62 |
+
|
| 63 |
+
mask.save(mask_path)
|
| 64 |
+
return mask
|
| 65 |
+
|
| 66 |
+
def get_all_jpgs(root_dir):
|
| 67 |
+
jpgs = []
|
| 68 |
+
for root, dirs, files in os.walk(root_dir):
|
| 69 |
+
for f in files:
|
| 70 |
+
if f.endswith('.jpg'):
|
| 71 |
+
jpgs.append(os.path.join(root, f))
|
| 72 |
+
return jpgs
|
| 73 |
+
|
| 74 |
+
def simplify_string(s):
|
| 75 |
+
s = s.replace('.jpg', '')
|
| 76 |
+
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
|
| 77 |
+
return s
|
| 78 |
+
|
| 79 |
+
def process_report():
|
| 80 |
+
if not os.path.exists(REPORT_PATH):
|
| 81 |
+
print(f"Report not found at {REPORT_PATH}")
|
| 82 |
+
return []
|
| 83 |
+
|
| 84 |
+
with open(REPORT_PATH, 'r', encoding='utf-8') as f:
|
| 85 |
+
lines = f.readlines()
|
| 86 |
+
|
| 87 |
+
tasks = []
|
| 88 |
+
current_filename = None
|
| 89 |
+
current_corners = []
|
| 90 |
+
|
| 91 |
+
for line in lines:
|
| 92 |
+
line = line.strip()
|
| 93 |
+
m_file = re.match(r"^### \d+\. (.+)$", line)
|
| 94 |
+
if m_file:
|
| 95 |
+
if current_filename and current_corners:
|
| 96 |
+
tasks.append({
|
| 97 |
+
'image': current_filename,
|
| 98 |
+
'corners': current_corners
|
| 99 |
+
})
|
| 100 |
+
current_filename = m_file.group(1)
|
| 101 |
+
current_corners = []
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
m_flag = re.search(r"\*\*(top_left|top_right|bottom_left|bottom_right)\*\*:.*\(Flagged\)", line)
|
| 105 |
+
if m_flag:
|
| 106 |
+
current_corners.append(m_flag.group(1))
|
| 107 |
+
|
| 108 |
+
if current_filename and current_corners:
|
| 109 |
+
tasks.append({
|
| 110 |
+
'image': current_filename,
|
| 111 |
+
'corners': current_corners
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
all_jpgs = get_all_jpgs(r"C:\ComfyUI\Articles")
|
| 115 |
+
jpg_map = []
|
| 116 |
+
for path in all_jpgs:
|
| 117 |
+
filename = os.path.basename(path)
|
| 118 |
+
simple = simplify_string(filename)
|
| 119 |
+
m = re.search(r'img(\d+)$', simple)
|
| 120 |
+
img_num = m.group(1) if m else None
|
| 121 |
+
jpg_map.append({'path': path, 'simple': simple, 'img_num': img_num})
|
| 122 |
+
|
| 123 |
+
matched_tasks = []
|
| 124 |
+
for task in tasks:
|
| 125 |
+
rep_filename = os.path.basename(task['image'])
|
| 126 |
+
rep_simple = simplify_string(rep_filename)
|
| 127 |
+
m = re.search(r'img(\d+)$', rep_simple)
|
| 128 |
+
rep_img_num = m.group(1) if m else None
|
| 129 |
+
|
| 130 |
+
best_match = None
|
| 131 |
+
for j in jpg_map:
|
| 132 |
+
if rep_img_num and j['img_num']:
|
| 133 |
+
if rep_img_num != j['img_num']: continue
|
| 134 |
+
elif rep_img_num or j['img_num']: continue
|
| 135 |
+
|
| 136 |
+
j_clean = j['simple'].replace('original', '')
|
| 137 |
+
rep_clean = rep_simple.replace('original', '')
|
| 138 |
+
if j_clean == rep_clean:
|
| 139 |
+
best_match = j['path']
|
| 140 |
+
break
|
| 141 |
+
|
| 142 |
+
if best_match:
|
| 143 |
+
matched_tasks.append({
|
| 144 |
+
'image': best_match,
|
| 145 |
+
'corners': task['corners']
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
return matched_tasks
|
| 149 |
+
|
| 150 |
+
def process_via_comfyui(img_path, corners):
|
| 151 |
+
# Create mask locally first
|
| 152 |
+
mask_path = img_path + "_mask.png"
|
| 153 |
+
mask_pil = create_mask(img_path, corners, mask_path)
|
| 154 |
+
|
| 155 |
+
# Save original backup
|
| 156 |
+
backup_path = img_path.replace(".jpg", "_original.jpg").replace(".png", "_original.png")
|
| 157 |
+
if not os.path.exists(backup_path):
|
| 158 |
+
shutil.copy2(img_path, backup_path)
|
| 159 |
+
|
| 160 |
+
# Copy input and mask to ComfyUI input directory
|
| 161 |
+
unique_id = str(int(time.time())) + "_" + str(np.random.randint(1000, 9999))
|
| 162 |
+
comfy_in_name = f"watermark_in_{unique_id}.jpg"
|
| 163 |
+
comfy_mask_name = f"watermark_mask_{unique_id}.png"
|
| 164 |
+
|
| 165 |
+
shutil.copy2(backup_path, os.path.join(COMFYUI_INPUT_DIR, comfy_in_name))
|
| 166 |
+
shutil.copy2(mask_path, os.path.join(COMFYUI_INPUT_DIR, comfy_mask_name))
|
| 167 |
+
|
| 168 |
+
# Load workflow template
|
| 169 |
+
with open(WORKFLOW_PATH, 'r', encoding='utf-8') as f:
|
| 170 |
+
workflow = json.load(f)
|
| 171 |
+
|
| 172 |
+
# Update inputs
|
| 173 |
+
workflow["39"]["inputs"]["image"] = comfy_in_name
|
| 174 |
+
workflow["40"]["inputs"]["image"] = comfy_mask_name
|
| 175 |
+
|
| 176 |
+
# Generate seed
|
| 177 |
+
seed = int(np.random.randint(1, 10000000))
|
| 178 |
+
workflow["43"]["inputs"]["seed"] = seed
|
| 179 |
+
|
| 180 |
+
# Queue prompt
|
| 181 |
+
print(f" Sending to ComfyUI API...")
|
| 182 |
+
payload = {"prompt": workflow, "client_id": "watermark_remover_agent"}
|
| 183 |
+
data = json.dumps(payload).encode('utf-8')
|
| 184 |
+
req = urllib.request.Request(f"{COMFYUI_URL}/prompt", data=data, headers={'Content-Type': 'application/json'})
|
| 185 |
+
|
| 186 |
+
try:
|
| 187 |
+
with urllib.request.urlopen(req) as res:
|
| 188 |
+
res_data = json.loads(res.read().decode('utf-8'))
|
| 189 |
+
prompt_id = res_data["prompt_id"]
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print(f" Failed to queue prompt: {e}")
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
print(f" Prompt queued. ID: {prompt_id}. Waiting for completion...")
|
| 195 |
+
|
| 196 |
+
# Poll for completion
|
| 197 |
+
completed = False
|
| 198 |
+
output_filename = None
|
| 199 |
+
|
| 200 |
+
# Wait up to 120 seconds
|
| 201 |
+
for _ in range(60):
|
| 202 |
+
time.sleep(2)
|
| 203 |
+
# Check history
|
| 204 |
+
req_hist = urllib.request.Request(f"{COMFYUI_URL}/history/{prompt_id}")
|
| 205 |
+
try:
|
| 206 |
+
with urllib.request.urlopen(req_hist) as res_hist:
|
| 207 |
+
hist_data = json.loads(res_hist.read().decode('utf-8'))
|
| 208 |
+
if prompt_id in hist_data:
|
| 209 |
+
# Completed!
|
| 210 |
+
outputs = hist_data[prompt_id].get("outputs", {})
|
| 211 |
+
# Find output from node 99 (SaveImage)
|
| 212 |
+
save_node_out = outputs.get("99", {})
|
| 213 |
+
if "images" in save_node_out and len(save_node_out["images"]) > 0:
|
| 214 |
+
output_filename = save_node_out["images"][0]["filename"]
|
| 215 |
+
completed = True
|
| 216 |
+
break
|
| 217 |
+
except Exception as e:
|
| 218 |
+
# ComfyUI might still be processing
|
| 219 |
+
pass
|
| 220 |
+
|
| 221 |
+
if not completed:
|
| 222 |
+
print(" Timeout waiting for ComfyUI to process.")
|
| 223 |
+
return False
|
| 224 |
+
|
| 225 |
+
# Copy completed image back
|
| 226 |
+
comfy_out_path = os.path.join(COMFYUI_OUTPUT_DIR, output_filename)
|
| 227 |
+
if os.path.exists(comfy_out_path):
|
| 228 |
+
shutil.copy2(comfy_out_path, img_path)
|
| 229 |
+
print(f" Successfully removed watermark using ComfyUI! Saved to {img_path}")
|
| 230 |
+
# Clean up input folder files
|
| 231 |
+
try:
|
| 232 |
+
os.remove(os.path.join(COMFYUI_INPUT_DIR, comfy_in_name))
|
| 233 |
+
os.remove(os.path.join(COMFYUI_INPUT_DIR, comfy_mask_name))
|
| 234 |
+
os.remove(mask_path)
|
| 235 |
+
except:
|
| 236 |
+
pass
|
| 237 |
+
return True
|
| 238 |
+
else:
|
| 239 |
+
print(f" ComfyUI output file not found at {comfy_out_path}")
|
| 240 |
+
return False
|
| 241 |
+
|
| 242 |
+
def process_via_local_fallback(img_path, corners, model, device):
|
| 243 |
+
mask_path = img_path + "_mask.png"
|
| 244 |
+
mask_pil = create_mask(img_path, corners, mask_path)
|
| 245 |
+
|
| 246 |
+
backup_path = img_path.replace(".jpg", "_original.jpg").replace(".png", "_original.png")
|
| 247 |
+
if not os.path.exists(backup_path):
|
| 248 |
+
shutil.copy2(img_path, backup_path)
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
img_pil = Image.open(backup_path).convert("RGB")
|
| 252 |
+
except Exception as e:
|
| 253 |
+
print(f" -> Error opening image: {e}")
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
w, h = img_pil.size
|
| 257 |
+
|
| 258 |
+
img_np = np.array(img_pil, dtype=np.float32) / 255.0
|
| 259 |
+
mask_np = np.array(mask_pil, dtype=np.float32) / 255.0
|
| 260 |
+
mask_np = (mask_np > 0.1).astype(np.float32)
|
| 261 |
+
|
| 262 |
+
image_tensor = torch.from_numpy(img_np).permute(2, 0, 1).unsqueeze(0).to(device)
|
| 263 |
+
mask_tensor = torch.from_numpy(mask_np).unsqueeze(0).unsqueeze(0).to(device)
|
| 264 |
+
|
| 265 |
+
pad_mod = 8
|
| 266 |
+
pad_h = (pad_mod - h % pad_mod) % pad_mod
|
| 267 |
+
pad_w = (pad_mod - w % pad_mod) % pad_mod
|
| 268 |
+
|
| 269 |
+
if pad_h > 0 or pad_w > 0:
|
| 270 |
+
image_tensor = F.pad(image_tensor, (0, pad_w, 0, pad_h), mode='reflect')
|
| 271 |
+
mask_tensor = F.pad(mask_tensor, (0, pad_w, 0, pad_h), mode='constant', value=0.0)
|
| 272 |
+
|
| 273 |
+
with torch.no_grad():
|
| 274 |
+
output = model(image_tensor, mask_tensor)
|
| 275 |
+
|
| 276 |
+
if pad_h > 0 or pad_w > 0:
|
| 277 |
+
output = output[:, :, :h, :w]
|
| 278 |
+
|
| 279 |
+
output = output.squeeze(0).permute(1, 2, 0).cpu().numpy()
|
| 280 |
+
output = np.clip(output * 255.0, 0, 255).astype(np.uint8)
|
| 281 |
+
|
| 282 |
+
output_pil = Image.fromarray(output)
|
| 283 |
+
output_pil.save(img_path)
|
| 284 |
+
print(" -> Success (Local Fallback)")
|
| 285 |
+
|
| 286 |
+
if os.path.exists(mask_path):
|
| 287 |
+
os.remove(mask_path)
|
| 288 |
+
return True
|
| 289 |
+
|
| 290 |
+
def main():
|
| 291 |
+
import sys
|
| 292 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 293 |
+
test_mode = "--test" in sys.argv
|
| 294 |
+
tasks = process_report()
|
| 295 |
+
print(f"Found {len(tasks)} images to process.")
|
| 296 |
+
|
| 297 |
+
if test_mode:
|
| 298 |
+
tasks = tasks[:2]
|
| 299 |
+
print(f"Running in TEST mode. Only processing {len(tasks)} images.")
|
| 300 |
+
|
| 301 |
+
if not tasks:
|
| 302 |
+
sys.exit(0)
|
| 303 |
+
|
| 304 |
+
comfy_online = check_comfy_online()
|
| 305 |
+
local_model = None
|
| 306 |
+
device = None
|
| 307 |
+
|
| 308 |
+
if comfy_online:
|
| 309 |
+
print("ComfyUI is ONLINE. Using ComfyUI API for high-quality removal.")
|
| 310 |
+
else:
|
| 311 |
+
print("ComfyUI is OFFLINE. Initializing local PyTorch LaMa fallback...")
|
| 312 |
+
if not os.path.exists(LAMA_MODEL_PATH):
|
| 313 |
+
print("LaMa model not found. Please run lama_inpaint.py once to download it.")
|
| 314 |
+
sys.exit(1)
|
| 315 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 316 |
+
print(f"Using device: {device}")
|
| 317 |
+
local_model = torch.jit.load(LAMA_MODEL_PATH, map_location=device)
|
| 318 |
+
local_model.eval()
|
| 319 |
+
|
| 320 |
+
for i, task in enumerate(tasks):
|
| 321 |
+
img_path = task['image']
|
| 322 |
+
corners = task['corners']
|
| 323 |
+
print(f"[{i+1}/{len(tasks)}] Processing {img_path}")
|
| 324 |
+
|
| 325 |
+
if not os.path.exists(img_path):
|
| 326 |
+
print(" -> File not found!")
|
| 327 |
+
continue
|
| 328 |
+
|
| 329 |
+
if comfy_online:
|
| 330 |
+
success = process_via_comfyui(img_path, corners)
|
| 331 |
+
if not success:
|
| 332 |
+
print(" Failed via ComfyUI. Attempting local fallback...")
|
| 333 |
+
if local_model is None:
|
| 334 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 335 |
+
local_model = torch.jit.load(LAMA_MODEL_PATH, map_location=device)
|
| 336 |
+
local_model.eval()
|
| 337 |
+
process_via_local_fallback(img_path, corners, local_model, device)
|
| 338 |
+
else:
|
| 339 |
+
process_via_local_fallback(img_path, corners, local_model, device)
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
main()
|
broll_assets.db
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7d1b2b2f9ca9c6a0d8684e7f381b29cb522f92a7de9d993b68f15d031f3b5d73
|
| 3 |
+
size 8171520
|
bypass_denoise_and_tts.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import uuid
|
| 5 |
+
import time
|
| 6 |
+
import urllib.request
|
| 7 |
+
import numpy as np
|
| 8 |
+
import librosa
|
| 9 |
+
import soundfile as sf
|
| 10 |
+
|
| 11 |
+
# Force Hugging Face and Transformers to load models offline
|
| 12 |
+
os.environ["HF_HUB_OFFLINE"] = "1"
|
| 13 |
+
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Add current directory to path
|
| 17 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
+
import tts_articles
|
| 19 |
+
|
| 20 |
+
def bypass_denoise(workflow_path):
|
| 21 |
+
with open(workflow_path, 'r', encoding='utf-8') as f:
|
| 22 |
+
wf = json.load(f)
|
| 23 |
+
|
| 24 |
+
denoise_node = None
|
| 25 |
+
save_audio_node = None
|
| 26 |
+
|
| 27 |
+
for node in wf["nodes"]:
|
| 28 |
+
if node["type"] == "ResembleDenoise":
|
| 29 |
+
denoise_node = node
|
| 30 |
+
elif node["type"] == "SaveAudio":
|
| 31 |
+
save_audio_node = node
|
| 32 |
+
|
| 33 |
+
if not denoise_node or not save_audio_node:
|
| 34 |
+
print(f"Warning: ResembleDenoise or SaveAudio node not found in {workflow_path}")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
input_link_id = None
|
| 38 |
+
for inp in denoise_node.get("inputs", []):
|
| 39 |
+
if inp["name"] == "audio":
|
| 40 |
+
input_link_id = inp.get("link")
|
| 41 |
+
|
| 42 |
+
if input_link_id is None:
|
| 43 |
+
print(f"Warning: ResembleDenoise input link not found in {workflow_path}")
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
# Connect input_link_id directly to SaveAudio
|
| 47 |
+
for inp in save_audio_node.get("inputs", []):
|
| 48 |
+
if inp["name"] == "audio":
|
| 49 |
+
inp["link"] = input_link_id
|
| 50 |
+
|
| 51 |
+
# Update the link in the workflow's links list
|
| 52 |
+
save_audio_id = save_audio_node["id"]
|
| 53 |
+
modified_link = False
|
| 54 |
+
for link in wf.get("links", []):
|
| 55 |
+
if link and link[0] == input_link_id:
|
| 56 |
+
link[3] = save_audio_id # to_node
|
| 57 |
+
link[4] = 0 # to_slot
|
| 58 |
+
modified_link = True
|
| 59 |
+
|
| 60 |
+
if not modified_link:
|
| 61 |
+
print(f"Warning: Link {input_link_id} not found in links list of {workflow_path}")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
# Remove ResembleDenoise node from the nodes list to be clean
|
| 65 |
+
wf["nodes"] = [n for n in wf["nodes"] if n["id"] != denoise_node["id"]]
|
| 66 |
+
|
| 67 |
+
# Save the modified workflow
|
| 68 |
+
with open(workflow_path, 'w', encoding='utf-8') as f:
|
| 69 |
+
json.dump(wf, f, indent=2)
|
| 70 |
+
print(f"Successfully bypassed ResembleDenoise in {workflow_path}")
|
| 71 |
+
return True
|
| 72 |
+
|
| 73 |
+
def run_tts_for_workflow(article_dir, workflow_path, output_filename, script_name="script_middle.md", server_url="http://127.0.0.1:7777"):
|
| 74 |
+
client_id = str(uuid.uuid4())
|
| 75 |
+
api_prompt_template = tts_articles.convert_ui_to_api(workflow_path, server_url)
|
| 76 |
+
|
| 77 |
+
text_input_node_id = None
|
| 78 |
+
save_audio_node_id = None
|
| 79 |
+
index_tts_node_id = None
|
| 80 |
+
emotion_text_node_id = None
|
| 81 |
+
|
| 82 |
+
for node_id, node in api_prompt_template.items():
|
| 83 |
+
if node["class_type"] == "TextInput_":
|
| 84 |
+
text_input_node_id = node_id
|
| 85 |
+
elif node["class_type"] == "SaveAudio":
|
| 86 |
+
save_audio_node_id = node_id
|
| 87 |
+
elif node["class_type"] in ["IndexTTSRun", "easy indexTTSGenerate", "IndexTTS2EmotionText"]:
|
| 88 |
+
index_tts_node_id = node_id
|
| 89 |
+
elif node["class_type"] == "easy indexTTSEmotionText":
|
| 90 |
+
emotion_text_node_id = node_id
|
| 91 |
+
|
| 92 |
+
if not text_input_node_id or not save_audio_node_id:
|
| 93 |
+
print(f"Error: Required nodes not found in {workflow_path}")
|
| 94 |
+
return False
|
| 95 |
+
|
| 96 |
+
script_file = os.path.join(article_dir, script_name)
|
| 97 |
+
if not os.path.exists(script_file):
|
| 98 |
+
print(f"Error: {script_name} not found in {article_dir}")
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
script_text = tts_articles.clean_script_text(script_file)
|
| 102 |
+
segments = tts_articles.split_into_segments(script_text)
|
| 103 |
+
if not segments:
|
| 104 |
+
print(f"Error: Script is empty.")
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
print(f"\nProcessing {len(segments)} segments with workflow {os.path.basename(workflow_path)}...")
|
| 108 |
+
|
| 109 |
+
audio_segments = []
|
| 110 |
+
comfy_output_dir = os.path.abspath(os.path.join(os.path.dirname(workflow_path), "..", "output"))
|
| 111 |
+
segment_failed = False
|
| 112 |
+
sr = 24000 # default
|
| 113 |
+
|
| 114 |
+
for s_idx, segment in enumerate(segments):
|
| 115 |
+
is_last = (s_idx == len(segments) - 1)
|
| 116 |
+
speed_factor = 1.0 # Force 1.0 to bypass time_stretch and avoid echo artifacts
|
| 117 |
+
pause_duration = tts_articles.get_pause_duration(segment)
|
| 118 |
+
|
| 119 |
+
emphasized_segment = segment # Bypass emphasis pause tags to prevent model confusion
|
| 120 |
+
emotion_desc = tts_articles.get_emotion_description(segment)
|
| 121 |
+
print(f" Segment {s_idx+1}/{len(segments)}: '{segment[:60]}...'")
|
| 122 |
+
print(f" -> Emotion: {emotion_desc}")
|
| 123 |
+
|
| 124 |
+
prompt = json.loads(json.dumps(api_prompt_template))
|
| 125 |
+
prompt[text_input_node_id]["inputs"]["text"] = emphasized_segment
|
| 126 |
+
|
| 127 |
+
if emotion_text_node_id:
|
| 128 |
+
prompt[emotion_text_node_id]["inputs"]["description"] = emotion_desc
|
| 129 |
+
elif index_tts_node_id and prompt[index_tts_node_id]["class_type"] == "IndexTTS2EmotionText":
|
| 130 |
+
prompt[index_tts_node_id]["inputs"]["emo_text"] = emotion_desc
|
| 131 |
+
prompt[index_tts_node_id]["inputs"]["use_emo_text"] = True
|
| 132 |
+
|
| 133 |
+
prompt_id = str(uuid.uuid4())
|
| 134 |
+
filename_prefix = f"audio/article_tts_{prompt_id}"
|
| 135 |
+
prompt[save_audio_node_id]["inputs"]["filename_prefix"] = filename_prefix
|
| 136 |
+
|
| 137 |
+
if index_tts_node_id and index_tts_node_id in prompt:
|
| 138 |
+
if prompt[index_tts_node_id]["class_type"] != "IndexTTS2EmotionText":
|
| 139 |
+
prompt[index_tts_node_id]["inputs"]["unload_model"] = is_last
|
| 140 |
+
elif "105" in prompt:
|
| 141 |
+
if prompt["105"]["class_type"] not in ["IndexTTS2ModelLoader", "IndexTTS2EmotionText"]:
|
| 142 |
+
prompt["105"]["inputs"]["unload_model"] = is_last
|
| 143 |
+
|
| 144 |
+
# Queue prompt
|
| 145 |
+
try:
|
| 146 |
+
resp = tts_articles.queue_prompt(server_url, prompt, prompt_id, client_id)
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f" Error: Failed to queue prompt: {e}")
|
| 149 |
+
segment_failed = True
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
# Wait for completion
|
| 153 |
+
completed = False
|
| 154 |
+
start_time = time.time()
|
| 155 |
+
while time.time() - start_time < 600:
|
| 156 |
+
try:
|
| 157 |
+
history = tts_articles.get_history(server_url, prompt_id)
|
| 158 |
+
if prompt_id in history:
|
| 159 |
+
completed = True
|
| 160 |
+
break
|
| 161 |
+
except:
|
| 162 |
+
pass
|
| 163 |
+
time.sleep(0.5)
|
| 164 |
+
|
| 165 |
+
if not completed:
|
| 166 |
+
print(f" Error: TTS timed out.")
|
| 167 |
+
segment_failed = True
|
| 168 |
+
break
|
| 169 |
+
|
| 170 |
+
history_entry = history[prompt_id]
|
| 171 |
+
outputs = history_entry.get("outputs", {})
|
| 172 |
+
|
| 173 |
+
if save_audio_node_id not in outputs or "audio" not in outputs[save_audio_node_id]:
|
| 174 |
+
print(f" Error: SaveAudio output not found.")
|
| 175 |
+
segment_failed = True
|
| 176 |
+
break
|
| 177 |
+
|
| 178 |
+
audio_outputs = outputs[save_audio_node_id]["audio"]
|
| 179 |
+
if not audio_outputs:
|
| 180 |
+
print(f" Error: No audio files returned.")
|
| 181 |
+
segment_failed = True
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
audio_info = audio_outputs[0]
|
| 185 |
+
gen_filename = audio_info["filename"]
|
| 186 |
+
gen_subfolder = audio_info["subfolder"]
|
| 187 |
+
|
| 188 |
+
src_path = os.path.join(comfy_output_dir, gen_subfolder, gen_filename)
|
| 189 |
+
if not os.path.exists(src_path):
|
| 190 |
+
src_path = os.path.join(r"C:\ComfyUI\output", gen_subfolder, gen_filename)
|
| 191 |
+
|
| 192 |
+
if not os.path.exists(src_path):
|
| 193 |
+
print(f" Error: Generated audio file not found at: {src_path}")
|
| 194 |
+
segment_failed = True
|
| 195 |
+
break
|
| 196 |
+
|
| 197 |
+
try:
|
| 198 |
+
y, sr = librosa.load(src_path, sr=None)
|
| 199 |
+
if abs(speed_factor - 1.0) > 0.01:
|
| 200 |
+
y_stretched = librosa.effects.time_stretch(y=y, rate=speed_factor)
|
| 201 |
+
else:
|
| 202 |
+
y_stretched = y
|
| 203 |
+
audio_segments.append(y_stretched)
|
| 204 |
+
|
| 205 |
+
if pause_duration > 0 and not is_last:
|
| 206 |
+
silence = np.zeros(int(sr * pause_duration))
|
| 207 |
+
audio_segments.append(silence)
|
| 208 |
+
|
| 209 |
+
os.remove(src_path)
|
| 210 |
+
except Exception as audio_err:
|
| 211 |
+
print(f" Error: Audio post-processing failed: {audio_err}")
|
| 212 |
+
segment_failed = True
|
| 213 |
+
break
|
| 214 |
+
|
| 215 |
+
if segment_failed:
|
| 216 |
+
print("Workflow execution failed.")
|
| 217 |
+
return False
|
| 218 |
+
|
| 219 |
+
dest_path = os.path.join(article_dir, output_filename)
|
| 220 |
+
try:
|
| 221 |
+
final_audio = np.concatenate(audio_segments)
|
| 222 |
+
max_val = np.max(np.abs(final_audio))
|
| 223 |
+
if max_val > 0.001:
|
| 224 |
+
final_audio = final_audio / max_val * 0.9
|
| 225 |
+
sf.write(dest_path, final_audio, sr, format='FLAC')
|
| 226 |
+
print(f"Saved TTS audio to: {dest_path}")
|
| 227 |
+
return True
|
| 228 |
+
except Exception as save_err:
|
| 229 |
+
print(f"Error saving final audio: {save_err}")
|
| 230 |
+
return False
|
| 231 |
+
|
| 232 |
+
if __name__ == "__main__":
|
| 233 |
+
wf_15 = r"C:\ComfyUI\workflows\05_Audio_&_TTS\Text to Speech.json"
|
| 234 |
+
|
| 235 |
+
article_dir = r"C:\ComfyUI\Articles\en-US\Moscow_Attacks\Moscow_Metro_hit_by_deadly_suicide_bombings_-_BBC"
|
| 236 |
+
|
| 237 |
+
# Run IndexTTS 1.5 for script_short_clean.txt
|
| 238 |
+
print("\n==================== Running IndexTTS 1.5 for short script ====================")
|
| 239 |
+
run_tts_for_workflow(
|
| 240 |
+
article_dir=article_dir,
|
| 241 |
+
workflow_path=wf_15,
|
| 242 |
+
output_filename="Moscow_Metro_hit_by_deadly_suicide_bombings_-_BBC_short_indextts1.5.flac",
|
| 243 |
+
script_name="script_short_clean.txt"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Run IndexTTS 1.5 for script_long_clean.txt
|
| 247 |
+
print("\n==================== Running IndexTTS 1.5 for long script ====================")
|
| 248 |
+
run_tts_for_workflow(
|
| 249 |
+
article_dir=article_dir,
|
| 250 |
+
workflow_path=wf_15,
|
| 251 |
+
output_filename="Moscow_Metro_hit_by_deadly_suicide_bombings_-_BBC_long_indextts1.5.flac",
|
| 252 |
+
script_name="script_long_clean.txt"
|
| 253 |
+
)
|
check_watermarks.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import argparse
|
| 5 |
+
import sys
|
| 6 |
+
import numpy as np
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 11 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 12 |
+
|
| 13 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 14 |
+
|
| 15 |
+
def analyze_corners(image_path):
|
| 16 |
+
try:
|
| 17 |
+
img = Image.open(image_path)
|
| 18 |
+
# Convert to grayscale for edge analysis
|
| 19 |
+
gray_img = img.convert("L")
|
| 20 |
+
w, h = img.size
|
| 21 |
+
arr = np.array(gray_img, dtype=np.float32)
|
| 22 |
+
|
| 23 |
+
# Simple horizontal and vertical differences to calculate edge strength
|
| 24 |
+
diff_x = np.abs(arr[:, 1:] - arr[:, :-1])
|
| 25 |
+
diff_y = np.abs(arr[1:, :] - arr[:-1, :])
|
| 26 |
+
|
| 27 |
+
edges = np.zeros_like(arr)
|
| 28 |
+
edges[:, :-1] += diff_x
|
| 29 |
+
edges[:-1, :] += diff_y
|
| 30 |
+
|
| 31 |
+
# Corner box: inspect 15% of width/height (standard watermark location size)
|
| 32 |
+
cw = int(w * 0.15)
|
| 33 |
+
ch = int(h * 0.15)
|
| 34 |
+
|
| 35 |
+
# Prevent zero-size slices
|
| 36 |
+
cw = max(cw, 10)
|
| 37 |
+
ch = max(ch, 10)
|
| 38 |
+
|
| 39 |
+
corners = {
|
| 40 |
+
"top_left": edges[0:ch, 0:cw],
|
| 41 |
+
"top_right": edges[0:ch, w-cw:w],
|
| 42 |
+
"bottom_left": edges[h-ch:h, 0:cw],
|
| 43 |
+
"bottom_right": edges[h-ch:h, w-cw:w]
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
results = {}
|
| 47 |
+
for name, region in corners.items():
|
| 48 |
+
mean_edge = np.mean(region)
|
| 49 |
+
max_edge = np.max(region)
|
| 50 |
+
|
| 51 |
+
# Heuristic thresholds:
|
| 52 |
+
# - mean_edge > 8.0 indicates texture or shape (lowered from 12.0 to detect thin text watermarks)
|
| 53 |
+
# - max_edge > 120.0 indicates a sharp text edge or logo line
|
| 54 |
+
is_potential_logo = mean_edge > 8.0 and max_edge > 120.0
|
| 55 |
+
results[name] = {
|
| 56 |
+
"edge_density": float(mean_edge),
|
| 57 |
+
"max_contrast": float(max_edge),
|
| 58 |
+
"is_potential_logo": bool(is_potential_logo)
|
| 59 |
+
}
|
| 60 |
+
return results
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return {"error": str(e)}
|
| 63 |
+
|
| 64 |
+
def get_article_source(article_dir):
|
| 65 |
+
# Find the main markdown article file
|
| 66 |
+
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md") and not f.endswith(("script_short.md", "script_middle.md", "script_long.md", "script_normal.md", "script.md"))]
|
| 67 |
+
if not md_files:
|
| 68 |
+
return "Unknown"
|
| 69 |
+
|
| 70 |
+
main_md = os.path.join(article_dir, md_files[0])
|
| 71 |
+
try:
|
| 72 |
+
with open(main_md, 'r', encoding='utf-8') as f:
|
| 73 |
+
content = f.read()
|
| 74 |
+
|
| 75 |
+
# Try to find "Source: [Source Name]" or similar in the metadata block
|
| 76 |
+
m = re.search(r'\*\*Source:\*\*\s*\[?([^\]\r\n]+)\]?', content, re.I)
|
| 77 |
+
if m:
|
| 78 |
+
return m.group(1).strip()
|
| 79 |
+
except:
|
| 80 |
+
pass
|
| 81 |
+
return "Unknown"
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
parser = argparse.ArgumentParser(description="Scan and inspect article images for watermarks and logos.")
|
| 85 |
+
parser.add_argument("--category", type=str, default=None, help="Inspect only a specific category.")
|
| 86 |
+
parser.add_argument("--locale", type=str, default=None, help="Inspect only a specific locale (en-US, ja-JP).")
|
| 87 |
+
parser.add_argument("--scan-all", action="store_true", help="Report potential logos in any image, regardless of known watermarked source.")
|
| 88 |
+
parser.add_argument("--output-report", type=str, default="watermark_scan_report.md", help="Filename of the markdown report to generate.")
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
|
| 91 |
+
locales = [args.locale] if args.locale else ["en-US", "ja-JP"]
|
| 92 |
+
scanned_count = 0
|
| 93 |
+
flagged_images = []
|
| 94 |
+
|
| 95 |
+
print("Scanning articles for image watermarks...")
|
| 96 |
+
|
| 97 |
+
for locale in locales:
|
| 98 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 99 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
categories = [args.category] if args.category else os.listdir(locale_path)
|
| 103 |
+
for category in categories:
|
| 104 |
+
if category in ["__pycache__"]:
|
| 105 |
+
continue
|
| 106 |
+
cat_path = os.path.join(locale_path, category)
|
| 107 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
articles = os.listdir(cat_path)
|
| 111 |
+
for article in articles:
|
| 112 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 113 |
+
continue
|
| 114 |
+
article_dir = os.path.join(cat_path, article)
|
| 115 |
+
if not os.path.isdir(article_dir):
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
source = get_article_source(article_dir)
|
| 119 |
+
source_lower = source.lower()
|
| 120 |
+
is_known_watermark_source = "bbc" in source_lower or "guardian" in source_lower
|
| 121 |
+
|
| 122 |
+
# Check for images in "images" subdirectory
|
| 123 |
+
img_dir = os.path.join(article_dir, "images")
|
| 124 |
+
image_paths = []
|
| 125 |
+
if os.path.exists(img_dir):
|
| 126 |
+
image_paths = [os.path.join(img_dir, f) for f in os.listdir(img_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 127 |
+
|
| 128 |
+
# Also check direct files
|
| 129 |
+
direct_imgs = [os.path.join(article_dir, f) for f in os.listdir(article_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 130 |
+
image_paths.extend(direct_imgs)
|
| 131 |
+
|
| 132 |
+
# Remove duplicates
|
| 133 |
+
image_paths = list(set(image_paths))
|
| 134 |
+
|
| 135 |
+
for img_path in image_paths:
|
| 136 |
+
scanned_count += 1
|
| 137 |
+
analysis = analyze_corners(img_path)
|
| 138 |
+
|
| 139 |
+
if "error" in analysis:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
# Determine if we should flag it
|
| 143 |
+
# BBC is top-left & bottom-left, Guardian is bottom-right.
|
| 144 |
+
flag = False
|
| 145 |
+
reason = []
|
| 146 |
+
|
| 147 |
+
if is_known_watermark_source or args.scan_all:
|
| 148 |
+
# Check specific corners for known sources
|
| 149 |
+
if "bbc" in source_lower:
|
| 150 |
+
if analysis["bottom_left"]["is_potential_logo"]:
|
| 151 |
+
flag = True
|
| 152 |
+
reason.append("BBC Watermark location (bottom-left) has high contrast edges")
|
| 153 |
+
if analysis["top_left"]["is_potential_logo"]:
|
| 154 |
+
flag = True
|
| 155 |
+
reason.append("BBC Verification stamp location (top-left) has high contrast edges")
|
| 156 |
+
elif "guardian" in source_lower:
|
| 157 |
+
if analysis["bottom_right"]["is_potential_logo"]:
|
| 158 |
+
flag = True
|
| 159 |
+
reason.append("The Guardian Logo location (bottom-right) has high contrast edges")
|
| 160 |
+
else:
|
| 161 |
+
# General scan for non-BBC/Guardian
|
| 162 |
+
for name, corner in analysis.items():
|
| 163 |
+
if corner["is_potential_logo"]:
|
| 164 |
+
flag = True
|
| 165 |
+
reason.append(f"Corner [{name}] contains a high-contrast pattern (possible logo)")
|
| 166 |
+
|
| 167 |
+
if flag:
|
| 168 |
+
flagged_images.append({
|
| 169 |
+
"image_path": img_path,
|
| 170 |
+
"article": article,
|
| 171 |
+
"category": category,
|
| 172 |
+
"source": source,
|
| 173 |
+
"reasons": reason,
|
| 174 |
+
"analysis": analysis
|
| 175 |
+
})
|
| 176 |
+
|
| 177 |
+
print(f"\nScan complete. Scanned {scanned_count} images.")
|
| 178 |
+
print(f"Flagged {len(flagged_images)} images with potential watermarks/logos.")
|
| 179 |
+
|
| 180 |
+
# Generate Markdown Report
|
| 181 |
+
report_path = os.path.join(ROOT_DIR, args.output_report)
|
| 182 |
+
try:
|
| 183 |
+
with open(report_path, 'w', encoding='utf-8') as f:
|
| 184 |
+
f.write(f"# Watermark and Logo Inspection Report\n")
|
| 185 |
+
f.write(f"Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
|
| 186 |
+
|
| 187 |
+
f.write(f"## Summary of Scan\n")
|
| 188 |
+
f.write(f"- **Total Images Scanned**: {scanned_count}\n")
|
| 189 |
+
f.write(f"- **Flagged Images**: {len(flagged_images)}\n")
|
| 190 |
+
f.write(f"- **Pass Rate**: {((scanned_count - len(flagged_images))/scanned_count*100) if scanned_count > 0 else 100:.2f}%\n\n")
|
| 191 |
+
|
| 192 |
+
if flagged_images:
|
| 193 |
+
f.write(f"## Flagged Images List\n")
|
| 194 |
+
f.write(f"The following images were flagged due to high-contrast corner patterns suggesting text, templates, or logos:\n\n")
|
| 195 |
+
|
| 196 |
+
for idx, item in enumerate(flagged_images, 1):
|
| 197 |
+
# Make path relative to ROOT_DIR for markdown links
|
| 198 |
+
rel_path = os.path.relpath(item["image_path"], ROOT_DIR).replace(os.sep, '/')
|
| 199 |
+
f.write(f"### {idx}. {os.path.basename(item['image_path'])}\n")
|
| 200 |
+
f.write(f"- **Article**: [{item['article']}](file:///{os.path.dirname(item['image_path']).replace(os.sep, '/')})\n")
|
| 201 |
+
f.write(f"- **Category**: {item['category']}\n")
|
| 202 |
+
f.write(f"- **Source**: {item['source']}\n")
|
| 203 |
+
f.write(f"- **Reasons for Flagging**:\n")
|
| 204 |
+
for r in item["reasons"]:
|
| 205 |
+
f.write(f" - ⚠️ {r}\n")
|
| 206 |
+
f.write(f"- **Raw Corner Edge Densities / Max Contrast**:\n")
|
| 207 |
+
for name, corner in item["analysis"].items():
|
| 208 |
+
f.write(f" - **{name}**: Density = {corner['edge_density']:.2f}, Max Contrast = {corner['max_contrast']:.2f} {'(Flagged)' if corner['is_potential_logo'] else ''}\n")
|
| 209 |
+
f.write(f"\n")
|
| 210 |
+
else:
|
| 211 |
+
f.write(f"## All Clear!\n")
|
| 212 |
+
f.write(f"No potential watermarks or logos detected in the scanned image corner regions.\n")
|
| 213 |
+
|
| 214 |
+
print(f"Report saved successfully to {report_path}")
|
| 215 |
+
except Exception as e:
|
| 216 |
+
print(f"Failed to save report: {e}")
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
main()
|
cleanup_duplicates.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import psutil
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
# Reconfigure stdout to utf-8 to prevent encoding crashes on Windows
|
| 7 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 8 |
+
|
| 9 |
+
TARGET_SCRIPTS = [
|
| 10 |
+
"auto_tts_on_idle.py",
|
| 11 |
+
"tqdm_watcher.py",
|
| 12 |
+
"run_pipeline_safely.ps1",
|
| 13 |
+
"run_video_watcher.ps1"
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
def cleanup_duplicates():
|
| 17 |
+
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Starting duplicate process cleanup...")
|
| 18 |
+
|
| 19 |
+
# Map from target script name to list of psutil.Process objects
|
| 20 |
+
found_processes = {script: [] for script in TARGET_SCRIPTS}
|
| 21 |
+
|
| 22 |
+
# Scan all running processes
|
| 23 |
+
for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'create_time']):
|
| 24 |
+
try:
|
| 25 |
+
cmdline = proc.info['cmdline']
|
| 26 |
+
if not cmdline:
|
| 27 |
+
continue
|
| 28 |
+
|
| 29 |
+
cmdline_str = " ".join(cmdline).lower()
|
| 30 |
+
proc_name = proc.info['name'].lower()
|
| 31 |
+
|
| 32 |
+
for target in TARGET_SCRIPTS:
|
| 33 |
+
# Check if this command line references our target script
|
| 34 |
+
if target.lower() in cmdline_str:
|
| 35 |
+
is_match = False
|
| 36 |
+
# For python scripts, the executing process must be python
|
| 37 |
+
if target.endswith(".py") and "python" in proc_name:
|
| 38 |
+
is_match = True
|
| 39 |
+
# For powershell scripts, the executing process must be powershell
|
| 40 |
+
elif target.endswith(".ps1") and ("powershell" in proc_name or "pwsh" in proc_name):
|
| 41 |
+
is_match = True
|
| 42 |
+
|
| 43 |
+
if is_match:
|
| 44 |
+
found_processes[target].append(proc)
|
| 45 |
+
break
|
| 46 |
+
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
cleaned_count = 0
|
| 50 |
+
|
| 51 |
+
for script, procs in found_processes.items():
|
| 52 |
+
# Filter out parent wrapper processes (if process A is parent of process B in the same list, A is a wrapper)
|
| 53 |
+
filtered_procs = []
|
| 54 |
+
for p in procs:
|
| 55 |
+
try:
|
| 56 |
+
is_parent = False
|
| 57 |
+
for other in procs:
|
| 58 |
+
if other.pid != p.pid:
|
| 59 |
+
try:
|
| 60 |
+
if other.ppid() == p.pid:
|
| 61 |
+
is_parent = True
|
| 62 |
+
break
|
| 63 |
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
| 64 |
+
pass
|
| 65 |
+
if not is_parent:
|
| 66 |
+
filtered_procs.append(p)
|
| 67 |
+
except Exception:
|
| 68 |
+
filtered_procs.append(p)
|
| 69 |
+
|
| 70 |
+
if len(filtered_procs) <= 1:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
print(f"Found {len(filtered_procs)} running instances of {script}:")
|
| 74 |
+
|
| 75 |
+
# Sort processes by creation time (oldest first)
|
| 76 |
+
# We want to keep the oldest instance as it's the main daemon, and kill the duplicates.
|
| 77 |
+
filtered_procs.sort(key=lambda p: p.info['create_time'])
|
| 78 |
+
|
| 79 |
+
main_proc = filtered_procs[0]
|
| 80 |
+
duplicate_procs = filtered_procs[1:]
|
| 81 |
+
|
| 82 |
+
main_time = datetime.fromtimestamp(main_proc.info['create_time']).strftime('%Y-%m-%d %H:%M:%S')
|
| 83 |
+
print(f" [KEEP] PID {main_proc.pid} (Started: {main_time})")
|
| 84 |
+
|
| 85 |
+
for dup in duplicate_procs:
|
| 86 |
+
dup_time = datetime.fromtimestamp(dup.info['create_time']).strftime('%Y-%m-%d %H:%M:%S')
|
| 87 |
+
print(f" [KILL] PID {dup.pid} (Started: {dup_time})")
|
| 88 |
+
try:
|
| 89 |
+
dup.kill()
|
| 90 |
+
cleaned_count += 1
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f" Failed to kill PID {dup.pid}: {e}")
|
| 93 |
+
|
| 94 |
+
if cleaned_count > 0:
|
| 95 |
+
print(f"Successfully terminated {cleaned_count} duplicate process(es) to reclaim VRAM and prevent OOM.")
|
| 96 |
+
else:
|
| 97 |
+
print("No duplicate processes found. All daemons running normally.")
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
cleanup_duplicates()
|
collect_broll_agent.py
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import re
|
| 4 |
+
import time
|
| 5 |
+
import urllib.request
|
| 6 |
+
import urllib.error
|
| 7 |
+
import urllib.parse
|
| 8 |
+
import json
|
| 9 |
+
import sqlite3
|
| 10 |
+
import subprocess
|
| 11 |
+
import argparse
|
| 12 |
+
import hashlib
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 15 |
+
import logging
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
# Reconfigure stdout/stderr to utf-8 to avoid encoding issues on Windows
|
| 19 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 20 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 21 |
+
|
| 22 |
+
# Logging setup
|
| 23 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 24 |
+
logger = logging.getLogger("broll_agent")
|
| 25 |
+
|
| 26 |
+
# Optional AI dependencies
|
| 27 |
+
HAS_AI = False
|
| 28 |
+
try:
|
| 29 |
+
import torch
|
| 30 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 31 |
+
HAS_AI = True
|
| 32 |
+
except ImportError:
|
| 33 |
+
logger.warning("CLIP libraries (torch/transformers) not available. Local visual indexing will be simulated.")
|
| 34 |
+
|
| 35 |
+
# DuckDuckGo fallback crawler
|
| 36 |
+
HAS_DDG = False
|
| 37 |
+
try:
|
| 38 |
+
from duckduckgo_search import DDGS
|
| 39 |
+
HAS_DDG = True
|
| 40 |
+
except ImportError:
|
| 41 |
+
logger.warning("duckduckgo_search package not available. DuckDuckGo fallback search disabled.")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def load_dotenv():
|
| 45 |
+
"""Locate and load .env file manually to support standalone execution."""
|
| 46 |
+
paths = [
|
| 47 |
+
Path.cwd() / ".env",
|
| 48 |
+
Path.cwd().parent / ".env",
|
| 49 |
+
Path(__file__).parent / ".env",
|
| 50 |
+
Path(r"C:\Android Times\Articles") / ".env",
|
| 51 |
+
Path(r"C:\ComfyUI\Articles") / ".env",
|
| 52 |
+
Path(r"C:\Roaming") / ".env"
|
| 53 |
+
]
|
| 54 |
+
for p in paths:
|
| 55 |
+
if p.exists():
|
| 56 |
+
logger.info(f"Loading environment variables from {p}")
|
| 57 |
+
with open(p, "r", encoding="utf-8") as f:
|
| 58 |
+
for line in f:
|
| 59 |
+
line = line.strip()
|
| 60 |
+
if line and not line.startswith("#") and "=" in line:
|
| 61 |
+
k, v = line.split("=", 1)
|
| 62 |
+
# strip quotes if present
|
| 63 |
+
v = v.strip().strip("'\"")
|
| 64 |
+
os.environ[k.strip()] = v
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Load env variables at startup
|
| 69 |
+
load_dotenv()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ==========================================
|
| 73 |
+
# 1. Query Fallback Mechanics
|
| 74 |
+
# ==========================================
|
| 75 |
+
|
| 76 |
+
def clean_query(text):
|
| 77 |
+
"""Remove special characters and extra spaces to clean search queries."""
|
| 78 |
+
text = re.sub(r'[^\w\s-]', '', text)
|
| 79 |
+
# Dedup spaces
|
| 80 |
+
return " ".join(text.split()).strip()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def generate_queries_via_gemini(title, category=None):
|
| 84 |
+
"""Fetch visual search queries optimized for stock search using Gemini API."""
|
| 85 |
+
api_key = os.environ.get("GEMINI_API_KEY")
|
| 86 |
+
if not api_key:
|
| 87 |
+
logger.warning("GEMINI_API_KEY is not set. Falling back to mechanical query extraction.")
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={api_key}"
|
| 91 |
+
headers = {"Content-Type": "application/json"}
|
| 92 |
+
|
| 93 |
+
# Instruct Gemini to output visual, concrete English queries
|
| 94 |
+
prompt = f"""
|
| 95 |
+
Given the news title: "{title}" (Category: {category if category else 'General'})
|
| 96 |
+
Suggest 3 simple, visual, and concrete search queries in English to find relevant stock photos or footage (for B-roll) on image search engines (like Getty Images).
|
| 97 |
+
Rules:
|
| 98 |
+
- Queries must be in English (even if the title is Japanese).
|
| 99 |
+
- Keep queries simple (usually 2-3 words, e.g., "artificial intelligence server", "stock market graph").
|
| 100 |
+
- Maintain core brand names or entities (like "Google", "OpenAI", "Elon Musk", "Mbappe", "Warren Buffett") if they are key to the article.
|
| 101 |
+
- Avoid abstract verbs, adverbs, or figures of speech (do NOT use words like "paces", "stunning", "simply", "crushed").
|
| 102 |
+
- Format the response as a JSON array of strings: ["query1", "query2", "query3"].
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
payload = {
|
| 106 |
+
"contents": [{"parts": [{"text": prompt}]}],
|
| 107 |
+
"generationConfig": {
|
| 108 |
+
"responseMimeType": "application/json"
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers)
|
| 114 |
+
with urllib.request.urlopen(req, timeout=12) as response:
|
| 115 |
+
res_data = json.loads(response.read().decode('utf-8'))
|
| 116 |
+
text_response = res_data["candidates"][0]["content"]["parts"][0]["text"]
|
| 117 |
+
# Clean possible markdown wrap from JSON response
|
| 118 |
+
cleaned_text = text_response.strip().replace("```json", "").replace("```", "").strip()
|
| 119 |
+
queries = json.loads(cleaned_text)
|
| 120 |
+
if isinstance(queries, dict):
|
| 121 |
+
queries = list(queries.values())
|
| 122 |
+
if isinstance(queries, list) and len(queries) > 0:
|
| 123 |
+
# Flatten nested lists if any (e.g. [["q1", "q2"]])
|
| 124 |
+
flat_queries = []
|
| 125 |
+
for item in queries:
|
| 126 |
+
if isinstance(item, list):
|
| 127 |
+
flat_queries.extend([str(x) for x in item])
|
| 128 |
+
else:
|
| 129 |
+
flat_queries.append(str(item))
|
| 130 |
+
queries = flat_queries
|
| 131 |
+
logger.info(f"LLM generated visual search queries: {queries}")
|
| 132 |
+
return queries
|
| 133 |
+
except Exception as e:
|
| 134 |
+
logger.warning(f"Failed to generate queries via Gemini API: {e}")
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_ollama_model():
|
| 139 |
+
"""Retrieve available Ollama models and pick the best candidate."""
|
| 140 |
+
try:
|
| 141 |
+
url = "http://127.0.0.1:11434/api/tags"
|
| 142 |
+
req = urllib.request.Request(url)
|
| 143 |
+
with urllib.request.urlopen(req, timeout=3) as response:
|
| 144 |
+
data = json.loads(response.read().decode('utf-8'))
|
| 145 |
+
models = [m.get("name") for m in data.get("models", [])]
|
| 146 |
+
if not models:
|
| 147 |
+
return None
|
| 148 |
+
for preferred in ["llama3.2:latest", "gemma2:2b", "gemma-4-e4b-uncensored:latest", "gemma4:latest", "litert-community/gemma-4-E2B-it-litert-lm:latest"]:
|
| 149 |
+
if preferred in models:
|
| 150 |
+
return preferred
|
| 151 |
+
return models[0]
|
| 152 |
+
except Exception:
|
| 153 |
+
return None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def generate_queries_via_ollama(title, category=None):
|
| 157 |
+
"""Fetch visual search queries optimized for stock search using local Ollama API."""
|
| 158 |
+
model = get_ollama_model()
|
| 159 |
+
if not model:
|
| 160 |
+
logger.warning("Local Ollama endpoint is not available or has no models.")
|
| 161 |
+
return None
|
| 162 |
+
logger.info(f"Using Ollama model '{model}' for query generation.")
|
| 163 |
+
|
| 164 |
+
url = "http://127.0.0.1:11434/api/generate"
|
| 165 |
+
headers = {"Content-Type": "application/json"}
|
| 166 |
+
|
| 167 |
+
prompt = f"""
|
| 168 |
+
Given the news title: "{title}" (Category: {category if category else 'General'})
|
| 169 |
+
Suggest 3 simple, visual, and concrete search queries in English to find relevant stock photos or footage (for B-roll) on image search engines (like Getty Images).
|
| 170 |
+
Rules:
|
| 171 |
+
- Queries must be in English (even if the title is Japanese).
|
| 172 |
+
- Keep queries simple (usually 2-3 words, e.g., "artificial intelligence server", "stock market graph").
|
| 173 |
+
- Maintain core brand names or entities (like "Google", "OpenAI", "Elon Musk", "Mbappe", "Warren Buffett") if they are key to the article.
|
| 174 |
+
- Avoid abstract verbs, adverbs, or figures of speech (do NOT use words like "paces", "stunning", "simply", "crushed").
|
| 175 |
+
- Format the response strictly as a JSON array of strings: ["query1", "query2", "query3"]. Do not include any other text or explanation.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
payload = {
|
| 179 |
+
"model": model,
|
| 180 |
+
"prompt": prompt,
|
| 181 |
+
"stream": False,
|
| 182 |
+
"format": "json"
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers)
|
| 187 |
+
with urllib.request.urlopen(req, timeout=90) as response:
|
| 188 |
+
res_data = json.loads(response.read().decode('utf-8'))
|
| 189 |
+
text_response = res_data.get("response", "")
|
| 190 |
+
cleaned_text = text_response.strip().replace("```json", "").replace("```", "").strip()
|
| 191 |
+
queries = json.loads(cleaned_text)
|
| 192 |
+
if isinstance(queries, dict):
|
| 193 |
+
queries = list(queries.values())
|
| 194 |
+
if isinstance(queries, list) and len(queries) > 0:
|
| 195 |
+
# Flatten nested lists if any (e.g. [["q1", "q2"]])
|
| 196 |
+
flat_queries = []
|
| 197 |
+
for item in queries:
|
| 198 |
+
if isinstance(item, list):
|
| 199 |
+
flat_queries.extend([str(x) for x in item])
|
| 200 |
+
else:
|
| 201 |
+
flat_queries.append(str(item))
|
| 202 |
+
queries = flat_queries
|
| 203 |
+
logger.info(f"Ollama ({model}) generated visual search queries: {queries}")
|
| 204 |
+
return queries
|
| 205 |
+
except Exception as e:
|
| 206 |
+
logger.warning(f"Failed to generate queries via Ollama API: {e}")
|
| 207 |
+
return None
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def generate_fallback_queries(title, category=None):
|
| 211 |
+
"""Generate multi-stage fallback queries based on PRD requirements, prioritized by LLM generation."""
|
| 212 |
+
# 1. Try Gemini API first
|
| 213 |
+
llm_queries = generate_queries_via_gemini(title, category)
|
| 214 |
+
if llm_queries:
|
| 215 |
+
# Append category fallback to LLM queries just in case
|
| 216 |
+
if category and category.lower() not in [q.lower() for q in llm_queries]:
|
| 217 |
+
llm_queries.append(clean_query(category))
|
| 218 |
+
return llm_queries
|
| 219 |
+
|
| 220 |
+
# 2. Try Ollama local LLM fallback
|
| 221 |
+
ollama_queries = generate_queries_via_ollama(title, category)
|
| 222 |
+
if ollama_queries:
|
| 223 |
+
if category and category.lower() not in [q.lower() for q in ollama_queries]:
|
| 224 |
+
ollama_queries.append(clean_query(category))
|
| 225 |
+
return ollama_queries
|
| 226 |
+
|
| 227 |
+
queries = []
|
| 228 |
+
cleaned_title = clean_query(title)
|
| 229 |
+
words = cleaned_title.split()
|
| 230 |
+
|
| 231 |
+
# Stage 1: Cleaned full title (capped to first 5 words)
|
| 232 |
+
if len(words) > 0:
|
| 233 |
+
queries.append(" ".join(words[:5]))
|
| 234 |
+
|
| 235 |
+
# Stage 2: Short fallback (first 2-3 words)
|
| 236 |
+
if len(words) > 2:
|
| 237 |
+
queries.append(" ".join(words[:3]))
|
| 238 |
+
elif len(words) > 0:
|
| 239 |
+
queries.append(" ".join(words[:2]))
|
| 240 |
+
|
| 241 |
+
# Stage 3: Category fallback
|
| 242 |
+
if category:
|
| 243 |
+
queries.append(clean_query(category))
|
| 244 |
+
|
| 245 |
+
# Remove duplicates while preserving priority order
|
| 246 |
+
unique_queries = []
|
| 247 |
+
for q in queries:
|
| 248 |
+
if q and q.strip() and q not in unique_queries:
|
| 249 |
+
unique_queries.append(q)
|
| 250 |
+
|
| 251 |
+
logger.info(f"Generated search queries hierarchy: {unique_queries}")
|
| 252 |
+
return unique_queries
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# ==========================================
|
| 256 |
+
# 2. Asset Search Providers
|
| 257 |
+
# ==========================================
|
| 258 |
+
|
| 259 |
+
def search_unsplash(query, access_key, limit=3):
|
| 260 |
+
"""Search Unsplash via official REST API."""
|
| 261 |
+
if not access_key:
|
| 262 |
+
return []
|
| 263 |
+
encoded_query = urllib.parse.quote(query)
|
| 264 |
+
url = f"https://api.unsplash.com/search/photos?query={encoded_query}&per_page={limit}"
|
| 265 |
+
headers = {"Authorization": f"Client-ID {access_key}", "User-Agent": "BrollAgent/1.0"}
|
| 266 |
+
try:
|
| 267 |
+
req = urllib.request.Request(url, headers=headers)
|
| 268 |
+
with urllib.request.urlopen(req, timeout=10) as response:
|
| 269 |
+
data = json.loads(response.read().decode('utf-8'))
|
| 270 |
+
results = []
|
| 271 |
+
for item in data.get("results", []):
|
| 272 |
+
results.append({
|
| 273 |
+
"title": item.get("description") or item.get("alt_description") or query,
|
| 274 |
+
"url": item.get("urls", {}).get("regular"),
|
| 275 |
+
"platform": "Unsplash",
|
| 276 |
+
"photographer": item.get("user", {}).get("name") or "Unknown"
|
| 277 |
+
})
|
| 278 |
+
return results
|
| 279 |
+
except Exception as e:
|
| 280 |
+
logger.warning(f"Unsplash API error for query '{query}': {e}")
|
| 281 |
+
return []
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def search_pexels(query, api_key, limit=3):
|
| 285 |
+
"""Search Pexels via official REST API."""
|
| 286 |
+
if not api_key:
|
| 287 |
+
return []
|
| 288 |
+
encoded_query = urllib.parse.quote(query)
|
| 289 |
+
url = f"https://api.pexels.com/v1/search?query={encoded_query}&per_page={limit}"
|
| 290 |
+
headers = {"Authorization": api_key, "User-Agent": "BrollAgent/1.0"}
|
| 291 |
+
try:
|
| 292 |
+
req = urllib.request.Request(url, headers=headers)
|
| 293 |
+
with urllib.request.urlopen(req, timeout=10) as response:
|
| 294 |
+
data = json.loads(response.read().decode('utf-8'))
|
| 295 |
+
results = []
|
| 296 |
+
for item in data.get("photos", []):
|
| 297 |
+
results.append({
|
| 298 |
+
"title": item.get("alt") or query,
|
| 299 |
+
"url": item.get("src", {}).get("large"),
|
| 300 |
+
"platform": "Pexels",
|
| 301 |
+
"photographer": item.get("photographer") or "Unknown"
|
| 302 |
+
})
|
| 303 |
+
return results
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logger.warning(f"Pexels API error for query '{query}': {e}")
|
| 306 |
+
return []
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def scrape_getty(query, limit=3):
|
| 310 |
+
"""Fallback Getty Images HTML scraper."""
|
| 311 |
+
encoded_query = urllib.parse.quote(query)
|
| 312 |
+
# Use Japanese subdomain or international
|
| 313 |
+
url = f"https://www.gettyimages.co.jp/search/2/image?phrase={encoded_query}"
|
| 314 |
+
headers = {
|
| 315 |
+
'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'
|
| 316 |
+
}
|
| 317 |
+
try:
|
| 318 |
+
req = urllib.request.Request(url, headers=headers)
|
| 319 |
+
with urllib.request.urlopen(req, timeout=10) as response:
|
| 320 |
+
html = response.read().decode('utf-8')
|
| 321 |
+
|
| 322 |
+
# Extract getty image urls from HTML
|
| 323 |
+
# Getty images typically use URLs like https://media.gettyimages.com/id/12345678/...
|
| 324 |
+
# We match greedily until double quotes, space, or angle brackets
|
| 325 |
+
pattern = r'https://media\.gettyimages\.com/id/[^"\s>]+'
|
| 326 |
+
urls = re.findall(pattern, html)
|
| 327 |
+
|
| 328 |
+
# Clean up escape backslashes, hex encodings and amp entities
|
| 329 |
+
cleaned_urls = []
|
| 330 |
+
for u in urls:
|
| 331 |
+
# Replace \u0026 or u0026 or & with &
|
| 332 |
+
u_clean = u.replace('\\u0026', '&').replace('u0026', '&').replace('&', '&').replace('\\', '')
|
| 333 |
+
cleaned_urls.append(u_clean)
|
| 334 |
+
|
| 335 |
+
# Dedup
|
| 336 |
+
urls = list(dict.fromkeys(cleaned_urls))
|
| 337 |
+
|
| 338 |
+
results = []
|
| 339 |
+
for i, img_url in enumerate(urls[:limit]):
|
| 340 |
+
results.append({
|
| 341 |
+
"title": f"{query} - Getty Asset {i}",
|
| 342 |
+
"url": img_url,
|
| 343 |
+
"platform": "GettyScraped",
|
| 344 |
+
"photographer": "Getty Images"
|
| 345 |
+
})
|
| 346 |
+
return results
|
| 347 |
+
except Exception as e:
|
| 348 |
+
logger.warning(f"Getty Images scraping error for query '{query}': {e}")
|
| 349 |
+
return []
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def search_ddg_fallback(query, limit=3):
|
| 353 |
+
"""Fallback DuckDuckGo image crawler."""
|
| 354 |
+
if not HAS_DDG:
|
| 355 |
+
return []
|
| 356 |
+
# Add a short delay to avoid DDG rate limits
|
| 357 |
+
time.sleep(2)
|
| 358 |
+
try:
|
| 359 |
+
ddgs = DDGS()
|
| 360 |
+
raw_results = list(ddgs.images(query, max_results=limit))
|
| 361 |
+
results = []
|
| 362 |
+
for res in raw_results:
|
| 363 |
+
results.append({
|
| 364 |
+
"title": res.get("title") or query,
|
| 365 |
+
"url": res.get("image"),
|
| 366 |
+
"platform": "DuckDuckGo",
|
| 367 |
+
"photographer": res.get("source") or "Unknown"
|
| 368 |
+
})
|
| 369 |
+
return results
|
| 370 |
+
except Exception as e:
|
| 371 |
+
logger.warning(f"DuckDuckGo fallback search error for query '{query}': {e}")
|
| 372 |
+
return []
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def aggregate_search(queries, limit=3):
|
| 376 |
+
"""Perform searches sequentially through queries and aggregate results across providers."""
|
| 377 |
+
unsplash_key = os.environ.get("UNSPLASH_ACCESS_KEY")
|
| 378 |
+
pexels_key = os.environ.get("PEXELS_API_KEY")
|
| 379 |
+
|
| 380 |
+
collected_assets = []
|
| 381 |
+
seen_urls = set()
|
| 382 |
+
|
| 383 |
+
for q in queries:
|
| 384 |
+
logger.info(f"Querying search providers for: '{q}'")
|
| 385 |
+
provider_results = []
|
| 386 |
+
|
| 387 |
+
with ThreadPoolExecutor(max_workers=4) as executor:
|
| 388 |
+
futures = []
|
| 389 |
+
|
| 390 |
+
# Official APIs
|
| 391 |
+
if unsplash_key:
|
| 392 |
+
futures.append(executor.submit(search_unsplash, q, unsplash_key, limit))
|
| 393 |
+
if pexels_key:
|
| 394 |
+
futures.append(executor.submit(search_pexels, q, pexels_key, limit))
|
| 395 |
+
|
| 396 |
+
# Scraper fallbacks
|
| 397 |
+
futures.append(executor.submit(scrape_getty, q, limit))
|
| 398 |
+
if HAS_DDG:
|
| 399 |
+
futures.append(executor.submit(search_ddg_fallback, q, limit))
|
| 400 |
+
|
| 401 |
+
for future in as_completed(futures):
|
| 402 |
+
try:
|
| 403 |
+
res = future.result()
|
| 404 |
+
if res:
|
| 405 |
+
provider_results.extend(res)
|
| 406 |
+
except Exception as e:
|
| 407 |
+
logger.warning(f"Search aggregator thread encountered error: {e}")
|
| 408 |
+
|
| 409 |
+
# Deduplicate and check if we met the limit
|
| 410 |
+
for asset in provider_results:
|
| 411 |
+
url = asset["url"]
|
| 412 |
+
if url not in seen_urls:
|
| 413 |
+
seen_urls.add(url)
|
| 414 |
+
collected_assets.append(asset)
|
| 415 |
+
|
| 416 |
+
if len(collected_assets) >= limit:
|
| 417 |
+
logger.info(f"Found sufficient assets ({len(collected_assets)}) using query '{q}'")
|
| 418 |
+
break
|
| 419 |
+
else:
|
| 420 |
+
logger.info(f"Insufficient assets ({len(collected_assets)}/{limit}) for query '{q}'. Attempting fallback...")
|
| 421 |
+
|
| 422 |
+
# Providers Redundancy Fill
|
| 423 |
+
# If we couldn't get enough assets from specific providers or queries, try broad fallback queries with DDG
|
| 424 |
+
if len(collected_assets) < limit and HAS_DDG:
|
| 425 |
+
fallback_query = queries[-1] + " news stock"
|
| 426 |
+
logger.info(f"Pipeline shortfall: Attempting broad fallback crawler query: '{fallback_query}'")
|
| 427 |
+
extra_ddg = search_ddg_fallback(fallback_query, limit=limit - len(collected_assets))
|
| 428 |
+
for asset in extra_ddg:
|
| 429 |
+
if asset["url"] not in seen_urls:
|
| 430 |
+
seen_urls.add(asset["url"])
|
| 431 |
+
collected_assets.append(asset)
|
| 432 |
+
|
| 433 |
+
return collected_assets[:limit]
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
# ==========================================
|
| 437 |
+
# 3. Cache & Downloader
|
| 438 |
+
# ==========================================
|
| 439 |
+
|
| 440 |
+
def download_asset(url, dest_path, retries=3, delay=1):
|
| 441 |
+
"""Download file with exponential backoff and caching support."""
|
| 442 |
+
if dest_path.exists() and dest_path.stat().st_size > 0:
|
| 443 |
+
logger.info(f"Cache hit: {dest_path.name} already exists. Skipping download.")
|
| 444 |
+
return True
|
| 445 |
+
|
| 446 |
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 447 |
+
|
| 448 |
+
for attempt in range(retries):
|
| 449 |
+
try:
|
| 450 |
+
req = urllib.request.Request(
|
| 451 |
+
url,
|
| 452 |
+
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
|
| 453 |
+
)
|
| 454 |
+
with urllib.request.urlopen(req, timeout=15) as response:
|
| 455 |
+
with open(dest_path, 'wb') as f:
|
| 456 |
+
f.write(response.read())
|
| 457 |
+
logger.info(f"Successfully downloaded asset to {dest_path}")
|
| 458 |
+
return True
|
| 459 |
+
except Exception as e:
|
| 460 |
+
logger.warning(f"Download attempt {attempt+1} failed for {url}: {e}")
|
| 461 |
+
if attempt < retries - 1:
|
| 462 |
+
sleep_time = delay * (2 ** attempt)
|
| 463 |
+
logger.info(f"Retrying in {sleep_time}s...")
|
| 464 |
+
time.sleep(sleep_time)
|
| 465 |
+
else:
|
| 466 |
+
logger.error(f"Download permanently failed for URL: {url}")
|
| 467 |
+
return False
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# ==========================================
|
| 471 |
+
# 4. Image Processing & FFmpeg Ken-Burns
|
| 472 |
+
# ==========================================
|
| 473 |
+
|
| 474 |
+
def standardize_image_16_9(img_path, output_path):
|
| 475 |
+
"""Standardize input image aspect ratio to 1920x1080 (16:9)."""
|
| 476 |
+
try:
|
| 477 |
+
with Image.open(img_path) as img:
|
| 478 |
+
# Convert palette/RGBA to RGB to prevent FFmpeg encoding issues
|
| 479 |
+
if img.mode != "RGB":
|
| 480 |
+
img = img.convert("RGB")
|
| 481 |
+
|
| 482 |
+
target_w, target_h = 1920, 1080
|
| 483 |
+
img_w, img_h = img.size
|
| 484 |
+
|
| 485 |
+
target_aspect = target_w / target_h
|
| 486 |
+
img_aspect = img_w / img_h
|
| 487 |
+
|
| 488 |
+
if img_aspect > target_aspect:
|
| 489 |
+
# Image is too wide, crop left/right
|
| 490 |
+
crop_w = int(img_h * target_aspect)
|
| 491 |
+
offset = (img_w - crop_w) // 2
|
| 492 |
+
img = img.crop((offset, 0, offset + crop_w, img_h))
|
| 493 |
+
else:
|
| 494 |
+
# Image is too tall, crop top/bottom
|
| 495 |
+
crop_h = int(img_w / target_aspect)
|
| 496 |
+
offset = (img_h - crop_h) // 2
|
| 497 |
+
img = img.crop((0, offset, img_w, offset + crop_h))
|
| 498 |
+
|
| 499 |
+
img_resized = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
| 500 |
+
img_resized.save(output_path, "JPEG", quality=95)
|
| 501 |
+
return True
|
| 502 |
+
except Exception as e:
|
| 503 |
+
logger.error(f"Failed to standardize image {img_path}: {e}")
|
| 504 |
+
return False
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def get_ffmpeg_path():
|
| 508 |
+
"""Locate ffmpeg binary on system, falling back to imageio_ffmpeg."""
|
| 509 |
+
env_path = os.environ.get("VIDEO_AGENT_FFMPEG")
|
| 510 |
+
if env_path and Path(env_path).exists():
|
| 511 |
+
return env_path
|
| 512 |
+
import shutil
|
| 513 |
+
which_ffmpeg = shutil.which("ffmpeg")
|
| 514 |
+
if which_ffmpeg:
|
| 515 |
+
return which_ffmpeg
|
| 516 |
+
try:
|
| 517 |
+
import imageio_ffmpeg
|
| 518 |
+
return imageio_ffmpeg.get_ffmpeg_exe()
|
| 519 |
+
except Exception:
|
| 520 |
+
pass
|
| 521 |
+
return "ffmpeg"
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def generate_ken_burns_clip(img_path, output_mp4, duration=5.0):
|
| 525 |
+
"""Apply slow-zoom Ken-Burns effect to image via FFmpeg and export MP4."""
|
| 526 |
+
try:
|
| 527 |
+
# Standardize first
|
| 528 |
+
standard_path = img_path.parent / f"std_{img_path.name}"
|
| 529 |
+
if not standardize_image_16_9(img_path, standard_path):
|
| 530 |
+
return False
|
| 531 |
+
|
| 532 |
+
ffmpeg = get_ffmpeg_path()
|
| 533 |
+
frames = int(duration * 30)
|
| 534 |
+
|
| 535 |
+
# Ken-Burns Zoom formula (slow zoom up to 1.08x)
|
| 536 |
+
zoom_formula = "min(zoom+0.0005,1.08)"
|
| 537 |
+
|
| 538 |
+
cmd = [
|
| 539 |
+
ffmpeg, "-y",
|
| 540 |
+
"-loop", "1",
|
| 541 |
+
"-i", str(standard_path),
|
| 542 |
+
"-vf", f"zoompan=z='{zoom_formula}':d={frames}:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':fps=30:s=1920x1080",
|
| 543 |
+
"-c:v", "libx264",
|
| 544 |
+
"-t", str(duration),
|
| 545 |
+
"-pix_fmt", "yuv420p",
|
| 546 |
+
"-movflags", "+faststart",
|
| 547 |
+
str(output_mp4)
|
| 548 |
+
]
|
| 549 |
+
|
| 550 |
+
logger.info(f"Running FFmpeg Ken-Burns render for {output_mp4.name}...")
|
| 551 |
+
res = subprocess.run(cmd, check=True, capture_output=True)
|
| 552 |
+
|
| 553 |
+
# Clean up standardized temp file
|
| 554 |
+
if standard_path.exists():
|
| 555 |
+
standard_path.unlink()
|
| 556 |
+
|
| 557 |
+
return True
|
| 558 |
+
except Exception as e:
|
| 559 |
+
logger.error(f"FFmpeg Ken-Burns encoding failed: {e}")
|
| 560 |
+
return False
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ==========================================
|
| 564 |
+
# 5. Database & Embedding (RAG) Indexer
|
| 565 |
+
# ==========================================
|
| 566 |
+
|
| 567 |
+
def init_db(db_path):
|
| 568 |
+
"""Initialize local SQLite DB for indexing stock assets."""
|
| 569 |
+
conn = sqlite3.connect(str(db_path))
|
| 570 |
+
cursor = conn.cursor()
|
| 571 |
+
cursor.execute("""
|
| 572 |
+
CREATE TABLE IF NOT EXISTS broll_assets (
|
| 573 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 574 |
+
title TEXT,
|
| 575 |
+
query TEXT,
|
| 576 |
+
platform TEXT,
|
| 577 |
+
image_url TEXT UNIQUE,
|
| 578 |
+
local_path TEXT,
|
| 579 |
+
photographer TEXT,
|
| 580 |
+
text_vector TEXT,
|
| 581 |
+
visual_vector TEXT,
|
| 582 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 583 |
+
)
|
| 584 |
+
""")
|
| 585 |
+
conn.commit()
|
| 586 |
+
conn.close()
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def get_gemini_embedding(text, api_key):
|
| 590 |
+
"""Fetch 1536d text embedding via Gemini API."""
|
| 591 |
+
if not api_key:
|
| 592 |
+
return None
|
| 593 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:embedContent?key={api_key}"
|
| 594 |
+
headers = {"Content-Type": "application/json"}
|
| 595 |
+
payload = {
|
| 596 |
+
"model": "models/text-embedding-004",
|
| 597 |
+
"content": {"parts": [{"text": text}]}
|
| 598 |
+
}
|
| 599 |
+
try:
|
| 600 |
+
req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers)
|
| 601 |
+
with urllib.request.urlopen(req, timeout=10) as response:
|
| 602 |
+
res_data = json.loads(response.read().decode('utf-8'))
|
| 603 |
+
return res_data.get("embedding", {}).get("values")
|
| 604 |
+
except Exception as e:
|
| 605 |
+
logger.warning(f"Gemini Text Embedding API failed: {e}")
|
| 606 |
+
return None
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
# Global CLIP Cache to prevent reloading models
|
| 610 |
+
_clip_model = None
|
| 611 |
+
_clip_processor = None
|
| 612 |
+
|
| 613 |
+
def get_clip_text_embedding(text):
|
| 614 |
+
"""Extract 512d CLIP text vector locally."""
|
| 615 |
+
global _clip_model, _clip_processor
|
| 616 |
+
if not HAS_AI:
|
| 617 |
+
return None
|
| 618 |
+
try:
|
| 619 |
+
if _clip_model is None:
|
| 620 |
+
logger.info("Initializing CLIP Model (openai/clip-vit-base-patch32)...")
|
| 621 |
+
_clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 622 |
+
_clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 623 |
+
|
| 624 |
+
inputs = _clip_processor(text=[text], return_tensors="pt", padding=True)
|
| 625 |
+
with torch.no_grad():
|
| 626 |
+
feat = _clip_model.get_text_features(**inputs)
|
| 627 |
+
|
| 628 |
+
# Check if output is a wrapper object instead of a raw Tensor
|
| 629 |
+
if not isinstance(feat, torch.Tensor):
|
| 630 |
+
if hasattr(feat, "text_embeds"):
|
| 631 |
+
feat = feat.text_embeds
|
| 632 |
+
elif hasattr(feat, "pooler_output"):
|
| 633 |
+
feat = feat.pooler_output
|
| 634 |
+
elif isinstance(feat, (list, tuple)):
|
| 635 |
+
feat = feat[0]
|
| 636 |
+
else:
|
| 637 |
+
feat = torch.tensor(feat)
|
| 638 |
+
|
| 639 |
+
# Normalize vector
|
| 640 |
+
feat = feat / feat.norm(dim=-1, keepdim=True)
|
| 641 |
+
return feat.tolist()[0]
|
| 642 |
+
except Exception as e:
|
| 643 |
+
logger.warning(f"CLIP text feature extraction failed: {e}")
|
| 644 |
+
return None
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def cosine_similarity(vec1, vec2):
|
| 648 |
+
"""Calculate cosine similarity between two lists of floats."""
|
| 649 |
+
if not vec1 or not vec2:
|
| 650 |
+
return 0.0
|
| 651 |
+
dot_product = sum(a * b for a, b in zip(vec1, vec2))
|
| 652 |
+
norm_a = sum(a * a for a in vec1) ** 0.5
|
| 653 |
+
norm_b = sum(b * b for b in vec2) ** 0.5
|
| 654 |
+
if norm_a == 0 or norm_b == 0:
|
| 655 |
+
return 0.0
|
| 656 |
+
return dot_product / (norm_a * norm_b)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def get_clip_visual_embedding(img_path):
|
| 660 |
+
"""Extract 512d CLIP visual vector locally."""
|
| 661 |
+
global _clip_model, _clip_processor
|
| 662 |
+
if not HAS_AI:
|
| 663 |
+
return None
|
| 664 |
+
try:
|
| 665 |
+
if _clip_model is None:
|
| 666 |
+
logger.info("Initializing CLIP Model (openai/clip-vit-base-patch32)...")
|
| 667 |
+
_clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 668 |
+
_clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 669 |
+
|
| 670 |
+
img = Image.open(img_path)
|
| 671 |
+
inputs = _clip_processor(images=img, return_tensors="pt")
|
| 672 |
+
with torch.no_grad():
|
| 673 |
+
feat = _clip_model.get_image_features(**inputs)
|
| 674 |
+
|
| 675 |
+
# Check if output is a wrapper object instead of a raw Tensor
|
| 676 |
+
if not isinstance(feat, torch.Tensor):
|
| 677 |
+
if hasattr(feat, "image_embeds"):
|
| 678 |
+
feat = feat.image_embeds
|
| 679 |
+
elif hasattr(feat, "pooler_output"):
|
| 680 |
+
feat = feat.pooler_output
|
| 681 |
+
elif isinstance(feat, (list, tuple)):
|
| 682 |
+
feat = feat[0]
|
| 683 |
+
else:
|
| 684 |
+
# Attempt to convert or extract
|
| 685 |
+
feat = torch.tensor(feat)
|
| 686 |
+
|
| 687 |
+
# Normalize vector
|
| 688 |
+
feat = feat / feat.norm(dim=-1, keepdim=True)
|
| 689 |
+
return feat.tolist()[0]
|
| 690 |
+
except Exception as e:
|
| 691 |
+
logger.warning(f"CLIP feature extraction failed: {e}")
|
| 692 |
+
return None
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def register_asset(db_path, title, query, platform, image_url, local_path, photographer, img_file_path):
|
| 696 |
+
"""Generate vectors (if keys/libraries available) and register asset into DB."""
|
| 697 |
+
gemini_key = os.environ.get("GEMINI_API_KEY")
|
| 698 |
+
|
| 699 |
+
text_vector = None
|
| 700 |
+
if gemini_key:
|
| 701 |
+
text_vector = get_gemini_embedding(title, gemini_key)
|
| 702 |
+
|
| 703 |
+
visual_vector = get_clip_visual_embedding(img_file_path)
|
| 704 |
+
|
| 705 |
+
conn = sqlite3.connect(str(db_path))
|
| 706 |
+
cursor = conn.cursor()
|
| 707 |
+
|
| 708 |
+
t_vec_str = json.dumps(text_vector) if text_vector else None
|
| 709 |
+
v_vec_str = json.dumps(visual_vector) if visual_vector else None
|
| 710 |
+
|
| 711 |
+
try:
|
| 712 |
+
cursor.execute("""
|
| 713 |
+
INSERT INTO broll_assets (title, query, platform, image_url, local_path, photographer, text_vector, visual_vector)
|
| 714 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
| 715 |
+
ON CONFLICT(image_url) DO UPDATE SET
|
| 716 |
+
title=excluded.title,
|
| 717 |
+
query=excluded.query,
|
| 718 |
+
platform=excluded.platform,
|
| 719 |
+
local_path=excluded.local_path,
|
| 720 |
+
photographer=excluded.photographer,
|
| 721 |
+
text_vector=coalesce(excluded.text_vector, broll_assets.text_vector),
|
| 722 |
+
visual_vector=coalesce(excluded.visual_vector, broll_assets.visual_vector)
|
| 723 |
+
""", (title, query, platform, image_url, str(local_path), photographer, t_vec_str, v_vec_str))
|
| 724 |
+
conn.commit()
|
| 725 |
+
logger.info(f"Asset recorded in database: {title}")
|
| 726 |
+
except Exception as e:
|
| 727 |
+
logger.error(f"Failed to record asset in DB: {e}")
|
| 728 |
+
finally:
|
| 729 |
+
conn.close()
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
# ==========================================
|
| 733 |
+
# 6. Main Orchestrator Flow
|
| 734 |
+
# ==========================================
|
| 735 |
+
|
| 736 |
+
def parse_article_metadata(article_dir):
|
| 737 |
+
"""Extract title and category from article directory."""
|
| 738 |
+
article_path = Path(article_dir)
|
| 739 |
+
category = article_path.parent.name
|
| 740 |
+
|
| 741 |
+
# Try finding main markdown file
|
| 742 |
+
md_files = [f for f in article_path.glob("*.md") if not f.name.startswith("script_")]
|
| 743 |
+
if md_files:
|
| 744 |
+
with open(md_files[0], "r", encoding="utf-8") as f:
|
| 745 |
+
for line in f:
|
| 746 |
+
# Match title
|
| 747 |
+
if line.startswith("# "):
|
| 748 |
+
title = line.replace("# ", "").strip()
|
| 749 |
+
return title, category
|
| 750 |
+
|
| 751 |
+
# Fallback to folder name
|
| 752 |
+
title = article_path.name.replace("_", " ").replace("-", " ")
|
| 753 |
+
return title, category
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def main():
|
| 757 |
+
parser = argparse.ArgumentParser(description="Automated B-roll Collection and Integration Agent")
|
| 758 |
+
parser.add_argument("--article-dir", type=str, help="Path to article directory to scan and save B-rolls into")
|
| 759 |
+
parser.add_argument("--query", type=str, help="Override title parsing and search for this specific query")
|
| 760 |
+
parser.add_argument("--category", type=str, help="Override category parsing")
|
| 761 |
+
parser.add_argument("--limit", type=int, default=3, help="Max B-roll clips to generate")
|
| 762 |
+
articles_dir = Path(__file__).parent
|
| 763 |
+
default_db = str(articles_dir / "broll_assets.db")
|
| 764 |
+
default_cache = str(articles_dir / "temp" / "broll_cache")
|
| 765 |
+
parser.add_argument("--db-path", type=str, default=default_db, help="Path to SQLite DB")
|
| 766 |
+
parser.add_argument("--cache-dir", type=str, default=default_cache, help="Cache directory")
|
| 767 |
+
args = parser.parse_args()
|
| 768 |
+
|
| 769 |
+
init_db(args.db_path)
|
| 770 |
+
cache_path = Path(args.cache_dir)
|
| 771 |
+
cache_path.mkdir(parents=True, exist_ok=True)
|
| 772 |
+
|
| 773 |
+
title = args.query
|
| 774 |
+
category = args.category
|
| 775 |
+
|
| 776 |
+
# Determine paths and prompts
|
| 777 |
+
if args.article_dir:
|
| 778 |
+
article_dir_path = Path(args.article_dir)
|
| 779 |
+
if not article_dir_path.exists():
|
| 780 |
+
logger.error(f"Article directory does not exist: {args.article_dir}")
|
| 781 |
+
sys.exit(1)
|
| 782 |
+
|
| 783 |
+
parsed_title, parsed_cat = parse_article_metadata(args.article_dir)
|
| 784 |
+
if not title:
|
| 785 |
+
title = parsed_title
|
| 786 |
+
if not category:
|
| 787 |
+
category = parsed_cat
|
| 788 |
+
|
| 789 |
+
# Target B-roll output folders are inside the article's directory under "Broll"
|
| 790 |
+
broll_dir = article_dir_path / "Broll"
|
| 791 |
+
image_output_dir = broll_dir
|
| 792 |
+
video_output_dir = broll_dir
|
| 793 |
+
image_output_dir.mkdir(parents=True, exist_ok=True)
|
| 794 |
+
else:
|
| 795 |
+
if not title:
|
| 796 |
+
logger.error("Must specify either --article-dir or --query")
|
| 797 |
+
sys.exit(1)
|
| 798 |
+
image_output_dir = Path(r"C:\ComfyUI\Broll\images")
|
| 799 |
+
video_output_dir = Path(r"C:\ComfyUI\Broll\videos")
|
| 800 |
+
image_output_dir.mkdir(parents=True, exist_ok=True)
|
| 801 |
+
video_output_dir.mkdir(parents=True, exist_ok=True)
|
| 802 |
+
|
| 803 |
+
logger.info(f"Targeting B-roll collection for: Title='{title}', Category='{category}'")
|
| 804 |
+
|
| 805 |
+
# 1. Fallback Query Pipeline
|
| 806 |
+
queries = generate_fallback_queries(title, category)
|
| 807 |
+
|
| 808 |
+
# 2. Aggregated Multiprovider Asset Search (Retrieve 3x candidates to filter relevance)
|
| 809 |
+
candidate_limit = args.limit * 3 if HAS_AI else args.limit
|
| 810 |
+
assets = aggregate_search(queries, limit=candidate_limit)
|
| 811 |
+
if not assets:
|
| 812 |
+
logger.error("No B-roll assets found from Unsplash, Pexels, Getty or DuckDuckGo.")
|
| 813 |
+
failed_marker = video_output_dir / "failed_attempts.txt"
|
| 814 |
+
try:
|
| 815 |
+
with open(failed_marker, "w", encoding="utf-8") as f:
|
| 816 |
+
f.write(f"Failed to generate B-roll clips (no assets found). Timestamp: {time.time()}\n")
|
| 817 |
+
except Exception as e:
|
| 818 |
+
logger.warning(f"Failed to write failed marker: {e}")
|
| 819 |
+
sys.exit(1)
|
| 820 |
+
|
| 821 |
+
logger.info(f"Retrieved {len(assets)} B-roll candidates. Processing relevance matching...")
|
| 822 |
+
|
| 823 |
+
# 3. CLIP Relevance filtering if enabled
|
| 824 |
+
filtered_assets = []
|
| 825 |
+
|
| 826 |
+
if HAS_AI:
|
| 827 |
+
text_emb = get_clip_text_embedding(title)
|
| 828 |
+
if text_emb:
|
| 829 |
+
logger.info(f"CLIP Text Vector extracted for: '{title}'. Evaluating images...")
|
| 830 |
+
scored_candidates = []
|
| 831 |
+
|
| 832 |
+
for i, asset in enumerate(assets):
|
| 833 |
+
# Temporary download for CLIP evaluation
|
| 834 |
+
url_hash = hashlib.md5(asset["url"].encode("utf-8")).hexdigest()[:10]
|
| 835 |
+
sanitized_title = clean_query(asset["title"])[:30].replace(" ", "_")
|
| 836 |
+
raw_image_path = image_output_dir / f"tmp_{url_hash}_{sanitized_title}.jpg"
|
| 837 |
+
|
| 838 |
+
if download_asset(asset["url"], raw_image_path):
|
| 839 |
+
from quality_gate_broll import validate_image_asset, remove_watermark_with_lama
|
| 840 |
+
is_ok, reason = validate_image_asset(raw_image_path)
|
| 841 |
+
if not is_ok:
|
| 842 |
+
if "Watermark" in reason:
|
| 843 |
+
logger.info(f"Watermark detected in candidate '{asset['title']}'. Attempting automatic removal...")
|
| 844 |
+
removed, remove_reason = remove_watermark_with_lama(raw_image_path)
|
| 845 |
+
if removed:
|
| 846 |
+
is_ok = True
|
| 847 |
+
else:
|
| 848 |
+
logger.warning(f"Watermark removal failed: {remove_reason}")
|
| 849 |
+
|
| 850 |
+
if not is_ok:
|
| 851 |
+
logger.warning(f"Discarding B-roll candidate '{asset['title']}' due to Quality Gate: {reason}")
|
| 852 |
+
if raw_image_path.exists():
|
| 853 |
+
raw_image_path.unlink()
|
| 854 |
+
continue
|
| 855 |
+
|
| 856 |
+
img_emb = get_clip_visual_embedding(raw_image_path)
|
| 857 |
+
score = cosine_similarity(text_emb, img_emb)
|
| 858 |
+
logger.info(f"Candidate [{i+1}/{len(assets)}]: '{asset['title']}' | CLIP similarity score: {score:.3f}")
|
| 859 |
+
|
| 860 |
+
# 0.17 threshold for mismatch protection
|
| 861 |
+
if score >= 0.17:
|
| 862 |
+
# Rename to permanent cache file path
|
| 863 |
+
perm_image_path = image_output_dir / f"{url_hash}_{sanitized_title}.jpg"
|
| 864 |
+
is_new_file = False
|
| 865 |
+
if raw_image_path.exists():
|
| 866 |
+
if perm_image_path.exists():
|
| 867 |
+
raw_image_path.unlink()
|
| 868 |
+
else:
|
| 869 |
+
try:
|
| 870 |
+
raw_image_path.rename(perm_image_path)
|
| 871 |
+
is_new_file = True
|
| 872 |
+
except FileExistsError:
|
| 873 |
+
perm_image_path.unlink(missing_ok=True)
|
| 874 |
+
raw_image_path.rename(perm_image_path)
|
| 875 |
+
is_new_file = True
|
| 876 |
+
asset["local_image_path"] = perm_image_path
|
| 877 |
+
asset["is_new_file"] = is_new_file
|
| 878 |
+
asset["score"] = score
|
| 879 |
+
scored_candidates.append(asset)
|
| 880 |
+
else:
|
| 881 |
+
logger.warning(f"Discarding mismatch B-roll asset '{asset['title']}' due to low relevance score: {score:.3f} < 0.17")
|
| 882 |
+
if raw_image_path.exists():
|
| 883 |
+
raw_image_path.unlink()
|
| 884 |
+
else:
|
| 885 |
+
logger.warning(f"Could not download candidate for evaluation: {asset['title']}")
|
| 886 |
+
|
| 887 |
+
# Sort candidates by relevance score descending
|
| 888 |
+
scored_candidates.sort(key=lambda x: x["score"], reverse=True)
|
| 889 |
+
filtered_assets = scored_candidates[:args.limit]
|
| 890 |
+
|
| 891 |
+
# Delete remaining temporary/unused downloaded assets (only if newly created in this run)
|
| 892 |
+
for extra in scored_candidates[args.limit:]:
|
| 893 |
+
if extra.get("is_new_file") and "local_image_path" in extra and extra["local_image_path"].exists():
|
| 894 |
+
extra["local_image_path"].unlink()
|
| 895 |
+
else:
|
| 896 |
+
filtered_assets = assets[:args.limit]
|
| 897 |
+
else:
|
| 898 |
+
filtered_assets = assets[:args.limit]
|
| 899 |
+
|
| 900 |
+
logger.info(f"Adopted {len(filtered_assets)} highly relevant B-roll assets. Converting to Ken-Burns clips...")
|
| 901 |
+
|
| 902 |
+
# 4. Download, Standardize, Convert and Index
|
| 903 |
+
clips = []
|
| 904 |
+
for i, asset in enumerate(filtered_assets):
|
| 905 |
+
logger.info(f"Rendering B-roll asset [{i+1}/{len(filtered_assets)}]: {asset['title']} ({asset['platform']})")
|
| 906 |
+
|
| 907 |
+
url_hash = hashlib.md5(asset["url"].encode("utf-8")).hexdigest()[:10]
|
| 908 |
+
sanitized_title = clean_query(asset["title"])[:30].replace(" ", "_")
|
| 909 |
+
|
| 910 |
+
raw_image_path = asset.get("local_image_path")
|
| 911 |
+
if not raw_image_path:
|
| 912 |
+
raw_image_path = image_output_dir / f"{url_hash}_{sanitized_title}.jpg"
|
| 913 |
+
|
| 914 |
+
clip_path = video_output_dir / f"{url_hash}_{sanitized_title}.mp4"
|
| 915 |
+
|
| 916 |
+
# Check if B-roll already generated to skip redundant rendering
|
| 917 |
+
if clip_path.exists() and clip_path.stat().st_size > 0:
|
| 918 |
+
logger.info(f"B-roll already exists: {clip_path.name}. Skipping generation.")
|
| 919 |
+
clips.append(str(clip_path))
|
| 920 |
+
register_asset(
|
| 921 |
+
args.db_path,
|
| 922 |
+
title=asset["title"],
|
| 923 |
+
query=title,
|
| 924 |
+
platform=asset["platform"],
|
| 925 |
+
image_url=asset["url"],
|
| 926 |
+
local_path=clip_path,
|
| 927 |
+
photographer=asset["photographer"],
|
| 928 |
+
img_file_path=raw_image_path
|
| 929 |
+
)
|
| 930 |
+
continue
|
| 931 |
+
|
| 932 |
+
# Download (if not already downloaded during evaluation)
|
| 933 |
+
if not raw_image_path.exists():
|
| 934 |
+
if not download_asset(asset["url"], raw_image_path):
|
| 935 |
+
continue
|
| 936 |
+
|
| 937 |
+
from quality_gate_broll import validate_image_asset, remove_watermark_with_lama
|
| 938 |
+
is_ok, reason = validate_image_asset(raw_image_path)
|
| 939 |
+
if not is_ok:
|
| 940 |
+
if "Watermark" in reason:
|
| 941 |
+
logger.info(f"Watermark detected in asset '{asset['title']}' before render. Attempting automatic removal...")
|
| 942 |
+
removed, remove_reason = remove_watermark_with_lama(raw_image_path)
|
| 943 |
+
if removed:
|
| 944 |
+
is_ok = True
|
| 945 |
+
else:
|
| 946 |
+
logger.warning(f"Watermark removal failed: {remove_reason}")
|
| 947 |
+
|
| 948 |
+
if not is_ok:
|
| 949 |
+
logger.warning(f"Skipping B-roll asset '{asset['title']}' due to Quality Gate: {reason}")
|
| 950 |
+
if raw_image_path.exists():
|
| 951 |
+
raw_image_path.unlink()
|
| 952 |
+
continue
|
| 953 |
+
|
| 954 |
+
# Convert to zoom video
|
| 955 |
+
if generate_ken_burns_clip(raw_image_path, clip_path):
|
| 956 |
+
clips.append(str(clip_path))
|
| 957 |
+
register_asset(
|
| 958 |
+
args.db_path,
|
| 959 |
+
title=asset["title"],
|
| 960 |
+
query=title,
|
| 961 |
+
platform=asset["platform"],
|
| 962 |
+
image_url=asset["url"],
|
| 963 |
+
local_path=clip_path,
|
| 964 |
+
photographer=asset["photographer"],
|
| 965 |
+
img_file_path=raw_image_path
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
failed_marker = video_output_dir / "failed_attempts.txt"
|
| 969 |
+
if len(clips) == 0:
|
| 970 |
+
logger.error("No B-roll clips were successfully generated (all candidates discarded or failed).")
|
| 971 |
+
try:
|
| 972 |
+
with open(failed_marker, "w", encoding="utf-8") as f:
|
| 973 |
+
f.write(f"Failed to generate B-roll clips. Timestamp: {time.time()}\n")
|
| 974 |
+
except Exception as e:
|
| 975 |
+
logger.warning(f"Failed to write failed marker: {e}")
|
| 976 |
+
sys.exit(1)
|
| 977 |
+
else:
|
| 978 |
+
if failed_marker.exists():
|
| 979 |
+
try:
|
| 980 |
+
failed_marker.unlink()
|
| 981 |
+
except Exception:
|
| 982 |
+
pass
|
| 983 |
+
|
| 984 |
+
logger.info(f"B-roll Collection Agent completed. Generated {len(clips)} Ken-Burns clips: {clips}")
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
if __name__ == "__main__":
|
| 988 |
+
main()
|
collect_media_parallel.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import glob
|
| 4 |
+
import urllib.request
|
| 5 |
+
import urllib.error
|
| 6 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 7 |
+
from duckduckgo_search import DDGS
|
| 8 |
+
import logging
|
| 9 |
+
import argparse
|
| 10 |
+
|
| 11 |
+
# Set up logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
ROOT_DIR = r"C:\ComfyUI\Articles"
|
| 16 |
+
|
| 17 |
+
def download_media(url, dest_path):
|
| 18 |
+
try:
|
| 19 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
| 20 |
+
with urllib.request.urlopen(req, timeout=10) as response:
|
| 21 |
+
with open(dest_path, 'wb') as f:
|
| 22 |
+
f.write(response.read())
|
| 23 |
+
return True
|
| 24 |
+
except Exception as e:
|
| 25 |
+
logger.warning(f"Failed to download {url}: {e}")
|
| 26 |
+
return False
|
| 27 |
+
|
| 28 |
+
def search_and_download_images(query, dest_folder, max_results=3):
|
| 29 |
+
try:
|
| 30 |
+
ddgs = DDGS()
|
| 31 |
+
results = list(ddgs.images(query, max_results=max_results))
|
| 32 |
+
downloaded = 0
|
| 33 |
+
for i, res in enumerate(results):
|
| 34 |
+
img_url = res.get("image")
|
| 35 |
+
if img_url:
|
| 36 |
+
ext = img_url.split('.')[-1].split('?')[0]
|
| 37 |
+
if ext.lower() not in ['jpg', 'jpeg', 'png', 'webp']:
|
| 38 |
+
ext = "jpg"
|
| 39 |
+
dest_path = os.path.join(dest_folder, f"image_{i}.{ext}")
|
| 40 |
+
if download_media(img_url, dest_path):
|
| 41 |
+
downloaded += 1
|
| 42 |
+
return downloaded
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.error(f"Image search failed for query '{query}': {e}")
|
| 45 |
+
return 0
|
| 46 |
+
|
| 47 |
+
def search_and_download_videos(query, dest_folder, max_results=2):
|
| 48 |
+
try:
|
| 49 |
+
ddgs = DDGS()
|
| 50 |
+
results = list(ddgs.videos(query, max_results=max_results))
|
| 51 |
+
downloaded = 0
|
| 52 |
+
# DuckDuckGo video search often returns YouTube/external links, not direct MP4 files.
|
| 53 |
+
# We'll save the links and metadata as a JSON file or try to find a direct media url if present.
|
| 54 |
+
# For a full system, you might want to integrate yt-dlp here.
|
| 55 |
+
# For now, we will just save the video metadata if we can't get a direct link.
|
| 56 |
+
for i, res in enumerate(results):
|
| 57 |
+
vid_url = res.get("content")
|
| 58 |
+
if vid_url and (vid_url.endswith('.mp4') or vid_url.endswith('.webm')):
|
| 59 |
+
dest_path = os.path.join(dest_folder, f"video_{i}.mp4")
|
| 60 |
+
if download_media(vid_url, dest_path):
|
| 61 |
+
downloaded += 1
|
| 62 |
+
else:
|
| 63 |
+
# Save metadata as a fallback reference
|
| 64 |
+
meta_path = os.path.join(dest_folder, f"video_ref_{i}.txt")
|
| 65 |
+
with open(meta_path, "w", encoding="utf-8") as f:
|
| 66 |
+
f.write(f"Title: {res.get('title')}\nURL: {res.get('content')}\nSource: {res.get('source')}\n")
|
| 67 |
+
downloaded += 1
|
| 68 |
+
return downloaded
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Video search failed for query '{query}': {e}")
|
| 71 |
+
return 0
|
| 72 |
+
|
| 73 |
+
def process_article(article_folder, locale="en-US"):
|
| 74 |
+
media_folder = os.path.join(article_folder, "media")
|
| 75 |
+
|
| 76 |
+
# Skip if media already collected
|
| 77 |
+
if os.path.exists(media_folder) and len(os.listdir(media_folder)) > 0:
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
# The title can be derived from the folder name
|
| 81 |
+
folder_name = os.path.basename(article_folder)
|
| 82 |
+
title = folder_name.replace('_', ' ')
|
| 83 |
+
|
| 84 |
+
if not title:
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
logger.info(f"Collecting media for: {title}")
|
| 88 |
+
|
| 89 |
+
os.makedirs(media_folder, exist_ok=True)
|
| 90 |
+
|
| 91 |
+
# We will use ThreadPoolExecutor to run image and video search concurrently
|
| 92 |
+
with ThreadPoolExecutor(max_workers=2) as executor:
|
| 93 |
+
future_img = executor.submit(search_and_download_images, title, media_folder)
|
| 94 |
+
future_vid = executor.submit(search_and_download_videos, title + " news", media_folder)
|
| 95 |
+
|
| 96 |
+
imgs_done = future_img.result()
|
| 97 |
+
vids_done = future_vid.result()
|
| 98 |
+
|
| 99 |
+
logger.info(f"Completed {article_folder}: {imgs_done} images, {vids_done} videos.")
|
| 100 |
+
|
| 101 |
+
if imgs_done == 0 and vids_done == 0:
|
| 102 |
+
try:
|
| 103 |
+
with open(os.path.join(media_folder, "no_media.txt"), "w", encoding="utf-8") as f:
|
| 104 |
+
f.write("No media found or rate limited.")
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"Failed to write no_media.txt: {e}")
|
| 107 |
+
|
| 108 |
+
def main():
|
| 109 |
+
parser = argparse.ArgumentParser()
|
| 110 |
+
parser.add_argument('--locale', type=str, default='en-US')
|
| 111 |
+
parser.add_argument('--test-run', action='store_true')
|
| 112 |
+
parser.add_argument('--limit', type=int, default=10, help="Max number of articles to collect media for in this run.")
|
| 113 |
+
args = parser.parse_args()
|
| 114 |
+
|
| 115 |
+
search_path = os.path.join(ROOT_DIR, args.locale, "*", "*")
|
| 116 |
+
article_folders = glob.glob(search_path)
|
| 117 |
+
|
| 118 |
+
# Filter folders that have script_long.md
|
| 119 |
+
valid_folders = [f for f in article_folders if os.path.isdir(f) and os.path.exists(os.path.join(f, "script_long.md"))]
|
| 120 |
+
|
| 121 |
+
# Filter to only folders that need media
|
| 122 |
+
folders_needing_media = []
|
| 123 |
+
for f in valid_folders:
|
| 124 |
+
media_folder = os.path.join(f, "media")
|
| 125 |
+
if not os.path.exists(media_folder) or len(os.listdir(media_folder)) == 0:
|
| 126 |
+
folders_needing_media.append(f)
|
| 127 |
+
|
| 128 |
+
if args.test_run:
|
| 129 |
+
logger.info("Running in test mode. Only processing 1 article.")
|
| 130 |
+
folders_needing_media = folders_needing_media[:1]
|
| 131 |
+
elif args.limit > 0:
|
| 132 |
+
folders_needing_media = folders_needing_media[:args.limit]
|
| 133 |
+
|
| 134 |
+
logger.info(f"Found {len(folders_needing_media)} articles to process for media collection (limit was {args.limit}).")
|
| 135 |
+
|
| 136 |
+
if not folders_needing_media:
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
with ThreadPoolExecutor(max_workers=4) as executor:
|
| 140 |
+
futures = {executor.submit(process_article, folder, args.locale): folder for folder in folders_needing_media}
|
| 141 |
+
for future in as_completed(futures):
|
| 142 |
+
try:
|
| 143 |
+
future.result()
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"Error processing article: {e}")
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
main()
|
collect_news_service.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
|
copy_completed_videos.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import re
|
| 4 |
+
import shutil
|
| 5 |
+
import glob
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 9 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 10 |
+
|
| 11 |
+
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
ROOT_DIR = SCRIPT_DIR if os.path.exists(os.path.join(SCRIPT_DIR, "en-US")) else r"C:\ComfyUI\Articles"
|
| 13 |
+
COMFY_OUTPUT_DIR = r"C:\ComfyUI\output"
|
| 14 |
+
|
| 15 |
+
def extract_main_word(title):
|
| 16 |
+
# Replace underscores and commas with spaces to handle words correctly
|
| 17 |
+
title = title.replace('_', ' ').replace(',', ' ')
|
| 18 |
+
|
| 19 |
+
is_ja = any(ord(char) > 0x3000 for char in title)
|
| 20 |
+
|
| 21 |
+
# Clean title from source marks
|
| 22 |
+
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)
|
| 23 |
+
cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE)
|
| 24 |
+
|
| 25 |
+
blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"]
|
| 26 |
+
|
| 27 |
+
def is_valid(word):
|
| 28 |
+
if not word:
|
| 29 |
+
return False
|
| 30 |
+
return word.strip().lower() not in blacklisted
|
| 31 |
+
|
| 32 |
+
# 1. Look for quotes like 「...」
|
| 33 |
+
quotes_ja = re.findall(r'「([^」]+)」', cleaned)
|
| 34 |
+
for q in quotes_ja:
|
| 35 |
+
if is_valid(q):
|
| 36 |
+
return q
|
| 37 |
+
|
| 38 |
+
quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned)
|
| 39 |
+
for q in quotes_en:
|
| 40 |
+
if len(q) < 25 and is_valid(q):
|
| 41 |
+
return q
|
| 42 |
+
|
| 43 |
+
# 2. Known key entities list
|
| 44 |
+
known_keywords = [
|
| 45 |
+
"OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk",
|
| 46 |
+
"大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI"
|
| 47 |
+
]
|
| 48 |
+
for kw in known_keywords:
|
| 49 |
+
if kw.lower() in cleaned.lower() and is_valid(kw):
|
| 50 |
+
m = re.search(re.escape(kw), cleaned, re.IGNORECASE)
|
| 51 |
+
if m:
|
| 52 |
+
return m.group(0)
|
| 53 |
+
|
| 54 |
+
if is_ja:
|
| 55 |
+
# Katakana sequences
|
| 56 |
+
katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned)
|
| 57 |
+
for k in katakana:
|
| 58 |
+
if is_valid(k):
|
| 59 |
+
return k
|
| 60 |
+
# Kanji sequences
|
| 61 |
+
kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned)
|
| 62 |
+
for k in kanji:
|
| 63 |
+
if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k):
|
| 64 |
+
return k
|
| 65 |
+
if kanji:
|
| 66 |
+
for k in kanji:
|
| 67 |
+
if is_valid(k):
|
| 68 |
+
return k
|
| 69 |
+
# Alphabetic words
|
| 70 |
+
alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned)
|
| 71 |
+
for a in alpha:
|
| 72 |
+
if is_valid(a):
|
| 73 |
+
return a
|
| 74 |
+
else:
|
| 75 |
+
words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned)
|
| 76 |
+
if words:
|
| 77 |
+
for w in words:
|
| 78 |
+
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):
|
| 79 |
+
return w
|
| 80 |
+
for w in words:
|
| 81 |
+
if is_valid(w):
|
| 82 |
+
return w
|
| 83 |
+
|
| 84 |
+
first_token = re.search(r'\w+', cleaned)
|
| 85 |
+
if first_token and is_valid(first_token.group(0)):
|
| 86 |
+
return first_token.group(0)
|
| 87 |
+
|
| 88 |
+
return ""
|
| 89 |
+
|
| 90 |
+
def safe_filename(name, max_len=40):
|
| 91 |
+
main_word = extract_main_word(name).strip()
|
| 92 |
+
|
| 93 |
+
cleaned = name.replace('_', ' ').replace(',', ' ')
|
| 94 |
+
cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned)
|
| 95 |
+
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 96 |
+
|
| 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 |
+
|
| 105 |
+
final_title = re.sub(r'\s+', ' ', final_title).strip()
|
| 106 |
+
|
| 107 |
+
if len(final_title) > max_len:
|
| 108 |
+
final_title = final_title[:max_len].strip()
|
| 109 |
+
final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title)
|
| 110 |
+
|
| 111 |
+
return final_title
|
| 112 |
+
|
| 113 |
+
def generate_youtube_metadata(article_path, dest_dir, safe_name):
|
| 114 |
+
# Try to find the original article title from the main markdown file
|
| 115 |
+
main_title = safe_name
|
| 116 |
+
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"]
|
| 117 |
+
article_summary = ""
|
| 118 |
+
source_info = ""
|
| 119 |
+
|
| 120 |
+
if main_md_files:
|
| 121 |
+
main_md_path = os.path.join(article_path, main_md_files[0])
|
| 122 |
+
try:
|
| 123 |
+
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
|
| 124 |
+
first_line = f.readline().strip()
|
| 125 |
+
if first_line.startswith("#"):
|
| 126 |
+
main_title = first_line.lstrip("#").strip()
|
| 127 |
+
else:
|
| 128 |
+
main_title = os.path.splitext(main_md_files[0])[0]
|
| 129 |
+
|
| 130 |
+
with open(main_md_path, "r", encoding="utf-8", errors="replace") as f:
|
| 131 |
+
content = f.read().strip()
|
| 132 |
+
paragraphs = [p.strip() for p in content.split('\n') if p.strip()]
|
| 133 |
+
non_headers = [p for p in paragraphs if not p.startswith('#')]
|
| 134 |
+
if non_headers:
|
| 135 |
+
article_summary = non_headers[0]
|
| 136 |
+
|
| 137 |
+
for p in paragraphs:
|
| 138 |
+
if p.startswith("**Source:**"):
|
| 139 |
+
source_text = p.replace("**Source:**", "").strip()
|
| 140 |
+
match = re.search(r'\[([^\]]+)\]\(([^)]+)\)', source_text)
|
| 141 |
+
if match:
|
| 142 |
+
source_info = f"{match.group(1)} ({match.group(2)})"
|
| 143 |
+
else:
|
| 144 |
+
source_info = source_text
|
| 145 |
+
except Exception as e:
|
| 146 |
+
print(f" Warning: Could not parse markdown for metadata: {e}")
|
| 147 |
+
|
| 148 |
+
# Title limit is 100 characters, so we must truncate main_title if it's too long
|
| 149 |
+
if len(main_title) > 100:
|
| 150 |
+
main_title = main_title[:97].strip() + "..."
|
| 151 |
+
|
| 152 |
+
short_script = ""
|
| 153 |
+
short_path = os.path.join(article_path, "script_short_clean.txt")
|
| 154 |
+
if os.path.exists(short_path):
|
| 155 |
+
try:
|
| 156 |
+
with open(short_path, "r", encoding="utf-8") as f:
|
| 157 |
+
short_script = f.read().strip()
|
| 158 |
+
except Exception:
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
long_script = ""
|
| 162 |
+
long_path = os.path.join(article_path, "script_long_clean.txt")
|
| 163 |
+
if os.path.exists(long_path):
|
| 164 |
+
try:
|
| 165 |
+
with open(long_path, "r", encoding="utf-8") as f:
|
| 166 |
+
long_script = f.read().strip()
|
| 167 |
+
except Exception:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
metadata_lines = []
|
| 171 |
+
metadata_lines.append("=== YOUTUBE UPLOAD METADATA ===")
|
| 172 |
+
metadata_lines.append(f"SUGGESTED TITLE: {main_title}")
|
| 173 |
+
metadata_lines.append("===============================")
|
| 174 |
+
metadata_lines.append("")
|
| 175 |
+
metadata_lines.append("=== DESCRIPTION ===")
|
| 176 |
+
|
| 177 |
+
if short_script:
|
| 178 |
+
metadata_lines.append(short_script)
|
| 179 |
+
elif article_summary:
|
| 180 |
+
metadata_lines.append(article_summary)
|
| 181 |
+
else:
|
| 182 |
+
metadata_lines.append(f"In this video: Latest news and updates about {main_title}.")
|
| 183 |
+
|
| 184 |
+
if source_info:
|
| 185 |
+
metadata_lines.append(f"\nSource: {source_info}")
|
| 186 |
+
else:
|
| 187 |
+
metadata_lines.append("\nSource: The Android Times / Provided News Sources")
|
| 188 |
+
|
| 189 |
+
metadata_lines.append("")
|
| 190 |
+
metadata_lines.append("--- Video Transcript ---")
|
| 191 |
+
if long_script:
|
| 192 |
+
metadata_lines.append(long_script)
|
| 193 |
+
else:
|
| 194 |
+
metadata_lines.append("(Transcript not available)")
|
| 195 |
+
|
| 196 |
+
metadata_lines.append("")
|
| 197 |
+
metadata_lines.append("--- About The Android Times ---")
|
| 198 |
+
metadata_lines.append("Your daily source for Android, AI, and technology news updates.")
|
| 199 |
+
metadata_lines.append("Subscribe to stay updated with the latest in tech!")
|
| 200 |
+
metadata_lines.append("")
|
| 201 |
+
metadata_lines.append("#Android #Tech #News")
|
| 202 |
+
metadata_lines.append("")
|
| 203 |
+
|
| 204 |
+
metadata_path = os.path.join(dest_dir, "youtube_metadata.txt")
|
| 205 |
+
try:
|
| 206 |
+
with open(metadata_path, "w", encoding="utf-8") as f:
|
| 207 |
+
f.write("\n".join(metadata_lines))
|
| 208 |
+
print(f" Generated YouTube metadata: {metadata_path}")
|
| 209 |
+
except Exception as e:
|
| 210 |
+
print(f" Error generating YouTube metadata file: {e}")
|
| 211 |
+
|
| 212 |
+
def package_youtube_assets(article_path, src_video_path, safe_name):
|
| 213 |
+
try:
|
| 214 |
+
youtube_dest_dir = os.path.join(r"C:\Users\eggof\Desktop\Android Times\Youtube", safe_name)
|
| 215 |
+
os.makedirs(youtube_dest_dir, exist_ok=True)
|
| 216 |
+
|
| 217 |
+
# 1. Copy article folder contents to Youtube\<safe_name>
|
| 218 |
+
for item in os.listdir(article_path):
|
| 219 |
+
s_item = os.path.join(article_path, item)
|
| 220 |
+
d_item = os.path.join(youtube_dest_dir, item)
|
| 221 |
+
if os.path.isdir(s_item):
|
| 222 |
+
if item not in ["__pycache__", "images", "sources"]:
|
| 223 |
+
shutil.copytree(s_item, d_item, dirs_exist_ok=True)
|
| 224 |
+
else:
|
| 225 |
+
shutil.copy2(s_item, d_item)
|
| 226 |
+
|
| 227 |
+
# Copy the video .mp4 there too
|
| 228 |
+
youtube_video_dest = os.path.join(youtube_dest_dir, f"{safe_name}.mp4")
|
| 229 |
+
shutil.copy2(src_video_path, youtube_video_dest)
|
| 230 |
+
print(f" Successfully copied video to Youtube folder: {youtube_video_dest}")
|
| 231 |
+
|
| 232 |
+
# 2. Generate YouTube Metadata
|
| 233 |
+
generate_youtube_metadata(article_path, youtube_dest_dir, safe_name)
|
| 234 |
+
|
| 235 |
+
except Exception as e:
|
| 236 |
+
print(f" Error packaging YouTube assets: {e}")
|
| 237 |
+
|
| 238 |
+
def main():
|
| 239 |
+
print(f"=== checking for completed videos: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
|
| 240 |
+
|
| 241 |
+
locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
|
| 242 |
+
copied_count = 0
|
| 243 |
+
|
| 244 |
+
for locale in locales:
|
| 245 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 246 |
+
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
|
| 247 |
+
continue
|
| 248 |
+
|
| 249 |
+
categories = os.listdir(locale_path)
|
| 250 |
+
for category in categories:
|
| 251 |
+
if category == "__pycache__":
|
| 252 |
+
continue
|
| 253 |
+
cat_path = os.path.join(locale_path, category)
|
| 254 |
+
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
|
| 255 |
+
continue
|
| 256 |
+
|
| 257 |
+
articles = os.listdir(cat_path)
|
| 258 |
+
for article in articles:
|
| 259 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 260 |
+
continue
|
| 261 |
+
article_path = os.path.join(cat_path, article)
|
| 262 |
+
if not os.path.isdir(article_path):
|
| 263 |
+
continue
|
| 264 |
+
|
| 265 |
+
# Check status
|
| 266 |
+
eval_path = os.path.join(article_path, "evaluation_result.json")
|
| 267 |
+
if not os.path.exists(eval_path):
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
try:
|
| 271 |
+
with open(eval_path, 'r', encoding='utf-8') as ef:
|
| 272 |
+
eval_data = ef.read()
|
| 273 |
+
if '"status": "READY_FOR_VIDEO"' not in eval_data:
|
| 274 |
+
continue
|
| 275 |
+
except Exception:
|
| 276 |
+
continue
|
| 277 |
+
|
| 278 |
+
# Check if video already exists
|
| 279 |
+
video_files = [f for f in os.listdir(article_path) if f.lower().endswith(".mp4")]
|
| 280 |
+
if video_files:
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
# Search for output video in ComfyUI output directory
|
| 284 |
+
safe_name = safe_filename(article)
|
| 285 |
+
video_dir = os.path.join(COMFY_OUTPUT_DIR, "video")
|
| 286 |
+
if not os.path.exists(video_dir):
|
| 287 |
+
video_dir = os.path.join(r"C:\ComfyUI\output", "video")
|
| 288 |
+
|
| 289 |
+
if not os.path.exists(video_dir):
|
| 290 |
+
continue
|
| 291 |
+
|
| 292 |
+
matching_files = [f for f in os.listdir(video_dir) if f.startswith(safe_name) and f.endswith(".mp4")]
|
| 293 |
+
if not matching_files:
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
# Get the latest one
|
| 297 |
+
matching_files.sort(key=lambda f: os.path.getmtime(os.path.join(video_dir, f)), reverse=True)
|
| 298 |
+
latest_video = matching_files[0]
|
| 299 |
+
src_path = os.path.join(video_dir, latest_video)
|
| 300 |
+
dest_path = os.path.join(article_path, f"{safe_name}.mp4")
|
| 301 |
+
|
| 302 |
+
print(f"Found completed video for: {article}")
|
| 303 |
+
print(f" Copying: {src_path} -> {dest_path}")
|
| 304 |
+
try:
|
| 305 |
+
shutil.copy2(src_path, dest_path)
|
| 306 |
+
print(" Successfully copied!")
|
| 307 |
+
package_youtube_assets(article_path, src_path, safe_name)
|
| 308 |
+
copied_count += 1
|
| 309 |
+
except Exception as e:
|
| 310 |
+
print(f" Error copying file: {e}")
|
| 311 |
+
|
| 312 |
+
print(f"Check finished. Copied {copied_count} video(s).")
|
| 313 |
+
|
| 314 |
+
if copied_count > 0:
|
| 315 |
+
copy_script = os.path.join(ROOT_DIR, "copy_passed_articles.py")
|
| 316 |
+
if os.path.exists(copy_script):
|
| 317 |
+
print("\nRunning copy_passed_articles.py to sync to workspace...")
|
| 318 |
+
try:
|
| 319 |
+
import subprocess
|
| 320 |
+
subprocess.run(["python", copy_script], check=True)
|
| 321 |
+
print("Sync completed successfully.")
|
| 322 |
+
except Exception as e:
|
| 323 |
+
print(f"Warning: Failed to sync: {e}")
|
| 324 |
+
|
| 325 |
+
if __name__ == "__main__":
|
| 326 |
+
main()
|
copy_passed_articles.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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 |
+
DEST_DIR = SCRIPT_DIR
|
| 16 |
+
|
| 17 |
+
def check_article_gate(article_dir):
|
| 18 |
+
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"]
|
| 19 |
+
if not md_files:
|
| 20 |
+
return False, "Main article markdown file not found."
|
| 21 |
+
|
| 22 |
+
main_md_path = os.path.join(article_dir, md_files[0])
|
| 23 |
+
try:
|
| 24 |
+
with open(main_md_path, "r", encoding="utf-8") as f:
|
| 25 |
+
content = f.read().strip()
|
| 26 |
+
except Exception as e:
|
| 27 |
+
return False, f"Failed to read article markdown: {e}"
|
| 28 |
+
|
| 29 |
+
if len(content) < 150:
|
| 30 |
+
return False, f"Article content is too short ({len(content)} chars)."
|
| 31 |
+
|
| 32 |
+
error_patterns = [
|
| 33 |
+
r"403\s+forbidden",
|
| 34 |
+
r"access\s+denied",
|
| 35 |
+
r"enable\s+javascript",
|
| 36 |
+
r"please\s+enable\s+cookies",
|
| 37 |
+
r"cloudflare",
|
| 38 |
+
r"captcha",
|
| 39 |
+
r"are\s+you\s+a\s+robot"
|
| 40 |
+
]
|
| 41 |
+
for pattern in error_patterns:
|
| 42 |
+
if re.search(pattern, content, re.IGNORECASE):
|
| 43 |
+
return False, f"Article content contains error pattern: '{pattern}'"
|
| 44 |
+
|
| 45 |
+
return True, "Pass"
|
| 46 |
+
|
| 47 |
+
def check_script_gate(article_dir):
|
| 48 |
+
lengths = ["short", "middle", "long"]
|
| 49 |
+
for length in lengths:
|
| 50 |
+
script_md = os.path.join(article_dir, f"script_{length}.md")
|
| 51 |
+
script_txt = os.path.join(article_dir, f"script_{length}_clean.txt")
|
| 52 |
+
|
| 53 |
+
if not os.path.exists(script_md) or not os.path.exists(script_txt):
|
| 54 |
+
return False, f"Missing script files for length: {length}"
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
with open(script_md, "r", encoding="utf-8") as f:
|
| 58 |
+
md_content = f.read().strip()
|
| 59 |
+
with open(script_txt, "r", encoding="utf-8") as f:
|
| 60 |
+
txt_content = f.read().strip()
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return False, f"Failed to read script files: {e}"
|
| 63 |
+
|
| 64 |
+
if not md_content or not txt_content:
|
| 65 |
+
return False, f"Script content is empty for length: {length}"
|
| 66 |
+
|
| 67 |
+
# Check for speaker labels or dialogue indicators in the text
|
| 68 |
+
forbidden_labels = [r'\bAnchor\b:', r'\bReporter\b:', r'\bCorrespondent\b:', r'\bPresenter\b:', r'\bNarrator\b:', r'\bHost\b:', r'\bVoiceover\b:']
|
| 69 |
+
for pattern in forbidden_labels:
|
| 70 |
+
if re.search(pattern, txt_content, re.IGNORECASE) or re.search(pattern, md_content, re.IGNORECASE):
|
| 71 |
+
return False, f"Script contains forbidden speaker label matching: '{pattern}'"
|
| 72 |
+
|
| 73 |
+
# Check for parenthetical directions like "(laughing)", "[music]"
|
| 74 |
+
if re.search(r'\([^)]+\)', txt_content) or re.search(r'\[[^\]]+\]', txt_content):
|
| 75 |
+
return False, f"Clean script contains parenthetical directions or annotations."
|
| 76 |
+
|
| 77 |
+
return True, "Pass"
|
| 78 |
+
|
| 79 |
+
def check_thumbnail_gate(article_dir):
|
| 80 |
+
thumb_path = os.path.join(article_dir, "thumbnail.png")
|
| 81 |
+
if not os.path.exists(thumb_path):
|
| 82 |
+
return False, "thumbnail.png not found."
|
| 83 |
+
try:
|
| 84 |
+
with Image.open(thumb_path) as img:
|
| 85 |
+
img.verify()
|
| 86 |
+
return True, "Pass"
|
| 87 |
+
except Exception as e:
|
| 88 |
+
return False, f"Thumbnail is corrupted: {e}"
|
| 89 |
+
|
| 90 |
+
def sync_directory(src, dest):
|
| 91 |
+
os.makedirs(dest, exist_ok=True)
|
| 92 |
+
copied_files = 0
|
| 93 |
+
for item in os.listdir(src):
|
| 94 |
+
s_item = os.path.join(src, item)
|
| 95 |
+
d_item = os.path.join(dest, item)
|
| 96 |
+
if os.path.isdir(s_item):
|
| 97 |
+
if item in ["__pycache__"]:
|
| 98 |
+
continue
|
| 99 |
+
copied_files += sync_directory(s_item, d_item)
|
| 100 |
+
else:
|
| 101 |
+
# Copy file if newer, modified size, or missing
|
| 102 |
+
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):
|
| 103 |
+
try:
|
| 104 |
+
shutil.copy2(s_item, d_item)
|
| 105 |
+
copied_files += 1
|
| 106 |
+
except Exception as e:
|
| 107 |
+
print(f" Failed to copy file {item}: {e}")
|
| 108 |
+
return copied_files
|
| 109 |
+
|
| 110 |
+
def main():
|
| 111 |
+
parser = argparse.ArgumentParser(description="Evaluate quality gates and copy passed articles to destination.")
|
| 112 |
+
parser.add_argument("--locale", type=str, default=None, help="Filter by locale.")
|
| 113 |
+
parser.add_argument("--category", type=str, default=None, help="Filter by category.")
|
| 114 |
+
parser.add_argument("--dry-run", action="store_true", help="Evaluate only, do not copy.")
|
| 115 |
+
args = parser.parse_args()
|
| 116 |
+
|
| 117 |
+
print(f"=== Quality Gate Evaluation & Copy System: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
|
| 118 |
+
print(f"Source: {ROOT_DIR}")
|
| 119 |
+
print(f"Destination: {DEST_DIR}")
|
| 120 |
+
if args.dry_run:
|
| 121 |
+
print("NOTE: Running in DRY RUN mode (no files will be copied).")
|
| 122 |
+
print("-" * 60)
|
| 123 |
+
|
| 124 |
+
# Find article directories
|
| 125 |
+
locales = [args.locale] if args.locale else [
|
| 126 |
+
d for d in os.listdir(ROOT_DIR)
|
| 127 |
+
if os.path.isdir(os.path.join(ROOT_DIR, d)) and d not in ["__pycache__", "temp", "temp_sources", "images", "sources"]
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
total_articles = 0
|
| 131 |
+
passed_articles = 0
|
| 132 |
+
copied_count = 0
|
| 133 |
+
|
| 134 |
+
for locale in locales:
|
| 135 |
+
locale_path = os.path.join(ROOT_DIR, locale)
|
| 136 |
+
if not os.path.isdir(locale_path):
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
categories = [args.category] if args.category else [
|
| 140 |
+
c for c in os.listdir(locale_path)
|
| 141 |
+
if os.path.isdir(os.path.join(locale_path, c)) and c not in ["__pycache__", "images", "sources"]
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
for category in categories:
|
| 145 |
+
cat_path = os.path.join(locale_path, category)
|
| 146 |
+
if not os.path.isdir(cat_path):
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
for article in os.listdir(cat_path):
|
| 150 |
+
if article in ["__pycache__", "images", "sources"]:
|
| 151 |
+
continue
|
| 152 |
+
article_path = os.path.join(cat_path, article)
|
| 153 |
+
if not os.path.isdir(article_path):
|
| 154 |
+
continue
|
| 155 |
+
|
| 156 |
+
total_articles += 1
|
| 157 |
+
|
| 158 |
+
# Check Gates
|
| 159 |
+
art_ok, art_reason = check_article_gate(article_path)
|
| 160 |
+
script_ok, script_reason = check_script_gate(article_path)
|
| 161 |
+
thumb_ok, thumb_reason = check_thumbnail_gate(article_path)
|
| 162 |
+
|
| 163 |
+
if art_ok and script_ok and thumb_ok:
|
| 164 |
+
passed_articles += 1
|
| 165 |
+
dest_path = os.path.join(DEST_DIR, locale, category, article)
|
| 166 |
+
|
| 167 |
+
if args.dry_run:
|
| 168 |
+
print(f"[PASS] {locale}/{category}/{article} (Dry Run)")
|
| 169 |
+
else:
|
| 170 |
+
print(f"[PASS] {locale}/{category}/{article}")
|
| 171 |
+
files_copied = sync_directory(article_path, dest_path)
|
| 172 |
+
if files_copied > 0:
|
| 173 |
+
print(f" -> Copied/Updated {files_copied} files.")
|
| 174 |
+
copied_count += 1
|
| 175 |
+
else:
|
| 176 |
+
print(" -> Already up-to-date in destination.")
|
| 177 |
+
else:
|
| 178 |
+
failures = []
|
| 179 |
+
if not art_ok: failures.append(f"Article: {art_reason}")
|
| 180 |
+
if not script_ok: failures.append(f"Script: {script_reason}")
|
| 181 |
+
if not thumb_ok: failures.append(f"Thumbnail: {thumb_reason}")
|
| 182 |
+
|
| 183 |
+
# Print failures in a compact way
|
| 184 |
+
print(f"[FAIL] {locale}/{category}/{article}")
|
| 185 |
+
for f in failures:
|
| 186 |
+
print(f" - {f}")
|
| 187 |
+
|
| 188 |
+
print("-" * 60)
|
| 189 |
+
print(f"Evaluation finished.")
|
| 190 |
+
print(f"Total articles scanned: {total_articles}")
|
| 191 |
+
print(f"Articles passed gates : {passed_articles}")
|
| 192 |
+
if not args.dry_run:
|
| 193 |
+
print(f"Article folders updated : {copied_count}")
|
| 194 |
+
print("=" * 60)
|
| 195 |
+
|
| 196 |
+
if __name__ == "__main__":
|
| 197 |
+
main()
|
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()
|
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()
|