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()