File size: 22,469 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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | 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'<meta[^>]*property=[\'"]og:image[\'"][^>]*content=[\'"]([^\'"]+)[\'"]', html, re.I)
if m:
return m.group(1)
m2 = re.search(r'<meta[^>]*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("<!-- slide -->")
carousel_lines.append(f"})")
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<iframe src=\"{uri}\" width=\"100%\" height=\"450px\" style=\"border: 1px solid #ccc; margin-bottom: 20px;\"></iframe>\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()
|