import os import json import sys import re import difflib from datetime import datetime try: import litert_lm except ImportError: litert_lm = None sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') ROOT_DIR = r"C:\ComfyUI\Articles" SYNTHESIS_FILE = os.path.join(ROOT_DIR, "synthesis_output.json") LITERT_MODEL_PATH = r"D:\text_encoders\gemma-4-E2B-it-litert-lm\gemma-4-E2B-it.litertlm" def get_existing_article_titles(): """ Scan category directories under locales (en-US, en-EU, ja-JP) to collect existing sanitized titles/folder names for duplicate detection. """ titles = set() locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"] for locale in locales: loc_path = os.path.join(ROOT_DIR, locale) if not os.path.exists(loc_path): continue for cat in os.listdir(loc_path): cat_path = os.path.join(loc_path, cat) if not os.path.isdir(cat_path) or cat == "__pycache__": continue for art in os.listdir(cat_path): art_path = os.path.join(cat_path, art) if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]: titles.add(art.lower()) titles.add(art.replace('_', ' ').lower()) return titles def is_duplicate(new_title, existing_titles, current_batch_titles, threshold=0.8): """ Check if a new article title is a duplicate of past articles or current batch. Uses SequenceMatcher ratio with a length-difference speed filter. """ new_title_clean = new_title.strip().lower() # 1. Exact matches if new_title_clean in existing_titles or new_title_clean in current_batch_titles: return True, "Exact title match" # 2. Similarity checks against existing articles for ext_title in existing_titles: # Fast optimization: skip if length difference is too large if abs(len(new_title_clean) - len(ext_title)) > max(10, len(new_title_clean) * 0.4): continue ratio = difflib.SequenceMatcher(None, new_title_clean, ext_title).ratio() if ratio >= threshold: return True, f"High similarity ({int(ratio*100)}%) with existing article: '{ext_title}'" # 3. Similarity checks against current batch for cur_title in current_batch_titles: if abs(len(new_title_clean) - len(cur_title)) > max(10, len(new_title_clean) * 0.4): continue ratio = difflib.SequenceMatcher(None, new_title_clean, cur_title).ratio() if ratio >= threshold: return True, f"High similarity ({int(ratio*100)}%) with another article in this batch: '{cur_title}'" return False, "" def clean_article_text(markdown_content): """ Remove markdown headers, metadata lines, image embeds, links, and common footers to extract the pure body text of the article for similarity comparison. """ if not markdown_content: return "" lines = markdown_content.splitlines() cleaned_lines = [] for line in lines: line_strip = line.strip() if not line_strip: continue if line_strip.startswith("#"): continue if line_strip.startswith("**Category:**") or line_strip.startswith("**Locale:**") or line_strip.startswith("**Source:**") or line_strip.startswith("**Date Collected:**"): continue if line_strip.startswith("!["): continue if line_strip == "---": continue if "*This article was automatically collected" in line_strip or "scraped" in line_strip.lower(): continue cleaned_lines.append(line_strip) text = " ".join(cleaned_lines) text = re.sub(r'<[^>]+>', '', text) text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text) text = re.sub(r'\s+', ' ', text).strip() return text def get_recent_article_bodies(max_per_category=30): """ Scan category directories under locales (en-US, en-EU, ja-JP) to collect recent articles' markdown file paths, read their content, and return a dict of {title: cleaned_body}. """ recent_bodies = {} locales = ["en-US", "en-EU", "ja-JP", "en-UA", "en-RU", "en-CN", "en-ME", "en-IN", "en-PK", "en-ZA", "en-AU"] for locale in locales: loc_path = os.path.join(ROOT_DIR, locale) if not os.path.exists(loc_path): continue for cat in os.listdir(loc_path): cat_path = os.path.join(loc_path, cat) if not os.path.isdir(cat_path) or cat == "__pycache__": continue articles = [] for art in os.listdir(cat_path): art_path = os.path.join(cat_path, art) if os.path.isdir(art_path) and art not in ["__pycache__", "images", "sources"]: try: mtime = os.path.getmtime(art_path) articles.append((art, art_path, mtime)) except Exception: continue articles.sort(key=lambda x: x[2], reverse=True) for art, art_path, _ in articles[:max_per_category]: md_file_name = f"{art}.md" md_file_path = os.path.join(art_path, md_file_name) if os.path.exists(md_file_path): try: with open(md_file_path, "r", encoding="utf-8") as f: content = f.read() cleaned = clean_article_text(content) if cleaned: recent_bodies[art.lower()] = cleaned except Exception as e: print(f"Error reading past article {md_file_path}: {e}") return recent_bodies def get_words(text): """ Extract alphanumeric words from text and normalize to lowercase. For Japanese, extract character bi-grams (2-character pairs) to improve similarity precision. """ text_lower = text.lower() is_ja = any(ord(char) > 0x3000 for char in text_lower) if is_ja: cleaned_chars = [char for char in text_lower if char.isalnum() and not char.isspace()] bigrams = set() for i in range(len(cleaned_chars) - 1): bigrams.add(cleaned_chars[i] + cleaned_chars[i+1]) return bigrams else: return set(re.findall(r'\b[a-z0-9]+\b', text_lower)) def is_content_duplicate(new_text, existing_bodies, current_batch_bodies, jaccard_threshold=0.65, seq_threshold=0.70): """ Check if the cleaned new_text is a duplicate of existing articles or current batch. Uses Jaccard word/bigram similarity as a fast pre-filter, followed by SequenceMatcher on prefix. """ new_cleaned = clean_article_text(new_text) if not new_cleaned: return False, "" new_words = get_words(new_cleaned) if not new_words: return False, "" # Check against existing articles for ext_title, ext_body in existing_bodies.items(): ext_words = get_words(ext_body) if not ext_words: continue intersection = new_words.intersection(ext_words) union = new_words.union(ext_words) jaccard = len(intersection) / len(union) if union else 0.0 # Fast early-exit: Jaccard similarity must be at least 0.35 to be a candidate if jaccard < 0.35: continue new_prefix = new_cleaned[:1000] ext_prefix = ext_body[:1000] ratio = difflib.SequenceMatcher(None, new_prefix, ext_prefix).ratio() # Strict AND condition to minimize false positives if jaccard >= jaccard_threshold and ratio >= seq_threshold: reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with existing article: '{ext_title}'" return True, reason # Check against current batch for cur_title, cur_body in current_batch_bodies.items(): cur_words = get_words(cur_body) if not cur_words: continue intersection = new_words.intersection(cur_words) union = new_words.union(cur_words) jaccard = len(intersection) / len(union) if union else 0.0 # Fast early-exit if jaccard < 0.35: continue new_prefix = new_cleaned[:1000] cur_prefix = cur_body[:1000] ratio = difflib.SequenceMatcher(None, new_prefix, cur_prefix).ratio() # Strict AND condition if jaccard >= jaccard_threshold and ratio >= seq_threshold: reason = f"High content similarity (Jaccard: {int(jaccard*100)}%, SequenceMatcher: {int(ratio*100)}%) with another article in this batch: '{cur_title}'" return True, reason return False, "" 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 evaluate_raw_markdown(markdown_content): """ Perform fast, hard-coded checks before sending to LLM. Returns (is_valid: bool, reason: str) """ # 1. Length check if len(markdown_content) < 150: return False, "Article is too short (< 150 chars). Likely a scraping error or stub." # 2. Regex Check: Scraping Errors error_patterns = [ r"403\s+forbidden", r"access\s+denied", r"enable\s+javascript", r"please\s+enable\s+cookies", r"cloudflare", r"captcha", r"are\s+you\s+a\s+robot" ] for pattern in error_patterns: if re.search(pattern, markdown_content, re.IGNORECASE): return False, f"Matches scraping error signature: '{pattern}'" return True, "Pass" def build_proofread_prompt(article_markdown): prompt = f"""You are a strict News Quality Gatekeeper and Proofreader. Your task is to evaluate the following scraped text. Instructions: 1. If the text is an error page, a privacy policy, a captcha request, or pure spam, reply strictly and ONLY with the text: "REJECT: [Reason]". 2. If it is a valid news article, review it for grammatical correctness, natural flow, and factual consistency. 3. PRESERVE the exact formatting of the article, including Markdown headings (#, ##), bullets, and the footer section ("---" and below containing Author and Sources). 4. Output ONLY the corrected markdown text or the REJECT signal. Do not include any introductory or concluding remarks. Article to evaluate: {article_markdown} """ return prompt def main(): print(f"Starting Quality Gate (READY_FOR_NEWS Evaluation) at {datetime.now().isoformat()}") synthesis_data = load_json(SYNTHESIS_FILE, []) if not synthesis_data: print("No synthesis data found. Exiting Quality Gate.") return print(f"Total articles pending evaluation: {len(synthesis_data)}") if not litert_lm: print("litert_lm module not found. Falling back to hard-filters only.") engine = None else: print(f"Loading LiteRT-LM engine for deep evaluation: {LITERT_MODEL_PATH}") try: engine = litert_lm.Engine(LITERT_MODEL_PATH, backend=litert_lm.Backend.CPU, max_num_tokens=8192) except Exception as e: print(f"LiteRT-LM Engine failure: {e}. Falling back to hard-filters only.") engine = None filtered_synthesis_data = [] rejected_count = 0 passed_count = 0 # Collect existing titles and bodies once at start existing_titles = get_existing_article_titles() print("Loading recent article bodies for content duplication check...") existing_bodies = get_recent_article_bodies(max_per_category=30) print(f"Loaded {len(existing_bodies)} recent article bodies.") current_batch_processed_titles = set() current_batch_processed_bodies = {} # {title: cleaned_body} try: for item in synthesis_data: title = item.get("title", "Unknown Title") markdown_content = item.get("markdown", "") if not markdown_content: print(f"REJECTED '{title}': Empty markdown content.") rejected_count += 1 continue print(f"Evaluating article: '{title}'...") # Step 0: Duplicate Checks is_dup, dup_reason = is_duplicate(title, existing_titles, current_batch_processed_titles) if is_dup: print(f" [REJECTED - Duplicate Title] {dup_reason}") rejected_count += 1 continue is_content_dup, content_dup_reason = is_content_duplicate( markdown_content, existing_bodies, current_batch_processed_bodies ) if is_content_dup: print(f" [REJECTED - Duplicate Content] {content_dup_reason}") rejected_count += 1 continue # Step 1: Hard Filters is_valid, reason = evaluate_raw_markdown(markdown_content) if not is_valid: print(f" [REJECTED by Hard Filter] {reason}") rejected_count += 1 continue # Truncate if ridiculously long, but 8192 tokens should be enough if len(markdown_content) > 15000: print(f" [FLAG] Article is extremely long. Skipping LLM proofread but passing through.") item["status"] = "READY_FOR_NEWS" filtered_synthesis_data.append(item) passed_count += 1 continue # Step 2: LLM Evaluation if engine: prompt = build_proofread_prompt(markdown_content) try: with engine.create_conversation() as conversation: response = conversation.send_message(prompt) output = response["content"][0]["text"].strip() if output.startswith("REJECT:"): print(f" [REJECTED by LLM] {output[7:].strip()}") rejected_count += 1 continue # Basic safety check: if model outputs something extremely short, keep original if len(output) > len(markdown_content) * 0.5: item["markdown"] = output print(f" [PASS] Successfully evaluated and proofread.") else: print(f" [PASS with Warning] Corrected output seems too short. Using original.") except Exception as model_err: print(f" [PASS with Warning] Error during LLM evaluation: {model_err}. Using original text.") else: print(" [PASS] Evaluated via hard-filter only (LLM offline).") item["status"] = "READY_FOR_NEWS" filtered_synthesis_data.append(item) current_batch_processed_titles.add(title.strip().lower()) # Store cleaned body for future comparisons in the same batch cleaned_body = clean_article_text(markdown_content) current_batch_processed_bodies[title.strip().lower()] = cleaned_body passed_count += 1 finally: if engine: engine.close() # Save the filtered results, dropping the rejected articles if passed_count > 0 or rejected_count > 0: save_json(SYNTHESIS_FILE, filtered_synthesis_data) print("\n" + "="*40) print("Quality Gate (READY_FOR_NEWS) Finished.") print(f"Articles Passed: {passed_count}") print(f"Articles Rejected & Dropped: {rejected_count}") print(f"Filtered data saved to {SYNTHESIS_FILE}") print("="*40) else: print("\nQuality Gate finished. No articles found to process.") if __name__ == "__main__": main()