File size: 16,027 Bytes
032a0c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | import os
import re
import sys
import json
import argparse
from datetime import datetime
# Reconfigure encoding to avoid Windows console encoding issues
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
ROOT_DIR = r"C:\ComfyUI\Articles"
LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm"
try:
import litert_lm
HAS_LITERT = True
except ImportError:
HAS_LITERT = False
def clean_for_tts(text):
lines = text.splitlines()
cleaned_lines = []
for line in lines:
line = line.strip()
if not line:
continue
# Skip headers
if line.startswith('#'):
continue
# Remove speaker labels like "**Anchor:**" or "**Correspondent (Riga):**" or "Military Analyst:"
line = re.sub(r'^\**[A-Za-z0-9\s\(\)\.\-\_]+:\**\s*', '', line)
# Remove parenthetical performance notes or sound effects like (Opening music...) or [Music]
line = re.sub(r'\([^)]*\)', '', line)
line = re.sub(r'\[[^\]]*\]', '', line)
# Remove markdown bold/italic markers
line = line.replace('**', '').replace('*', '')
# Remove leading/trailing quotes
line = line.strip()
if line.startswith('"') and line.endswith('"'):
line = line[1:-1]
elif line.startswith('“') and line.endswith('”'):
line = line[1:-1]
line = line.strip()
if line:
cleaned_lines.append(line)
return '\n\n'.join(cleaned_lines)
def detect_japanese(text):
# Check for Hiragana (0x3040-0x309F), Katakana (0x30A0-0x30FF), or Kanji (0x4E00-0x9FFF)
for char in text:
cp = ord(char)
if (0x3040 <= cp <= 0x309F) or (0x30A0 <= cp <= 0x30FF) or (0x4E00 <= cp <= 0x9FFF):
return True
return False
def generate_script_prompt(article_title, article_content, length_type, is_ja):
lang_name = "Japanese" if is_ja else "English"
is_very_short = len(article_content.strip()) < 300
if length_type == "short":
word_limit = "100 words" if is_very_short else "200 words"
elif length_type == "middle":
word_limit = "200 words" if is_very_short else "400 words"
else: # long
word_limit = "400 words" if is_very_short else "800-1000 words"
# Common rules for anchor script
if is_ja:
rules = """1. スクリプトは日本語で書いてください。
2. ニュースキャスターが声に出して読み上げるのに適した、自然で分かりやすい話し言葉(です・ます調)にしてください。
3. 主観的な解説や、「この記事は~」「この記事が強調するように~」といったメタ的な表現(記事そのものに言及する表現)は絶対に含めないでください。あなた自身がニュースを直接伝えているキャスターであるかのように描写してください。
4. 「これは〜を示唆しています」「この状況は〜という複雑な現実を浮き彫りにしています」のような学術的・分析的な表現は避け、事実と状況をストレートに伝えてください。
5. 自然な導入フレーズ(例:「こんばんは。本日お伝えするニュースは、」など)で始め、最後は「アンドロイド・タイムズがお伝えしました。」という結びの言葉で終わらせてください。
6. 単一のキャスターが連続して読み上げる形式にしてください。対話形式やヘッダー(「導入」「背景」など)、話者ラベル(「キャスター:」「ナレーター:」など)は含めないでください。"""
else:
rules = """1. Write the script in clear, spoken English, suitable for reading aloud.
2. Use a professional yet conversational tone, typical of international news broadcasts.
3. Act as if YOU are reporting the news firsthand as a live anchor. Crucially, do NOT say "The article says", "The article highlights", "According to the article", "This report", or refer to the text/article itself in any metatextual way.
4. Avoid analytical or academic phrasing like "This suggests...", "The narrative...", "This highlights...". Focus only on the facts and developments of the event.
5. Begin the script with a natural introductory phrase (e.g., "Good evening. Today, we turn to..." or "Tonight, we have an important update regarding...").
6. Sign-off by explicitly saying a closing phrase such as "Reporting for The Android Times."
7. Crucially, do NOT include any speaker labels (e.g., do NOT write '**Anchor:**', '**Reporter:**', etc.) or section headers. Just output the clean script text. Do not wrap paragraphs in quotation marks.
8. Ensure correct grammar and natural phrasing. Do not omit necessary articles (e.g., say "An airstrike..." instead of "Airstrike...")."""
prompt = f"""You are a professional news anchor.
Write a {length_type}-length news script (about {word_limit}) in {lang_name} based on the following article.
{"Since the article content is extremely brief, expand on the potential implications and general context of this news." if is_very_short and length_type == "long" else ""}
The script should be optimized for a news broadcast voiceover.
Article Title: {article_title}
Article Content:
{article_content}
Requirements:
{rules}
Keep it to approximately {word_limit} (or equivalent length in Japanese).
Return only the script content. Do not include any introductory or concluding chat remarks or code block formatting (like ```).
"""
return prompt
def strip_forbidden_labels(text):
forbidden_patterns = [
r'^([\s\*\-]*)\**Anchor\b:\**\s*',
r'^([\s\*\-]*)\**Reporter\b:\**\s*',
r'^([\s\*\-]*)\**Correspondent\b:\**\s*',
r'^([\s\*\-]*)\**Presenter\b:\**\s*',
r'^([\s\*\-]*)\**Narrator\b:\**\s*',
r'^([\s\*\-]*)\**Host\b:\**\s*',
r'^([\s\*\-]*)\**Voiceover\b:\**\s*'
]
lines = text.splitlines()
cleaned_lines = []
for line in lines:
cleaned_line = line
for pattern in forbidden_patterns:
cleaned_line = re.sub(pattern, r'\1', cleaned_line, flags=re.IGNORECASE)
cleaned_lines.append(cleaned_line)
return '\n'.join(cleaned_lines)
def process_article(engine, article_dir, force):
dir_name = os.path.basename(article_dir)
print(f"\nProcessing article directory: {dir_name}")
# Find the main article file (same name as directory, or ends with .md but not a script)
md_files = [f for f in os.listdir(article_dir) if f.endswith(".md")]
main_article_file = None
for f in md_files:
if not f.endswith(("script_short.md", "script_middle.md", "script_long.md", "script_normal.md", "script.md")):
main_article_file = f
break
if not main_article_file:
# Fallback: search for any .md file
for f in md_files:
main_article_file = f
break
if not main_article_file:
print(f"Error: No main markdown file found in {dir_name}. Skipping.")
return False
main_article_path = os.path.join(article_dir, main_article_file)
try:
with open(main_article_path, 'r', encoding='utf-8') as f:
article_content = f.read().strip()
except Exception as e:
print(f"Error reading {main_article_path}: {e}. Skipping.")
return False
# Get article title
title_m = re.match(r'^#\s+(.+)$', article_content.splitlines()[0])
article_title = title_m.group(1) if title_m else dir_name
is_ja = detect_japanese(article_content)
print(f"Detected language: {'Japanese' if is_ja else 'English'}")
lengths = ["short", "middle", "long"]
generated_any = False
for length in lengths:
script_file_name = f"script_{length}.md"
script_path = os.path.join(article_dir, script_file_name)
txt_file_name = f"script_{length}_clean.txt"
txt_path = os.path.join(article_dir, txt_file_name)
# Check if files already exist
if os.path.exists(script_path) and os.path.exists(txt_path) and not force:
print(f" {length} script and TTS text already exist. Skipping.")
continue
print(f" Generating {length} script...")
prompt = generate_script_prompt(article_title, article_content, length, is_ja)
try:
with engine.create_conversation() as conversation:
response = conversation.send_message(prompt)
script_text = response["content"][0]["text"].strip()
# Strip forbidden speaker labels from the script markdown itself
script_text = strip_forbidden_labels(script_text)
# Write markdown script
with open(script_path, 'w', encoding='utf-8') as f:
f.write(script_text)
print(f" Saved script: {script_path}")
# Clean for TTS and write text file
clean_text = clean_for_tts(script_text)
with open(txt_path, 'w', encoding='utf-8') as f:
f.write(clean_text)
print(f" Saved TTS text: {txt_path}")
generated_any = True
except Exception as e:
print(f" Error generating {length} script: {e}")
return generated_any
def main():
parser = argparse.ArgumentParser(description="Batch generate news scripts and clean TTS text files for all articles.")
parser.add_argument("--limit", type=int, default=5, help="Maximum number of articles to process in this run. Default is 5.")
parser.add_argument("--category", type=str, default=None, help="Process only a specific category (e.g. World_Affairs).")
parser.add_argument("--locale", type=str, default=None, help="Process only a specific locale (e.g. en-US, ja-JP).")
parser.add_argument("--force", action="store_true", help="Force regeneration of scripts even if they exist.")
parser.add_argument("--all", action="store_true", help="Process all articles without limit.")
parser.add_argument("--gpu", action="store_true", help="Use GPU backend for inference.")
args = parser.parse_args()
if not HAS_LITERT:
print("Error: litert_lm package is not installed. Please check environment.")
sys.exit(1)
if not os.path.exists(LITERT_MODEL_PATH):
print(f"Error: Model not found at {LITERT_MODEL_PATH}")
sys.exit(1)
# Scan article directories
locales = [args.locale] if args.locale else ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"]
article_dirs = []
for locale in locales:
locale_path = os.path.join(ROOT_DIR, locale)
if not os.path.exists(locale_path) or not os.path.isdir(locale_path):
continue
categories = [args.category] if args.category else os.listdir(locale_path)
for category in categories:
if category in ["__pycache__"]:
continue
cat_path = os.path.join(locale_path, category)
if not os.path.exists(cat_path) or not os.path.isdir(cat_path):
continue
articles = os.listdir(cat_path)
for article in articles:
if article in ["__pycache__", "images", "sources"]:
continue
article_path = os.path.join(cat_path, article)
if os.path.isdir(article_path):
# Check if it has a main markdown file
md_files = [f for f in os.listdir(article_path) if f.endswith(".md")]
if md_files:
article_dirs.append(article_path)
def get_priority_score(article_dir):
path_lower = article_dir.lower()
score = 0
if "en-us" in path_lower:
score += 10000
if "en-us" in path_lower and "moscow_attacks" in path_lower:
score += 1000
elif "moscow_attacks" in path_lower:
score += 500
elif "war_and_military" in path_lower:
score += 400
# War-related keywords in English and Japanese
war_keywords = [
"war", "military", "conflict", "attack", "bombing", "invasion",
"soldier", "battle", "clash", "defense", "missile", "drone",
"bomb", "strike", "shelling", "army", "troop", "nato", "putin",
"ukraine", "russia", "kremlin", "pentagon", "blasts",
"戦争", "軍事", "衝突", "攻撃", "爆撃", "侵攻", "兵士", "戦闘",
"ミサイル", "ドローン", "爆発", "ウクライナ", "ロシア", "プーチン"
]
if any(kw in path_lower for kw in war_keywords):
score += 200
return score
# Sort by priority score descending first, then by modification time descending
article_dirs.sort(key=lambda x: (get_priority_score(x), os.path.getmtime(x)), reverse=True)
print(f"Found total of {len(article_dirs)} articles.")
# Filter directories depending on whether they need processing (unless --force is set)
dirs_to_process = []
for d in article_dirs:
# Check if script_short.md and script_short_clean.txt etc. exist
all_exist = True
for length in ["short", "middle", "long"]:
script_path = os.path.join(d, f"script_{length}.md")
txt_path = os.path.join(d, f"script_{length}_clean.txt")
if not os.path.exists(script_path) or not os.path.exists(txt_path):
all_exist = False
break
if not all_exist or args.force:
dirs_to_process.append(d)
print(f"Articles requiring script generation: {len(dirs_to_process)}")
if not dirs_to_process:
print("All articles already have scripts. Use --force to regenerate.")
return
# Apply limit
limit = len(dirs_to_process) if args.all else args.limit
dirs_to_process = dirs_to_process[:limit]
print(f"Will process {len(dirs_to_process)} articles in this run.")
# Helper to check GPU utilization
def is_gpu_busy(threshold_util=25):
import subprocess
try:
output = subprocess.check_output(
['nvidia-smi', '--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'],
stderr=subprocess.DEVNULL
).decode().strip()
util = int(output.strip())
return util > threshold_util
except Exception:
return False
processed_count = 0
for idx, article_dir in enumerate(dirs_to_process, 1):
print(f"\n--- Article {idx}/{len(dirs_to_process)} ---")
# Select backend dynamically based on GPU load
current_backend = litert_lm.Backend.CPU
backend_name = "CPU"
if args.gpu:
if is_gpu_busy():
print("GPU is currently busy (utilization > 25%). Falling back to CPU backend for this article to avoid contention and timeouts.")
else:
current_backend = litert_lm.Backend.GPU
backend_name = "GPU"
print(f"Loading LiteRT-LM Engine with Gemma-4 model on {backend_name}...")
try:
with litert_lm.Engine(LITERT_MODEL_PATH, backend=current_backend, max_num_tokens=8192) as engine:
success = process_article(engine, article_dir, args.force)
if success:
processed_count += 1
except Exception as engine_err:
print(f"LiteRT-LM engine error for article {idx}: {engine_err}")
print(f"\nFinished. Successfully generated scripts for {processed_count} articles.")
if __name__ == "__main__":
main()
|