import os import re import json import urllib.request import urllib.parse import sys from datetime import datetime import requests try: from curl_cffi import requests as requests_cffi HAS_CURL_CFFI = True except ImportError: HAS_CURL_CFFI = False from googlenewsdecoder import new_decoderv1 sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') # Dynamic path for importing WatermarkRemover sys.path.insert(0, r"C:\Roaming\scripts") try: from news_collector.watermark_remover import WatermarkRemover HAS_REMOVER = True except ImportError: HAS_REMOVER = False ROOT_DIR = r"C:\ComfyUI\Articles" HISTORY_FILE = os.path.join(ROOT_DIR, "history.json") PENDING_FILE = os.path.join(ROOT_DIR, "pending.json") SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json") TEST_VIDEO_URL = "https://www.w3schools.com/html/mov_bbb.mp4" # Fallback images removed for authentic scraping def load_json(path, default): if os.path.exists(path): try: with open(path, 'r', encoding='utf-8') as f: return json.load(f) except Exception as e: print(f"Failed to load JSON {path}: {e}") return default def save_json(path, data): try: with open(path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=4, ensure_ascii=False) except Exception as e: print(f"Failed to save JSON {path}: {e}") def extract_main_word(title): # Replace underscores and commas with spaces to handle words correctly title = title.replace('_', ' ').replace(',', ' ') is_ja = any(ord(char) > 0x3000 for char in title) # Clean title from source marks cleaned = re.sub(r'\s*-\s*[^-\s]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', title, flags=re.IGNORECASE) cleaned = re.sub(r'_[^_]+(?:ニュース|新聞|オンライン|net|jp|com|JAPAN|Jpn|DIG|WSJ| Forbes|産経|共同|時事|読売|朝日|毎日|毎日新聞|株探|かぶたん|note|AFPBB|Gizmodo|MONOist|Impress|Real Sound|デイリー|西日本|沖縄|神戸|下野|福島|東奥|愛媛|福井|佐賀)\s*$', '', cleaned, flags=re.IGNORECASE) blacklisted = ["ai", "artificial intelligence", "人工知能", "生成ai", "生成系ai"] def is_valid(word): if not word: return False return word.strip().lower() not in blacklisted # 1. Look for quotes like 「...」 quotes_ja = re.findall(r'「([^」]+)」', cleaned) for q in quotes_ja: if is_valid(q): return q quotes_en = re.findall(r'["\']([^"\']+)["\']', cleaned) for q in quotes_en: if len(q) < 25 and is_valid(q): return q # 2. Known key entities list known_keywords = [ "OpenAI", "Google", "Amazon", "Bezos", "Trump", "Anthropic", "Microsoft", "Apple", "Nvidia", "Meta", "Musk", "大谷", "オオタニ", "大谷翔平", "小田急", "ソニー", "ソフトバンク", "ChatGPT", "Claude", "IOWN", "サカナAI" ] for kw in known_keywords: if kw.lower() in cleaned.lower() and is_valid(kw): m = re.search(re.escape(kw), cleaned, re.IGNORECASE) if m: return m.group(0) if is_ja: # Katakana sequences katakana = re.findall(r'[\u30a1-\u30fc]{2,}', cleaned) for k in katakana: if is_valid(k): return k # Kanji sequences kanji = re.findall(r'[\u4e00-\u9fff]{2,}', cleaned) for k in kanji: if k not in ["米国", "日本", "市場", "世界", "政府", "計画", "導入"] and is_valid(k): return k if kanji: for k in kanji: if is_valid(k): return k # Alphabetic words alpha = re.findall(r'[a-zA-Z0-9]{2,}', cleaned) for a in alpha: if is_valid(a): return a else: words = re.findall(r'\b[A-Z][a-zA-Z0-9]*\b', cleaned) if words: for w in words: if w.lower() not in ["a", "an", "the", "in", "on", "at", "for", "to", "of", "and", "or", "but", "with", "by", "is", "are", "was", "were"] and is_valid(w): return w for w in words: if is_valid(w): return w first_token = re.search(r'\w+', cleaned) if first_token and is_valid(first_token.group(0)): return first_token.group(0) return "" def safe_filename(name, max_len=40): main_word = extract_main_word(name).strip() cleaned = name.replace('_', ' ').replace(',', ' ') cleaned = re.sub(r'[\\/*?:"<>|\'\`\(\)\[\]]', ' ', cleaned) cleaned = re.sub(r'\s+', ' ', cleaned).strip() if main_word: if cleaned.lower().startswith(main_word.lower()): final_title = cleaned else: final_title = f"{main_word} {cleaned}" else: final_title = cleaned final_title = re.sub(r'\s+', ' ', final_title).strip() if len(final_title) > max_len: final_title = final_title[:max_len].strip() final_title = re.sub(r'[\s\.,\-_\+!@#\$%^&\*]+$', '', final_title) return final_title def to_file_uri(path): path_part = path.replace(os.sep, '/') return f"file:///{path_part.replace(' ', '%20')}" def to_markdown_absolute_path(path): return path.replace(os.sep, '/') def download_file(url, dest_path): print(f"Downloading: {url} -> {dest_path}") headers = { "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", "Accept": "image/webp,image/apng,image/*,*/*;q=0.8", "Accept-Language": "ja,en-US;q=0.9,en;q=0.8", "Referer": "https://news.google.com/" } try: os.makedirs(os.path.dirname(dest_path), exist_ok=True) if HAS_CURL_CFFI: response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=30) else: response = requests.get(url, headers=headers, timeout=30) response.raise_for_status() with open(dest_path, 'wb') as f: f.write(response.content) if os.path.exists(dest_path) and os.path.getsize(dest_path) > 0: print(f"Download success: {dest_path} ({os.path.getsize(dest_path)} bytes)") return True else: print(f"Downloaded file is empty: {dest_path}") if os.path.exists(dest_path): os.remove(dest_path) return False except Exception as e: print(f"Failed to download {url}: {e}") if os.path.exists(dest_path): try: os.remove(dest_path) except: pass return False def is_valid_image(img_url, img_path): # 1. URL Substring Check url_lower = img_url.lower() # Generic keywords indicating logos, default fallback pictures, ads, etc. blacklist_keywords = [ "logo", "avatar", "favicon", "icon", "placeholder", "default", "fallback", "dummy", "spacer", "pixel", "header", "footer", "ad-", "ads-", "advertisement", "newsletter", "subscribe", "sign-up", "social-share", "facebook-share", "twitter-share", "share-icon", "share-logo", "app-store", "play-store", "transparent", "blank", "branding" ] # Also block specific generic image names commonly used by news outlets # e.g., Yahoo, Reuters, AP, Bloomberg, BBC, etc. logos or generic graphics generic_patterns = [ "reuters-logo", "reuters_logo", "nytimes-logo", "nytimes_logo", "ap-logo", "ap_logo", "bbc-logo", "bbc_logo", "cnn-logo", "cnn_logo", "bloomberg-logo", "bloomberg_logo", "yahoo-logo", "yahoo_logo", "wsj_logo", "wsj-logo", "guardian-logo", "guardian_logo" ] for kw in blacklist_keywords: if kw in url_lower: print(f" Rejecting image URL (matches blacklist keyword '{kw}'): {img_url}") return False for pat in generic_patterns: if pat in url_lower: print(f" Rejecting image URL (matches generic logo pattern '{pat}'): {img_url}") return False # 2. Image Content Check (using Pillow) if not os.path.exists(img_path): return False try: from PIL import Image, ImageStat with Image.open(img_path) as img: width, height = img.size # Aspect Ratio aspect_ratio = width / height # Minimum dimension requirements min_width = 300 min_height = 200 if width < min_width or height < min_height: print(f" Rejecting image (too small: {width}x{height}, required min {min_width}x{min_height})") return False # Aspect Ratio Check (block extremely wide/tall banner or ad layout blocks) if aspect_ratio < 0.5 or aspect_ratio > 3.0: print(f" Rejecting image (extreme aspect ratio: {aspect_ratio:.2f})") return False # Perfect square check (width == height) for small images (usually logos/avatars) if width == height and width < 450: print(f" Rejecting image (square logo/avatar heuristic: {width}x{height})") return False # Standard Deviation check (blank or solid color placeholder images) # A natural photograph typically has standard deviation > 10. # Spacer GIFs or blank images will have standard deviation near 0. stat = ImageStat.Stat(img) # Check standard deviation of all bands (RGB / RGBA / L) std_devs = stat.stddev if std_devs and all(sd < 3.0 for sd in std_devs): print(f" Rejecting image (low variance / solid color placeholder: stddev={std_devs})") return False except ImportError: print(" Warning: Pillow (PIL) is not installed. Skipping image dimension and content validation.") except Exception as e: print(f" Warning: Failed to validate image content properties: {e}") return True def extract_og_image(url): print(f"Extracting og:image from: {url}") headers = { "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", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "ja,en-US;q=0.9,en;q=0.8", "Referer": "https://news.google.com/" } try: if HAS_CURL_CFFI: response = requests_cffi.get(url, headers=headers, impersonate="chrome120", timeout=15) else: response = requests.get(url, headers=headers, timeout=15) response.raise_for_status() html = response.text m = re.search(r']*property=[\'"]og:image[\'"][^>]*content=[\'"]([^\'"]+)[\'"]', html, re.I) if m: return m.group(1) m2 = re.search(r']*content=[\'"]([^\'"]+)[\'"][^>]*property=[\'"]og:image[\'"]', html, re.I) if m2: return m2.group(1) except Exception as e: print(f"Failed to fetch og:image from {url}: {e}") return None def finalize_article(category, title, link, article_content, source_file): print(f"\nFinalizing article: {title} under category: {category}") safe_title = safe_filename(title) # Determine language (ja-JP if title contains Japanese characters, else en-US) is_ja = any(ord(char) > 0x3000 for char in title) lang = "ja-JP" if is_ja else "en-US" # Map raw RSS category to directory category name CAT_MAP = { "Business": "Business_and_Economy", "World_Affairs": "World_Affairs", "General": "General_News", "Animals": "Science_and_Animals" } cat_folder = CAT_MAP.get(category, "Uncategorized") # Create article-specific directory structure under appropriate language/category article_dir = os.path.join(ROOT_DIR, lang, cat_folder, safe_title) images_dir = os.path.join(article_dir, "images") sources_dir = os.path.join(article_dir, "sources") os.makedirs(images_dir, exist_ok=True) os.makedirs(sources_dir, exist_ok=True) # 1. Rename raw source file and collect details downloaded_sources = [] if source_file and os.path.exists(source_file): final_filename = f"{safe_title}_source_1.txt" final_dest = os.path.join(sources_dir, final_filename) try: if os.path.exists(final_dest): os.remove(final_dest) os.rename(source_file, final_dest) downloaded_sources.append((title, to_file_uri(final_dest))) print(f"Moved source file: {source_file} -> {final_dest}") except Exception as e: print(f"Failed to move source file {source_file} to {final_dest}: {e}") downloaded_sources.append((title, to_file_uri(source_file))) else: print(f"Source file not found or not specified for: {title}") # 2. Download authentic images from source link image_urls = [] decoded_link = link if "news.google.com" in link: try: res = new_decoderv1(link, interval=1) if res.get("status"): decoded_link = res["decoded_url"] print(f"Decoded Google News URL for image extraction: {decoded_link}") except Exception as e: print(f"Failed to decode Google News URL {link} for image extraction: {e}") og_img = extract_og_image(decoded_link) if og_img: image_urls.append(og_img) downloaded_images = [] # Initialize WatermarkRemover if available from pathlib import Path remover = WatermarkRemover(Path(ROOT_DIR)) if HAS_REMOVER else None for idx, url in enumerate(image_urls[:2], 1): img_filename = f"{safe_title}_img{idx}.jpg" img_dest = os.path.join(images_dir, img_filename) success = download_file(url, img_dest) if success: if not is_valid_image(url, img_dest): print(f"Rejected downloaded image as unrelated: {url}") if os.path.exists(img_dest): try: os.remove(img_dest) except: pass continue downloaded_images.append(img_dest) if remover: try: remover.remove_watermark(Path(img_dest), decoded_link) except Exception as rem_err: print(f"Failed to remove watermark for {img_dest}: {rem_err}") # 3. No related video briefing available by default. Omit placeholder. video_embed_md = "" # 4. Inject Carousel at the top (right after title or date) if downloaded_images: lines = article_content.splitlines() title_idx = -1 for i, line in enumerate(lines): if line.strip().startswith("# "): title_idx = i break date_idx = -1 if title_idx != -1: for i in range(title_idx + 1, len(lines)): if lines[i].strip(): date_idx = i break insert_idx = -1 if date_idx != -1: insert_idx = date_idx + 1 elif title_idx != -1: insert_idx = title_idx + 1 if insert_idx != -1: carousel_lines = ["", "```carousel"] for j, img_path in enumerate(downloaded_images, 1): if j > 1: carousel_lines.append("") carousel_lines.append(f"![Visual Theme {j}]({to_markdown_absolute_path(img_path)})") carousel_lines.append("```") carousel_lines.append("") lines = lines[:insert_idx] + carousel_lines + lines[insert_idx:] article_content = "\n".join(lines) # 5. Inject Video embed before the footer if video_embed_md: footer_idx = article_content.rfind("---") if footer_idx != -1: article_content = article_content[:footer_idx] + video_embed_md + article_content[footer_idx:] else: article_content += video_embed_md # 6. Inject Source document preview iframe before the footer if downloaded_sources: sources_preview_md = "\n\n### Original Source Document Previews\n" for title_src, uri in downloaded_sources[:3]: sources_preview_md += f"#### {title_src}\n\n" footer_idx = article_content.rfind("---") if footer_idx != -1: article_content = article_content[:footer_idx] + sources_preview_md + article_content[footer_idx:] else: article_content += sources_preview_md # 7. Save the final Markdown file inside the article directory dest_file_path = os.path.join(article_dir, f"{safe_title}.md") try: with open(dest_file_path, 'w', encoding='utf-8') as f: f.write(article_content) print(f"Saved Article successfully: {dest_file_path}") # 7.5. Check if it's Russian, Ukrainian, or independent media to assign S-Tier (tier 1) is_s_tier = False s_tier_domains = [ "meduza.io", "themoscowtimes.com", "kyivindependent.com", "pravda.com.ua", "novayagazeta.eu", "novayagazeta.ru", "zona.media", "mediazona.ca", "tvrain.tv", "tvrain.ru", "istories.media", "theins.ru", "theins.press", "verstka.media", "currenttime.tv", "rferl.org", "unian.net", "unian.info", "euromaidanpress.com", "ukrinform.net", "ukrinform.ua", "hromadske.ua" ] link_lower = link.lower() decoded_link_lower = decoded_link.lower() if any(domain in link_lower or domain in decoded_link_lower for domain in s_tier_domains): is_s_tier = True if is_s_tier: meta_dest = os.path.join(article_dir, f"{safe_title}.json") try: with open(meta_dest, 'w', encoding='utf-8') as mf: json.dump({ "importance": 9, "urgency": 9, "tier": 1 }, mf, indent=4) print(f"Automatically assigned S-Tier (tier 1) for independent RU/UA source: {meta_dest}") except Exception as e: print(f"Failed to write S-Tier metadata for {safe_title}: {e}") return True except Exception as e: print(f"Failed to save article {safe_title}: {e}") return False def main(): print(f"Starting finalization at {datetime.now().isoformat()}") synthesis_data = load_json(SYNTHESIS_FILE, []) if not synthesis_data: print("No synthesis data found. Exiting.") return [] history = load_json(HISTORY_FILE, {}) pending_list = load_json(PENDING_FILE, []) processed_count = 0 newly_processed_urls = set() finalized_dirs = [] for article_dict in synthesis_data: category = article_dict.get("category") title = article_dict.get("title") link = article_dict.get("link") markdown = article_dict.get("markdown") source_file = article_dict.get("source_file") if not markdown or not link: continue success = finalize_article(category, title, link, markdown, source_file) if success: processed_count += 1 newly_processed_urls.add(link) history[link] = { "title": title, "collected_at": datetime.now().isoformat(), "category": category } # Reconstruct the exact path where the article was finalized safe_title = safe_filename(title) is_ja = any(ord(char) > 0x3000 for char in title) lang = "ja-JP" if is_ja else "en-US" CAT_MAP = { "Business": "Business_and_Economy", "World_Affairs": "World_Affairs", "General": "General_News", "Animals": "Science_and_Animals" } cat_folder = CAT_MAP.get(category, "Uncategorized") article_dir = os.path.join(ROOT_DIR, lang, cat_folder, safe_title) finalized_dirs.append(article_dir) if processed_count > 0: if len(history) > 2000: sorted_keys = sorted(history.keys(), key=lambda k: history[k].get("collected_at", "")) for k in sorted_keys[:len(history) - 2000]: del history[k] save_json(HISTORY_FILE, history) updated_pending = [item for item in pending_list if item["link"] not in newly_processed_urls] save_json(PENDING_FILE, updated_pending) print(f"Successfully finalized {processed_count} articles.") # Clean up temp_sources directory if empty temp_sources_dir = os.path.join(ROOT_DIR, "temp_sources") if os.path.exists(temp_sources_dir): try: if not os.listdir(temp_sources_dir): os.rmdir(temp_sources_dir) print("Removed empty temp_sources directory.") except Exception as e: print(f"Failed to check/remove temp_sources directory: {e}") if os.path.exists(SYNTHESIS_FILE): try: os.remove(SYNTHESIS_FILE) print("Cleared synthesis_output.json") except Exception as e: print(f"Failed to delete synthesis_output.json: {e}") return finalized_dirs if __name__ == "__main__": main()