---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" CopeCheck Layoff — Submission Processor Runs every 5 minutes via cron. Processes ONLY pending items in submissions.json. Does NOT call Brave/GNews search APIs — preserves daily quota. Usage."
resource: "https://layoffs.copecheck.com"
tags: ["copecheck", "layoffs", "source-file", "py"]
timestamp: "2026-08-24T13:37:19Z"
site: "layoffs"
source_path: "copecheck-layoffs/process_submissions.py"
---

# !/usr/bin/env python3

Source path: `copecheck-layoffs/process_submissions.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T13:37:19Z`

```py
#!/usr/bin/env python3
"""
CopeCheck Layoff — Submission Processor
Runs every 5 minutes via cron. Processes ONLY pending items in submissions.json.
Does NOT call Brave/GNews search APIs — preserves daily quota.

Usage:
    python3 process_submissions.py
    python3 process_submissions.py --dry-run
    python3 process_submissions.py --verbose
"""

import json
import os
import re
import sys
import hashlib
import logging
import time
from datetime import datetime
from urllib.request import Request, urlopen

# --- Config (same as scanner.py) ---
[redacted secret-like line]
CRAWL4AI_URL = os.environ.get("CRAWL4AI_URL", "http://localhost:11235")
[redacted secret-like line]
BROWSERACT_BASE_URL = "https://api.browseract.com/v2/workflow"
# Template ID for generic web page content extraction
BROWSERACT_WEB_TEMPLATE_ID = os.environ.get("BROWSERACT_WEB_TEMPLATE_ID", "")


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_FILE = os.path.join(BASE_DIR, "data", "layoffs.json")
SEEN_FILE = os.path.join(BASE_DIR, "data", "seen_articles.json")
SUBMISSIONS_FILE = os.path.join(BASE_DIR, "data", "submissions.json")
LOG_FILE = os.path.join(BASE_DIR, "data", "submissions.log")

CRAWL_DELAY = 2
LLM_DELAY = 1

COUNTRY_HINTS = {
    "US": ["united states", "us-based", "silicon valley", "san francisco", "new york",
           "seattle", "austin", "california", "american"],
    "UK": ["united kingdom", "uk", "london", "british", "england", "scotland", "wales",
           "manchester", "birmingham"],
    "DE": ["germany", "german", "berlin", "munich", "frankfurt"],
    "AU": ["australia", "australian", "sydney", "melbourne"],
    "CA": ["canada", "canadian", "toronto", "vancouver"],
    "IN": ["india", "indian", "bangalore", "mumbai", "hyderabad"],
    "IE": ["ireland", "irish", "dublin"],
    "FR": ["france", "french", "paris"],
    "JP": ["japan", "japanese", "tokyo"],
    "CN": ["china", "chinese", "beijing", "shanghai"],
}

SECTOR_HINTS = {
    "Technology": ["tech", "software", "saas", "cloud", "platform"],
    "Finance": ["bank", "financial", "fintech", "investment", "insurance"],
    "E-commerce": ["e-commerce", "ecommerce", "online retail", "marketplace"],
    "Social Media": ["social media", "social network"],
    "Gaming": ["game", "gaming", "esports"],
    "Healthcare": ["health", "medical", "pharma", "biotech"],
    "Automotive": ["auto", "car", "vehicle", "ev ", "electric vehicle"],
    "Telecoms": ["telecom", "telco", "mobile network"],
    "Retail": ["retail", "store", "shop", "consumer"],
    "Enterprise Software": ["enterprise", "crm", "erp"],
    "Media": ["media", "news", "publishing", "broadcast"],
    "Crypto / Fintech": ["crypto", "blockchain", "defi", "bitcoin"],
    "Hardware": ["hardware", "chip", "semiconductor", "device"],
}


def setup_logging(verbose=False):
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[
            logging.FileHandler(LOG_FILE),
            logging.StreamHandler(),
        ]
    )


def load_data():
    with open(DATA_FILE) as f:
        return json.load(f)


def save_data(data):
    with open(DATA_FILE, "w") as f:
        json.dump(data, f, indent=2)


def load_seen():
    if os.path.exists(SEEN_FILE):
        with open(SEEN_FILE) as f:
            return json.load(f)
    return {"urls": [], "hashes": []}


def save_seen(seen):
    with open(SEEN_FILE, "w") as f:
        json.dump(seen, f, indent=2)


def load_submissions():
    if os.path.exists(SUBMISSIONS_FILE):
        with open(SUBMISSIONS_FILE) as f:
            return json.load(f)
    return []


def save_submissions(submissions):
    with open(SUBMISSIONS_FILE, "w") as f:
        json.dump(submissions, f, indent=2)


def article_hash(url):
    return hashlib.md5(url.lower().strip().encode()).hexdigest()


def detect_country(text):
    text_lower = text.lower()
    scores = {}
    for country, keywords in COUNTRY_HINTS.items():
        score = sum(1 for kw in keywords if kw in text_lower)
        if score > 0:
            scores[country] = score
    return max(scores, key=scores.get) if scores else "US"


def detect_sector(text):
    text_lower = text.lower()
    scores = {}
    for sector, keywords in SECTOR_HINTS.items():
        score = sum(1 for kw in keywords if kw in text_lower)
        if score > 0:
            scores[sector] = score
    return max(scores, key=scores.get) if scores else "Technology"


def detect_ai_driven(text):
    ai_keywords = [
        "artificial intelligence", " ai ", "ai-driven", "automation",
        "replaced by ai", "ai replac", "machine learning", "chatgpt",
        "generative ai", "ai tool", "ai system", "automat",
        "ai invest", "ai infrastructure", "ai pivot", "ai-powered",
    ]
    text_lower = f" {text.lower()} "
    return any(kw in text_lower for kw in ai_keywords)



def fetch_article_via_browseract(url):
    """Fallback: fetch rendered page content via BrowserAct when Crawl4AI fails (403/500/empty)."""
[redacted secret-like line]
        return ""

    # If a web scraper template ID is configured, use BrowserAct workflow API
    if BROWSERACT_WEB_TEMPLATE_ID:
        try:
            payload = json.dumps({
                "workflow_template_id": BROWSERACT_WEB_TEMPLATE_ID,
                "input_parameters": [{"name": "TargetURL", "value": url}],
            })
            req = Request(
                f"{BROWSERACT_BASE_URL}/run-task-by-template",
                data=payload.encode(),
                headers={
[redacted secret-like line]
                    "Content-Type": "application/json",
                },
            )
            with urlopen(req, timeout=30) as resp:
                task_data = json.loads(resp.read().decode())
            task_id = task_data.get("id")
            if not task_id:
                logging.warning("BrowserAct: no task_id returned")
                return ""

            # Poll for completion (max ~2 min)
            for _ in range(12):
                time.sleep(10)
                status_req = Request(
                    f"{BROWSERACT_BASE_URL}/get-task-status?task_id={task_id}",
[redacted secret-like line]
                )
                with urlopen(status_req, timeout=15) as r:
                    status_data = json.loads(r.read().decode())
                status = status_data.get("status", "unknown")
                if status == "finished":
                    break
                if status in ("failed", "canceled"):
                    logging.warning(f"BrowserAct: task {status}")
                    return ""

            result_req = Request(
                f"{BROWSERACT_BASE_URL}/get-task?task_id={task_id}",
[redacted secret-like line]
            )
            with urlopen(result_req, timeout=15) as r:
                result = json.loads(r.read().decode())
            output = result.get("output") or result.get("result") or {}
            if isinstance(output, dict):
                content = (output.get("content") or output.get("text")
                           or output.get("markdown") or "")
            else:
                content = str(output)
            if content:
                logging.info(f"BrowserAct (template): fetched {len(content)} chars for {url[:60]}")
            return content
        except Exception as e:
            logging.warning(f"BrowserAct template fetch failed for {url[:80]}: {e}")
            return ""

    # No template configured — fallback to browser user-agent direct fetch
    try:
        req = Request(
            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": "en-US,en;q=0.9",
            }
        )
        with urlopen(req, timeout=20) as resp:
            html = resp.read().decode("utf-8", errors="replace")
        # Strip scripts, styles, tags
        text = re.sub(r"<script[^>]*>.*?</script>", " ", html, flags=re.DOTALL | re.IGNORECASE)
        text = re.sub(r"<style[^>]*>.*?</style>", " ", text, flags=re.DOTALL | re.IGNORECASE)
        text = re.sub(r"<[^>]+>", " ", text)
        text = re.sub(r"\s+", " ", text).strip()
        if len(text) > 200:
            logging.info(f"BrowserAct (UA-spoof): fetched {len(text)} chars for {url[:60]}")
            return text[:8000]
    except Exception as e:
        logging.warning(f"BrowserAct UA-spoof fetch failed for {url[:80]}: {e}")

    return ""

def fetch_article_text(url):
    """Fetch full article text via Crawl4AI."""
    try:
        payload = json.dumps({"urls": [url], "word_count_threshold": 30})
        req = Request(
            f"{CRAWL4AI_URL}/crawl",
            data=payload.encode(),
            headers={"Content-Type": "application/json"},
        )
        with urlopen(req, timeout=30) as resp:
            data = json.loads(resp.read().decode())
            results = data.get("results", [])
            if results and results[0].get("success"):
                md = results[0].get("markdown", {})
                if isinstance(md, dict):
                    return md.get("raw_markdown", "")
                return str(md) if md else ""
    except Exception as e:
        logging.warning(f"Crawl4AI failed for {url[:80]}: {e}")
    return ""


def extract_with_minimax(url, article_text):
    """Use MiniMax to extract layoff data from article text."""
[redacted secret-like line]
[redacted secret-like line]
        return None

    context = article_text[:4000] if article_text else f"URL: {url}"

    prompt = (
        "Extract layoff information from this news article. Return ONLY valid JSON, no other text.\n\n"
        f"URL: {url}\n\n"
        f"Article content:\n{context}\n\n"
        "RULES:\n"
        "1. If this article announces layoffs at ONE specific company, return a JSON array with one object:\n"
        '[{"company": "CompanyName", "laid_off": number_or_null, "pct": "X%" or null, '
        '"country": "US", "sector": "Technology", "reason": "brief reason", "ai_driven": true_or_false}]\n\n'
        "2. If this article is a ROUNDUP listing multiple companies with layoff details, return a JSON array "
        "with one object per company (only include companies where you can identify a specific layoff number or percentage).\n\n"
        "3. If this is an opinion piece, general commentary, or has no specific company layoff data, return:\n"
        '[{"skip": true, "reason": "brief explanation"}]\n\n'
        "Return ONLY the JSON array, nothing else."
    )

    payload = json.dumps({
        "model": "minimax-m2.7",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.1,
[redacted secret-like line]
    })

    try:
        req = Request(
            "https://api.minimax.io/v1/chat/completions",
            data=payload.encode(),
            headers={
                "Content-Type": "application/json",
[redacted secret-like line]
            }
        )
        with urlopen(req, timeout=45) as resp:
            result = json.loads(resp.read().decode())
            content = result["choices"][0]["message"]["content"]
            content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()
            json_match = re.search(r"\[.*\]", content, re.DOTALL)
            if json_match:
                parsed = json.loads(json_match.group())
                if isinstance(parsed, list):
                    return parsed
            json_match = re.search(r"\{.*\}", content, re.DOTALL)
            if json_match:
                return [json.loads(json_match.group())]
    except Exception as e:
        logging.warning(f"MiniMax extraction failed: {e}")

    return None


def process_submission(submission, seen, existing_companies, data, dry_run=False):
    """Process a single pending submission. Returns list of new entries added."""
    url = submission.get("url", "")
    note = submission.get("note", "")

    logging.info(f"Processing submission: {url[:80]}")

    # Check if already seen
    url_hash = article_hash(url)
    if url in seen["urls"] or url_hash in seen["hashes"]:
        logging.info(f"  Already processed (seen): {url[:80]}")
        submission["status"] = "duplicate"
        submission["processed_at"] = datetime.utcnow().isoformat() + "Z"
        return []

    # Mark as seen immediately to avoid reprocessing on crash
    seen["urls"].append(url)
    seen["hashes"].append(url_hash)

    # Fetch article text (Crawl4AI primary, BrowserAct fallback on 403/500/empty)
    article_text = fetch_article_text(url)
    if article_text:
        logging.info(f"  Fetched {len(article_text)} chars via Crawl4AI")
    else:
        logging.warning("  Crawl4AI failed — trying BrowserAct fallback...")
        article_text = fetch_article_via_browseract(url)
        if article_text:
            logging.info(f"  BrowserAct fetched {len(article_text)} chars")
        else:
            logging.warning("  Could not fetch article text (all methods failed)")
    time.sleep(CRAWL_DELAY)

    # Extract with MiniMax
    extracted_list = extract_with_minimax(url, article_text)
    time.sleep(LLM_DELAY)

    new_entries = []

    if not extracted_list:
        logging.warning("  Extraction failed or returned nothing")
        submission["status"] = "failed"
        submission["processed_at"] = datetime.utcnow().isoformat() + "Z"
        submission["error"] = "extraction_failed"
        return []

    for extracted in extracted_list:
        if extracted.get("skip"):
            reason = extracted.get("reason", "not a specific layoff announcement")
            logging.info(f"  Skipped: {reason}")
            submission["status"] = "skipped"
            submission["processed_at"] = datetime.utcnow().isoformat() + "Z"
            submission["skip_reason"] = reason
            continue

        company = extracted.get("company")
        if not company:
            continue

        laid_off = extracted.get("laid_off")
        pct = extracted.get("pct")

        if not laid_off and not pct:
            logging.info(f"  No layoff number found for {company}")
            continue

        company_lower = company.lower().strip()
        if company_lower in existing_companies:
            logging.info(f"  Already tracking: {company}")
            submission["status"] = "duplicate"
            submission["processed_at"] = datetime.utcnow().isoformat() + "Z"
            continue

        date_str = datetime.utcnow().strftime("%Y-%m")

        entry = {
            "company": company,
            "laid_off": laid_off,
            "date": date_str,
            "sector": extracted.get("sector") or detect_sector(article_text),
            "country": extracted.get("country") or detect_country(article_text),
            "reason": extracted.get("reason", note or "")[:120],
            "ai_driven": extracted.get("ai_driven", detect_ai_driven(article_text)),
            "source": "User Submission",
            "source_url": url,
            "added_by": "submission",
            "added_date": datetime.utcnow().strftime("%Y-%m-%d"),
            "verification_status": "unverified_submission",
        }
        if pct:
            entry["pct"] = pct

        new_entries.append(entry)
        existing_companies.add(company_lower)
        logging.info(
            f"  NEW: {company} — {laid_off or '?'} laid off "
            f"({entry['country']}, {entry['sector']})"
        )

    if new_entries:
        submission["status"] = "processed"
        submission["processed_at"] = datetime.utcnow().isoformat() + "Z"
        submission["entries_added"] = len(new_entries)
    elif submission.get("status") not in ("duplicate", "skipped", "failed"):
        submission["status"] = "no_data"
        submission["processed_at"] = datetime.utcnow().isoformat() + "Z"

    return new_entries


def update_summary(data):
    """Record claim-ledger coverage without summing overlapping reports."""
    all_2026 = data.get("major_2026", []) + data.get("scanned_2026", [])
    all_2025 = data.get("major_2025", []) + data.get("scanned_2025", [])
    summary = data.setdefault("summary", {})
    for year, entries in (("2026", all_2026), ("2025", all_2025)):
        row = summary.setdefault(year, {})
        row.update({
            "total_layoffs": None,
            "avg_per_day": None,
            "ai_attributed": None,
            "total_events": len(entries),
            "source_linked_events": sum(bool(e.get("source_url")) for e in entries),
            "aggregate_status": "withheld_non_additive",
        })
    summary.setdefault("since_2020", {})["total"] = None


def run(dry_run=False, verbose=False):
    setup_logging(verbose)

    submissions = load_submissions()
    pending = [s for s in submissions if s.get("status") == "pending"]

    if not pending:
        logging.info(f"No pending submissions (total: {len(submissions)})")
        return 0

    logging.info(f"Found {len(pending)} pending submission(s)")

    data = load_data()
    seen = load_seen()

    # Build existing companies set
    existing_companies = set()
    for key in ["major_2026", "major_2025", "scanned_2026", "scanned_2025"]:
        for entry in data.get(key, []):
            existing_companies.add(entry["company"].lower().strip())
    for entry in data.get("uk_layoffs", []):
        existing_companies.add(entry["company"].lower().strip())

    if "scanned_2026" not in data:
        data["scanned_2026"] = []
    if "scanned_2025" not in data:
        data["scanned_2025"] = []

    total_new = 0

    for submission in submissions:
        if submission.get("status") != "pending":
            continue

        new_entries = process_submission(submission, seen, existing_companies, data, dry_run)

        if new_entries and not dry_run:
            current_year = datetime.utcnow().year
            for entry in new_entries:
                entry_year = int(entry["date"].split("-")[0]) if entry.get("date") else current_year
                if entry_year >= 2026:
                    data["scanned_2026"].append(entry)
                else:
                    data["scanned_2025"].append(entry)
            total_new += len(new_entries)
        elif new_entries and dry_run:
            logging.info(f"  DRY RUN — would add {len(new_entries)} entries")
            total_new += len(new_entries)

    if not dry_run:
        if total_new > 0:
            update_summary(data)
            data["meta"]["last_updated"] = datetime.utcnow().strftime("%Y-%m-%d")
            data["meta"]["last_scan"] = datetime.utcnow().isoformat()
            save_data(data)
            logging.info(f"Saved {total_new} new entries to layoffs.json")
        save_seen(seen)
        save_submissions(submissions)

    logging.info(f"Done. {total_new} new entries from {len(pending)} submission(s).")
    return total_new


if __name__ == "__main__":
    dry_run = "--dry-run" in sys.argv
    verbose = "--verbose" in sys.argv
    run(dry_run=dry_run, verbose=verbose)
```
