---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import json import os import re import shutil import sqlite3 import subprocess import sys import time from collections import defaultdict from datetime import date."
resource: "https://seo.copecheck.com"
tags: ["copecheck", "seo", "source-file", "py"]
timestamp: "2026-05-11T14:17:37Z"
site: "seo"
source_path: "copecheck-seo/search_console_importer.py"
---

# from __future__ import annotations

Source path: `copecheck-seo/search_console_importer.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-11T14:17:37Z`

```py
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
from collections import defaultdict
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"
DEFAULT_DB = DATA_DIR / "search-console.sqlite"
DEFAULT_SNAPSHOT = DATA_DIR / "search-console-snapshot.json"
DEFAULT_ADC = Path.home() / ".config" / "gcloud" / "application_default_credentials.json"
[redacted secret-like line]
API_ROOT = "https://www.googleapis.com/webmasters/v3"
DEFAULT_SITE_URLS = ["sc-domain:copecheck.com"]
SEARCH_TYPES = ["web"]
QUERY_DIMENSIONS = [
    ["date"],
    ["query"],
    ["page"],
    ["page", "query"],
]
PUBLIC_QUERY_LIMIT = 30
PUBLIC_PAGE_LIMIT = 30
PUBLIC_PROPERTY_LIMIT = 20


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def iso_day(value: date) -> str:
    return value.isoformat()


def normalize_ctr(value: float | int | None) -> float:
    if value is None:
        return 0.0
    return round(float(value) * 100, 2)


def weighted_position(rows: list[dict[str, Any]]) -> float | None:
    total_impressions = sum(float(row.get("impressions") or 0) for row in rows)
    if total_impressions <= 0:
        positions = [float(row.get("position") or 0) for row in rows if row.get("position") is not None]
        return round(sum(positions) / len(positions), 2) if positions else None
    return round(
        sum(float(row.get("position") or 0) * float(row.get("impressions") or 0) for row in rows) / total_impressions,
        2,
    )


def host_for_page(page: str | None) -> str:
    if not page:
        return "unknown"
    match = re.match(r"https?://([^/]+)", page)
    if not match:
        return "unknown"
    return match.group(1).removeprefix("www.")


def display_number(value: float | int | None) -> int | float:
    if value is None:
        return 0
    value = float(value)
    if value.is_integer():
        return int(value)
    return round(value, 2)


def read_adc(path: Path) -> dict[str, Any]:
    if not path.exists():
        raise FileNotFoundError(
            f"Google ADC file not found at {path}. Run: gcloud auth application-default login "
            "--scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform"
        )
    data = json.loads(path.read_text(encoding="utf-8"))
[redacted secret-like line]
    missing = required - set(data)
    if missing:
        raise ValueError(f"ADC file is missing {', '.join(sorted(missing))}")
    return data


def http_json(url: str, method: str = "GET", headers: dict[str, str] | None = None, payload: Any = None) -> dict[str, Any]:
    data = None
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
    req = Request(
        url,
        data=data,
        method=method,
        headers={
            "Accept": "application/json",
            "Content-Type": "application/json",
            "User-Agent": "CopeCheckSearchImporter/1.0",
            **(headers or {}),
        },
    )
    try:
        with urlopen(req, timeout=60) as response:
            body = response.read().decode("utf-8")
            return json.loads(body) if body else {}
    except HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP {exc.code} from {url}: {body}") from exc
    except URLError as exc:
        raise RuntimeError(f"Network error for {url}: {exc}") from exc


def quota_project(adc_path: Path) -> str | None:
    try:
        data = read_adc(adc_path)
    except Exception:
        return None
    return data.get("quota_project_id")


[redacted secret-like line]
[redacted secret-like line]
    if quota_project_id:
        headers["X-Goog-User-Project"] = quota_project_id
    return headers


[redacted secret-like line]
    adc = read_adc(adc_path)
    payload = {
        "client_id": adc["client_id"],
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    }
    req = Request(
[redacted secret-like line]
        data="&".join(f"{quote(str(k))}={quote(str(v))}" for k, v in payload.items()).encode("utf-8"),
        method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    try:
        with urlopen(req, timeout=30) as response:
[redacted secret-like line]
    except HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"OAuth refresh failed: HTTP {exc.code}: {body}") from exc
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]


[redacted secret-like line]
[redacted secret-like line]
    return body.get("siteEntry") or []


def query_search_console(
[redacted secret-like line]
    quota_project_id: str | None,
    site_url: str,
    start_date: str,
    end_date: str,
    dimensions: list[str],
    search_type: str = "web",
    row_limit: int = 25000,
    max_rows: int = 50000,
) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    start_row = 0
    encoded_site = quote(site_url, safe="")
    endpoint = f"{API_ROOT}/sites/{encoded_site}/searchAnalytics/query"
    while start_row < max_rows:
        payload = {
            "startDate": start_date,
            "endDate": end_date,
            "dimensions": dimensions,
            "type": search_type,
            "rowLimit": min(row_limit, max_rows - start_row),
            "startRow": start_row,
            "dataState": "final",
        }
        body = http_json(
            endpoint,
            method="POST",
[redacted secret-like line]
            payload=payload,
        )
        batch = body.get("rows") or []
        for row in batch:
            keys = row.get("keys") or []
            mapped = {
                "site_url": site_url,
                "search_type": search_type,
                "dimensions": ",".join(dimensions),
                "start_date": start_date,
                "end_date": end_date,
                "clicks": float(row.get("clicks") or 0),
                "impressions": float(row.get("impressions") or 0),
                "ctr": float(row.get("ctr") or 0),
                "position": float(row.get("position") or 0),
            }
            for index, dimension in enumerate(dimensions):
                mapped[dimension] = keys[index] if index < len(keys) else None
            rows.append(mapped)
        if len(batch) < row_limit:
            break
        start_row += row_limit
        time.sleep(0.2)
    return rows


def init_db(db_path: Path) -> sqlite3.Connection:
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(db_path)
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS gsc_rows (
          site_url TEXT NOT NULL,
          search_type TEXT NOT NULL,
          dimensions TEXT NOT NULL,
          start_date TEXT NOT NULL,
          end_date TEXT NOT NULL,
          date TEXT,
          query TEXT,
          page TEXT,
          country TEXT,
          device TEXT,
          clicks REAL NOT NULL DEFAULT 0,
          impressions REAL NOT NULL DEFAULT 0,
          ctr REAL NOT NULL DEFAULT 0,
          position REAL NOT NULL DEFAULT 0,
          fetched_at TEXT NOT NULL,
          PRIMARY KEY (
            site_url, search_type, dimensions, start_date, end_date,
            date, query, page, country, device
          )
        )
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS gsc_query_seen (
          site_url TEXT NOT NULL,
          query TEXT NOT NULL,
          first_seen TEXT NOT NULL,
          last_seen TEXT NOT NULL,
          last_clicks REAL NOT NULL DEFAULT 0,
          last_impressions REAL NOT NULL DEFAULT 0,
          PRIMARY KEY (site_url, query)
        )
        """
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_gsc_rows_page ON gsc_rows(page)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_gsc_rows_query ON gsc_rows(query)")
    return conn


def store_rows(conn: sqlite3.Connection, rows: list[dict[str, Any]], fetched_at: str) -> None:
    for row in rows:
        conn.execute(
            """
            INSERT OR REPLACE INTO gsc_rows (
              site_url, search_type, dimensions, start_date, end_date,
              date, query, page, country, device,
              clicks, impressions, ctr, position, fetched_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                row.get("site_url"),
                row.get("search_type"),
                row.get("dimensions"),
                row.get("start_date"),
                row.get("end_date"),
                row.get("date"),
                row.get("query"),
                row.get("page"),
                row.get("country"),
                row.get("device"),
                row.get("clicks") or 0,
                row.get("impressions") or 0,
                row.get("ctr") or 0,
                row.get("position") or 0,
                fetched_at,
            ),
        )
    query_rows = [row for row in rows if row.get("dimensions") == "query" and row.get("query")]
    for row in query_rows:
        existing = conn.execute(
            "SELECT first_seen FROM gsc_query_seen WHERE site_url = ? AND query = ?",
            (row["site_url"], row["query"]),
        ).fetchone()
        first_seen = existing[0] if existing else fetched_at
        conn.execute(
            """
            INSERT OR REPLACE INTO gsc_query_seen (
              site_url, query, first_seen, last_seen, last_clicks, last_impressions
            ) VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                row["site_url"],
                row["query"],
                first_seen,
                fetched_at,
                row.get("clicks") or 0,
                row.get("impressions") or 0,
            ),
        )
    conn.commit()


def aggregate_properties(page_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for row in page_rows:
        grouped[host_for_page(row.get("page"))].append(row)
    properties = []
    for host, rows in grouped.items():
        clicks = sum(float(row.get("clicks") or 0) for row in rows)
        impressions = sum(float(row.get("impressions") or 0) for row in rows)
        queries_seen = set()
        properties.append(
            {
                "property": host,
                "clicks": display_number(clicks),
                "impressions": display_number(impressions),
                "ctr": normalize_ctr(clicks / impressions if impressions else 0),
                "position": weighted_position(rows),
                "pages_seen": len({row.get("page") for row in rows if row.get("page")}),
                "queries_seen": len(queries_seen),
            }
        )
    properties.sort(key=lambda item: (item["impressions"], item["clicks"]), reverse=True)
    return properties[:PUBLIC_PROPERTY_LIMIT]


def public_rows(rows: list[dict[str, Any]], dimension: str, limit: int) -> list[dict[str, Any]]:
    filtered = [row for row in rows if row.get(dimension)]
    filtered.sort(key=lambda row: (float(row.get("impressions") or 0), float(row.get("clicks") or 0)), reverse=True)
    public = []
    for row in filtered[:limit]:
        clicks = float(row.get("clicks") or 0)
        impressions = float(row.get("impressions") or 0)
        item = {
            dimension: row.get(dimension),
            "clicks": display_number(clicks),
            "impressions": display_number(impressions),
            "ctr": normalize_ctr(clicks / impressions if impressions else 0),
            "position": display_number(row.get("position")),
        }
        if dimension == "page":
            item["host"] = host_for_page(row.get("page"))
        public.append(item)
    return public


def daily_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        if row.get("date"):
            grouped[str(row["date"])].append(row)
    daily = []
    for day, day_rows in grouped.items():
        clicks = sum(float(row.get("clicks") or 0) for row in day_rows)
        impressions = sum(float(row.get("impressions") or 0) for row in day_rows)
        daily.append(
            {
                "date": day,
                "clicks": display_number(clicks),
                "impressions": display_number(impressions),
                "ctr": normalize_ctr(clicks / impressions if impressions else 0),
                "position": weighted_position(day_rows),
            }
        )
    daily.sort(key=lambda row: row["date"])
    return daily


def opportunity_rows(page_rows: list[dict[str, Any]], limit: int = 16) -> list[dict[str, Any]]:
    rows = [
        row
        for row in page_rows
        if float(row.get("impressions") or 0) > 0 and float(row.get("clicks") or 0) == 0
    ]
    rows.sort(key=lambda row: float(row.get("impressions") or 0), reverse=True)
    return [
        {
            "page": row.get("page"),
            "host": host_for_page(row.get("page")),
            "impressions": display_number(row.get("impressions")),
            "position": display_number(row.get("position")),
        }
        for row in rows[:limit]
    ]


def new_queries(conn: sqlite3.Connection, since_days: int = 7, limit: int = 16) -> list[dict[str, Any]]:
    cutoff = datetime.now(timezone.utc) - timedelta(days=since_days)
    rows = conn.execute(
        """
        SELECT query, site_url, first_seen, last_impressions, last_clicks
        FROM gsc_query_seen
        WHERE first_seen >= ?
        ORDER BY last_impressions DESC, last_clicks DESC
        LIMIT ?
        """,
        (cutoff.isoformat().replace("+00:00", "Z"), limit),
    ).fetchall()
    return [
        {
            "query": row[0],
            "site_url": row[1],
            "first_seen": row[2],
            "impressions": display_number(row[3]),
            "clicks": display_number(row[4]),
        }
        for row in rows
    ]


def build_snapshot(
    conn: sqlite3.Connection,
    site_urls: list[str],
    start_date: str,
    end_date: str,
    fetched_at: str,
    all_rows: list[dict[str, Any]],
    errors: list[dict[str, str]],
) -> dict[str, Any]:
    date_rows = [row for row in all_rows if row.get("dimensions") == "date"]
    query_rows = [row for row in all_rows if row.get("dimensions") == "query"]
    page_rows = [row for row in all_rows if row.get("dimensions") == "page"]
    clicks = sum(float(row.get("clicks") or 0) for row in date_rows) or sum(
        float(row.get("clicks") or 0) for row in page_rows
    )
    impressions = sum(float(row.get("impressions") or 0) for row in date_rows) or sum(
        float(row.get("impressions") or 0) for row in page_rows
    )
    snapshot = {
        "status": "connected" if all_rows else "connected_no_rows",
        "updated_at": fetched_at,
        "range": {"start": start_date, "end": end_date},
        "site_urls": site_urls,
        "totals": {
            "clicks": display_number(clicks),
            "impressions": display_number(impressions),
            "ctr": normalize_ctr(clicks / impressions if impressions else 0),
            "position": weighted_position(page_rows or date_rows),
        },
        "daily": daily_rows(date_rows),
        "properties": aggregate_properties(page_rows),
        "queries": public_rows(query_rows, "query", PUBLIC_QUERY_LIMIT),
        "pages": public_rows(page_rows, "page", PUBLIC_PAGE_LIMIT),
        "opportunities": opportunity_rows(page_rows),
        "new_queries": new_queries(conn),
        "errors": errors,
        "note": "Search Console API export via the CopeCheck lightweight importer. Public data is summarized from local SQLite, not queried live on page load.",
    }
    return snapshot


def write_json_atomic(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    tmp.replace(path)


def push_snapshot(snapshot_path: Path, remote: str) -> None:
    if not remote:
        return
    subprocess.run(["scp", str(snapshot_path), remote], check=True)


def run_import(args: argparse.Namespace) -> dict[str, Any]:
    fetched_at = utc_now()
    end = date.today() - timedelta(days=args.delay_days)
    start = end - timedelta(days=args.days - 1)
    start_date = iso_day(start)
    end_date = iso_day(end)
    site_urls = args.site_url or DEFAULT_SITE_URLS
[redacted secret-like line]
    quota_project_id = quota_project(Path(args.adc))
    conn = init_db(Path(args.db))
    all_rows: list[dict[str, Any]] = []
    errors: list[dict[str, str]] = []
    for site_url in site_urls:
        for search_type in SEARCH_TYPES:
            for dimensions in QUERY_DIMENSIONS:
                try:
                    rows = query_search_console(
[redacted secret-like line]
                        quota_project_id=quota_project_id,
                        site_url=site_url,
                        start_date=start_date,
                        end_date=end_date,
                        dimensions=dimensions,
                        search_type=search_type,
                        max_rows=args.max_rows,
                    )
                except Exception as exc:
                    errors.append(
                        {
                            "site_url": site_url,
                            "dimensions": ",".join(dimensions),
                            "error": str(exc)[:700],
                        }
                    )
                    continue
                all_rows.extend(rows)
                store_rows(conn, rows, fetched_at)
    snapshot = build_snapshot(conn, site_urls, start_date, end_date, fetched_at, all_rows, errors)
    write_json_atomic(Path(args.snapshot), snapshot)
    if args.push:
        push_snapshot(Path(args.snapshot), args.push)
    return snapshot


def write_error_snapshot(snapshot_path: Path, error: str) -> None:
    write_json_atomic(
        snapshot_path,
        {
            "status": "auth_or_import_error",
            "updated_at": utc_now(),
            "totals": {"clicks": 0, "impressions": 0, "ctr": 0, "position": None},
            "properties": [],
            "queries": [],
            "pages": [],
            "opportunities": [],
            "new_queries": [],
            "errors": [{"error": error[:1200]}],
            "note": "Search Console import is configured but needs a valid authorised Google account with access to the CopeCheck property.",
        },
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Import Google Search Console data for seo.copecheck.com")
    parser.add_argument("--adc", default=str(DEFAULT_ADC), help="Google ADC JSON path")
    parser.add_argument("--db", default=str(DEFAULT_DB), help="SQLite database path")
    parser.add_argument("--snapshot", default=str(DEFAULT_SNAPSHOT), help="Public snapshot JSON path")
    parser.add_argument("--site-url", action="append", help="Search Console property, e.g. sc-domain:copecheck.com")
    parser.add_argument("--days", type=int, default=28, help="Number of days to import")
    parser.add_argument("--delay-days", type=int, default=2, help="Delay because GSC data is not same-day")
    parser.add_argument("--max-rows", type=int, default=50000, help="Maximum rows per dimension query")
    parser.add_argument("--push", default="", help="Optional scp target for public snapshot")
    parser.add_argument("--list-sites", action="store_true", help="List accessible Search Console properties")
    parser.add_argument("--write-error-snapshot", action="store_true", help="Write public error snapshot on failure")
    args = parser.parse_args()

    try:
[redacted secret-like line]
        quota_project_id = quota_project(Path(args.adc))
        if args.list_sites:
[redacted secret-like line]
            print(json.dumps({"ok": True, "sites": sites}, ensure_ascii=False, indent=2))
            return
        snapshot = run_import(args)
    except Exception as exc:
        if args.write_error_snapshot:
            write_error_snapshot(Path(args.snapshot), f"{type(exc).__name__}: {exc}")
            if args.push:
                push_snapshot(Path(args.snapshot), args.push)
        print(json.dumps({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, ensure_ascii=False), file=sys.stderr)
        raise SystemExit(1)

    print(
        json.dumps(
            {
                "ok": True,
                "updated_at": snapshot["updated_at"],
                "range": snapshot.get("range"),
                "totals": snapshot.get("totals"),
                "properties": len(snapshot.get("properties") or []),
                "queries": len(snapshot.get("queries") or []),
                "pages": len(snapshot.get("pages") or []),
                "errors": snapshot.get("errors") or [],
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
```
