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