SPB Git

Repository Public

gen_connector_docs.py 28.3 KB 673 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Lou·Ka10# File             : scripts/gen_connector_docs.py11# Module           : scripts12# Repository       : https://git.spboucher.ai/lou-ka13# Created          : 2026-08-1814# Last Modified    : 2026-08-2715#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : None specified (no license file in this repository)81# Maintainer       : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# -----------------------------------------------------------------------------89# Lou-Ka — Agrégateur de logements à louer (province de Québec)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# scripts/gen_connector_docs.py : documentation STANDARDISÉE des connecteurs.92#93#   Génère docs/connecteurs/INDEX.md + une fiche docs/connecteurs/<source_id>.md94#   par connecteur, de façon 100 % programmatique et rejouable, en croisant :95#     1. le registre data/sources.json (nom, url, secteurs, statut, notes) ;96#     2. l'introspection STATIQUE (ast) du code de louka/connectors/*.py :97#        classe, backend (direct / Firecrawl / Scrapfly), endpoint de base,98#        pagination, constantes de budget — sans exécuter les connecteurs ;99#     3. la BD live data/louka.db : volumétrie, complétude des champs par100#        source (SQL), dernier sync OK, cadence observée, erreurs récentes.101#102#   Usage : python3 scripts/gen_connector_docs.py       (depuis la racine)103#   À relancer après tout changement de connecteur / registre / ingestion.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import ast108import json109import re110import sqlite3111import statistics112from datetime import datetime113from pathlib import Path114115ROOT = Path(__file__).resolve().parents[1]116CONN_DIR = ROOT / "louka" / "connectors"117DOCS_DIR = ROOT / "docs" / "connecteurs"118DB_PATH = ROOT / "data" / "louka.db"119SOURCES_JSON = ROOT / "data" / "sources.json"120121SKIP_MODULES = {"__init__", "base", "_detailutil"}122URL_RE = re.compile(r"https?://[^\s\"'\\)>,;]+")123DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}")124INFRA_HOSTS = ("api.firecrawl.dev", "api.scrapfly.io", "lou-ka.com",125               "nominatim", "overpass")126127# Colonnes de `listings` documentées dans la section « Champs récupérés » :128# (colonne, libellé, condition SQL de complétude sur les annonces actives)129FIELDS = [130    ("title", "Titre de l'annonce", "title IS NOT NULL AND title != ''"),131    ("address", "Adresse civique", "address IS NOT NULL AND address != ''"),132    ("city", "Ville (normalisée)", "city IS NOT NULL AND city != ''"),133    ("sector", "Secteur / quartier", "sector IS NOT NULL AND sector != ''"),134    ("unit_type", "Type d'unité (3½, 4½…)",135     "unit_type IS NOT NULL AND unit_type != ''"),136    ("price", "Loyer mensuel ($)", "price IS NOT NULL"),137    ("bedrooms", "Chambres", "bedrooms IS NOT NULL"),138    ("bathrooms", "Salles de bain", "bathrooms IS NOT NULL"),139    ("area_sqft", "Superficie (pi²)", "area_sqft IS NOT NULL"),140    ("availability_date", "Date de disponibilité",141     "availability_date IS NOT NULL AND availability_date != ''"),142    ("lat", "GPS (lat/lng)", "lat IS NOT NULL AND lng IS NOT NULL"),143    ("description", "Description", "description IS NOT NULL AND description != ''"),144    ("images", "Photos (JSON)", "images IS NOT NULL AND length(images) > 4"),145    ("amenities", "Commodités (JSON)",146     "amenities IS NOT NULL AND length(amenities) > 4"),147    ("details", "Détails additionnels (JSON)",148     "details IS NOT NULL AND length(details) > 4"),149    ("url", "URL de l'annonce source", "url IS NOT NULL AND url != ''"),150]151152153# -- helpers de formatage ------------------------------------------------------154155def esc(s: str, limit: int = 100) -> str:156    """Échappe une valeur pour une cellule de tableau Markdown."""157    s = str(s).replace("\\", "\\\\").replace("|", "\\|")158    s = re.sub(r"\s+", " ", s).strip()159    return s[: limit - 1] + "…" if len(s) > limit else s160161162def pct(n, d) -> str:163    if not d:164        return "—"165    return f"{100.0 * (n or 0) / d:.0f} %"166167168def fmt_ts(ts) -> str:169    if not ts:170        return "—"171    return datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d %H:%M")172173174def fmt_secs(sec: float) -> str:175    if sec < 5400:176        return f"≈ {sec / 60:.0f} min"177    if sec < 129600:178        return f"≈ {sec / 3600:.1f} h"179    return f"≈ {sec / 86400:.1f} j"180181182def example_value(col: str, value) -> str:183    """Rend un exemple lisible tiré d'une ligne réelle de la BD."""184    if value is None or value == "":185        return "—"186    if col == "images":187        try:188            imgs = json.loads(value)189            if not imgs:190                return "—"191            return esc(f"{len(imgs)} photo(s) — {imgs[0]}", 90)192        except (ValueError, TypeError):193            return esc(value, 90)194    if col in ("amenities", "details"):195        return esc(value, 90)196    if col == "price":197        return f"{float(value):,.0f} $".replace(",", " ")198    if col in ("bedrooms", "bathrooms", "area_sqft"):199        v = float(value)200        return f"{v:g}"201    return esc(value, 90)202203204# -- introspection statique du code des connecteurs ----------------------------205206def banner_description(text: str, module: str) -> str:207    """Extrait la description du bandeau de commentaires en tête de module."""208    lines, started = [], False209    for raw in text.splitlines():210        if not raw.startswith("#"):211            if started or not raw.strip():212                break213            continue214        body = raw.lstrip("#").strip()215        if set(body) <= {"-", "="}:216            continue217        marker = f"connectors/{module}.py"218        if not started:219            if marker in body:220                started = True221                lines.append(body.split(":", 1)[-1].strip())222            continue223        lines.append(body)224    return " ".join(l for l in lines if l).strip()225226227def detect_backends(text: str) -> tuple[list[str], str]:228    """(liste détaillée, famille courte) des backends de fetch utilisés."""229    detailed, family = [], "direct"230    if re.search(r"self\.(get|post)\(", text):231        detailed.append("requests direct (session UA LouKaBot, throttling poli)")232    if ".scrapfly(" in text:233        detailed.append("Scrapfly (asp + render_js — contournement anti-bot)")234        family = "Scrapfly"235    if "get_rendered(" in text:236        detailed.append("Scrapfly render_js (HTML rendu, JavaScript exécuté"237                        " — ex-Firecrawl, migré 2026-08-27)")238        family = "Scrapfly" if family == "direct" else family239    if not detailed:240        detailed.append("requests direct")241    return detailed, family242243244def detect_flavor(text: str) -> str:245    low = text.lower()246    if "graphql" in low:247        return "API GraphQL interne"248    if "admin-ajax" in low:249        return "API admin-ajax (WordPress)"250    if "/wp-json" in low:251        return "API REST WordPress (wp-json)"252    if "sitemap" in low:253        return "sitemap XML + pages HTML"254    if re.search(r"\.json\(\)", text) and re.search(r"api[./_]", low):255        return "API JSON interne du site"256    return "pages HTML (rendu serveur)"257258259def detect_pagination(text: str, constants: dict) -> str:260    hits = []261    low = text.lower()262    if "js_scenario" in text:263        hits.append("défilement simulé (js_scenario Scrapfly)")264    if re.search(r"[?&]page=|[\"']page[\"']\s*[:=]|paged", low):265        hits.append("pagination par numéro de page")266    if re.search(r"[?&]offset=|[\"']offset[\"']", low):267        hits.append("pagination par offset")268    if "load_more" in low or "loadmore" in low:269        hits.append("bouton « charger plus » rejoué")270    roots = [k for k, v in constants.items()271             if isinstance(v, (list, tuple)) and len(v) > 1272             and k in ("ROOTS", "PAGES", "SECTIONS", "SECTEURS", "CITIES",273                       "REGIONS", "URLS", "LISTS")]274    if roots:275        n = len(constants[roots[0]])276        hits.append(f"multi-racines ({n} pages de départ : {roots[0]})")277    if not hits:278        hits.append("page de liste unique (pas de pagination)")279    return " ; ".join(hits)280281282def introspect_module(path: Path) -> list[dict]:283    """Retourne une entrée par classe connecteur du module (souvent 1)."""284    text = path.read_text(encoding="utf-8")285    module = path.stem286    try:287        tree = ast.parse(text)288    except SyntaxError:289        return []290291    constants: dict = {}292    for node in tree.body:293        if isinstance(node, ast.Assign) and len(node.targets) == 1 \294                and isinstance(node.targets[0], ast.Name) \295                and node.targets[0].id.isupper():296            try:297                constants[node.targets[0].id] = ast.literal_eval(node.value)298            except (ValueError, TypeError, SyntaxError):299                seg = ast.get_source_segment(text, node.value) or ""300                urls = URL_RE.findall(seg)301                constants[node.targets[0].id] = urls if len(urls) > 1 else \302                    (urls[0] if urls else None)303304    urls_all = []305    for u in URL_RE.findall(text):306        u = u.rstrip('".')307        host = u.split("//", 1)[-1].split("/", 1)[0]308        if "." not in host:      # fragment de f-string, pas une vraie URL309            continue310        if not any(h in u for h in INFRA_HOSTS) and u not in urls_all:311            urls_all.append(u)312313    endpoint = None314    for name in ("BASE", "BASE_URL", "API", "API_URL", "API_BASE", "ROOT",315                 "SITE", "URL", "LIST_URL", "HOST"):316        v = constants.get(name)317        if isinstance(v, str) and v.startswith("http"):318            endpoint = v319            break320    if not endpoint and urls_all:321        endpoint = urls_all[0]322323    budgets = {k: v for k, v in constants.items()324               if isinstance(v, (int, float)) and not isinstance(v, bool)325               and re.search(r"MAX|CAP|LIMIT|BUDGET|TTL|PER_PAGE|PAGES|DELAY", k)}326327    backends, family = detect_backends(text)328    entries = []329    for node in tree.body:330        if not isinstance(node, ast.ClassDef):331            continue332        bases = {getattr(b, "id", getattr(b, "attr", "")) for b in node.bases}333        if not (bases & {"BaseConnector"}) and not any(334                b.endswith("Connector") for b in bases if b):335            continue336        attrs = {"request_delay": 0.6, "timeout": 30, "use_detail_cache": True,337                 "disabled": False, "source_id": ""}338        for sub in node.body:339            if isinstance(sub, ast.Assign) and len(sub.targets) == 1 \340                    and isinstance(sub.targets[0], ast.Name):341                try:342                    attrs[sub.targets[0].id] = ast.literal_eval(sub.value)343                except (ValueError, TypeError, SyntaxError):344                    pass345        if not attrs.get("source_id"):346            continue347        entries.append({348            "module": module, "path": f"louka/connectors/{module}.py",349            "class": node.name, "class_doc": ast.get_docstring(node) or "",350            "banner": banner_description(text, module),351            "source_id": attrs["source_id"], "disabled": attrs["disabled"],352            "request_delay": attrs["request_delay"], "timeout": attrs["timeout"],353            "use_detail_cache": attrs["use_detail_cache"],354            "endpoint": endpoint, "urls": urls_all[:4], "budgets": budgets,355            "backends": backends, "backend_family": family,356            "flavor": detect_flavor(text),357            "pagination": detect_pagination(text, constants),358        })359    return entries360361362# -- BD live -------------------------------------------------------------------363364def db_stats(con: sqlite3.Connection, sid: str) -> dict:365    parts = ", ".join(366        f"sum(CASE WHEN active=1 AND {cond} THEN 1 ELSE 0 END) AS f_{col}"367        for col, _label, cond in FIELDS)368    row = con.execute(369        f"SELECT count(*) AS total, coalesce(sum(active),0) AS act, "370        f"min(first_seen) AS first_seen, max(last_seen) AS last_seen, {parts} "371        f"FROM listings WHERE source=?", (sid,)).fetchone()372    sample = con.execute(373        "SELECT * FROM listings WHERE source=? AND active=1 "374        "ORDER BY last_seen DESC LIMIT 1", (sid,)).fetchone()375    if sample is None:376        sample = con.execute(377            "SELECT * FROM listings WHERE source=? ORDER BY last_seen DESC "378            "LIMIT 1", (sid,)).fetchone()379380    runs = con.execute(381        "SELECT ts, ok, found, added, updated, removed, message FROM sync_log "382        "WHERE source=? ORDER BY ts DESC LIMIT 60", (sid,)).fetchall()383    ok_ts = sorted(r["ts"] for r in runs if r["ok"])384    cadence = None385    if len(ok_ts) >= 3:386        deltas = [b - a for a, b in zip(ok_ts, ok_ts[1:]) if b - a > 60]387        if deltas:388            cadence = statistics.median(deltas)389    last_ok = next((r for r in runs if r["ok"]), None)390    errors = [r for r in runs if not r["ok"]][:5]391    return {"agg": row, "sample": sample, "runs": runs, "cadence": cadence,392            "last_ok": last_ok, "errors": errors,393            "err_count": sum(1 for r in runs if not r["ok"])}394395396# -- rendu des fiches ------------------------------------------------------------397398def short_status(entry: dict, reg: list[dict]) -> str:399    if entry["disabled"]:400        return "désactivé (disabled=True)"401    status = (reg[0].get("status") or "") if reg else ""402    if status.startswith("actif (dégradé)"):403        return "actif (dégradé)"404    for p in ("actif", "suspendu", "non connectable"):405        if status.startswith(p):406            return p407    return status.split("—")[0].strip() or "actif (hors registre)"408409410def history_lines(reg: list[dict], stats: dict) -> list[str]:411    lines = []412    if stats["agg"]["first_seen"]:413        lines.append(f"- {fmt_ts(stats['agg']['first_seen'])[:10]} — premières "414                     "annonces de la source ingérées dans la BD.")415    seen = set()416    for r in reg:417        blob = " ".join(str(r.get(k, "")) for k in ("status", "notes"))418        for m in DATE_RE.finditer(blob):419            d = m.group(0)420            if d in seen:421                continue422            seen.add(d)423            ctx = blob[max(0, m.start() - 90): m.end() + 90]424            ctx = re.sub(r"\s+", " ", ctx).strip()425            lines.append(f"- {d} — mention au registre : « …{ctx}… »")426    lines.append("- 2026-08-18 — vague d'enrichissement : standardisation de la "427                 "documentation des connecteurs (fiche générée par "428                 "`scripts/gen_connector_docs.py`).")429    return lines430431432def render_fiche(entry: dict, reg: list[dict], stats: dict, now: str) -> str:433    sid = entry["source_id"]434    agg = stats["agg"]435    main = reg[0] if reg else {}436    name = main.get("name") or sid437    region = main.get("region") or "—"438    etat = short_status(entry, reg)439440    out = [f"# {name} — connecteur `{sid}`", ""]441    out.append(f"_Fiche générée automatiquement par "442               f"`scripts/gen_connector_docs.py` le {now} — ne pas éditer à la "443               f"main, régénérer._")444    out.append("")445    out.append(f"**État : {etat}** · Région : {region} · Backend : "446               f"{entry['backend_family']} · Annonces actives : "447               f"{agg['act']}/{agg['total']}")448    out.append("")449450    # -- Description ------------------------------------------------------------451    out.append("## Description de la source")452    out.append("")453    desc = entry["banner"] or entry["class_doc"].splitlines()[0] if (454        entry["banner"] or entry["class_doc"]) else ""455    if desc:456        out.append(desc)457        out.append("")458    out.append(f"- **Site** : {main.get('url', '—')}")459    out.append(f"- **Page des annonces** : {main.get('listing_url', '—')}")460    if main.get("sectors"):461        out.append(f"- **Secteurs couverts** : {main['sectors']}")462    out.append(f"- **Module** : `{entry['path']}` — classe `{entry['class']}`")463    if len(reg) > 1:464        others = ", ".join(f"`{r['id']}` ({r.get('name', '')})" for r in reg[1:])465        out.append(f"- **Entrées additionnelles du registre couvertes** : {others}")466    out.append("")467468    # -- Accès --------------------------------------------------------------------469    out.append("## Accès")470    out.append("")471    out.append(f"- **Type d'accès** : {entry['flavor']}")472    out.append(f"- **Endpoint de base** : {entry['endpoint'] or '—'}")473    if entry["urls"]:474        out.append("- **URLs de départ (constantes du module)** : "475                   + " · ".join(entry["urls"]))476    out.append("- **Authentification** : aucune — contenu public"477               + (" (clé Scrapfly côté Lou-Ka)" if entry["backend_family"] ==478                  "Scrapfly" else ""))479    out.append(f"- **Pagination** : {entry['pagination']}")480    out.append(f"- **Backend anti-bot / rendu** : {' ; '.join(entry['backends'])}")481    out.append(f"- **Politesse** : {entry['request_delay']} s entre requêtes, "482               f"timeout {entry['timeout']} s, User-Agent identifiable "483               f"`LouKaBot/1.0 (+https://www.lou-ka.com/bot)`")484    out.append("")485486    # -- Champs -------------------------------------------------------------------487    out.append("## Champs récupérés → schéma cible")488    out.append("")489    out.append(f"Le connecteur ({entry['backend_family']}, {entry['flavor']}) "490               f"alimente les colonnes de la table `listings`. Complétude "491               f"mesurée en SQL sur les {agg['act']} annonces actives ; exemple "492               f"tiré d'une ligne réelle de la BD.")493    out.append("")494    out.append("| Colonne `listings` | Contenu | Renseignée (actives) | Exemple réel |")495    out.append("|---|---|---|---|")496    sample = stats["sample"]497    for col, label, _cond in FIELDS:498        ex = example_value(col, sample[col]) if sample is not None else "—"499        out.append(f"| `{col}` | {label} | {pct(agg[f'f_{col}'], agg['act'])} "500                   f"| {ex} |")501    out.append("")502503    # -- Fréquence & budget ---------------------------------------------------------504    out.append("## Fréquence & budget")505    out.append("")506    cad = fmt_secs(stats["cadence"]) if stats["cadence"] else "—"507    out.append(f"- **Cadence observée** (médiane des passages OK, sync_log) : {cad}")508    lo = stats["last_ok"]509    if lo:510        out.append(f"- **Dernier passage OK** : {fmt_ts(lo['ts'])} — "511                   f"{lo['found'] or 0} trouvées, +{lo['added'] or 0} / "512                   f"~{lo['updated'] or 0} / -{lo['removed'] or 0}")513    else:514        out.append("- **Dernier passage OK** : aucun dans les 60 derniers runs")515    out.append(f"- **Throttling** : {entry['request_delay']} s entre requêtes "516               f"(constante de classe `request_delay`)")517    out.append(f"- **Cache des pages détail (BD `detail_cache`)** : "518               f"{'activé' if entry['use_detail_cache'] else 'désactivé'} — "519               f"évite de re-visiter les fiches inchangées")520    if entry["budgets"]:521        caps = ", ".join(f"`{k}` = {v}" for k, v in sorted(entry["budgets"].items()))522        out.append(f"- **Caps / budgets du module** : {caps}")523    out.append("")524525    # -- Volumétrie -------------------------------------------------------------------526    out.append("## Volumétrie & complétude")527    out.append("")528    out.append(f"- **Annonces en BD** : {agg['total']} au total, "529               f"**{agg['act']} actives**")530    out.append(f"- **Première ingestion** : {fmt_ts(agg['first_seen'])[:10]} · "531               f"**Dernière observation** : {fmt_ts(agg['last_seen'])[:10]}")532    out.append(f"- **Complétude clé (actives)** : GPS "533               f"{pct(agg['f_lat'], agg['act'])} · prix "534               f"{pct(agg['f_price'], agg['act'])} · photos "535               f"{pct(agg['f_images'], agg['act'])} · description "536               f"{pct(agg['f_description'], agg['act'])}")537    out.append(f"- **Runs journalisés (60 derniers)** : {len(stats['runs'])}, "538               f"dont {stats['err_count']} en erreur")539    out.append("")540541    # -- Erreurs ------------------------------------------------------------------------542    out.append("## Erreurs connues & dépannage")543    out.append("")544    if stats["errors"]:545        out.append("| Date | Message (sync_log) |")546        out.append("|---|---|")547        for r in stats["errors"]:548            out.append(f"| {fmt_ts(r['ts'])} | {esc(r['message'] or '', 160)} |")549        out.append("")550    else:551        out.append("Aucune erreur dans les 60 derniers runs journalisés.")552        out.append("")553    status = main.get("status", "")554    if status and not status.strip() == "actif":555        out.append(f"**Note du registre** : {status}")556        out.append("")557    out.append(f"Rejouer la source seule : `python3 run.py sync {sid}` · "558               f"vérifier ensuite `sync_log` (`SELECT * FROM sync_log WHERE "559               f"source='{sid}' ORDER BY ts DESC LIMIT 5;`).")560    out.append("")561562    # -- Licence ------------------------------------------------------------------------563    out.append("## Licence, attribution & conditions")564    out.append("")565    out.append("- Scraping poli d'annonces **publiques** (données factuelles : "566               "prix, adresse, disponibilité) publiées par le gestionnaire sur "567               "son propre site.")568    out.append("- User-Agent **identifiable** avec page d'information et "569               "contact : `LouKaBot/1.0 (+https://www.lou-ka.com/bot; "570               "contact@spboucher.ai)` ; throttling "571               f"{entry['request_delay']} s ; cache détail pour minimiser les "572               "requêtes.")573    out.append("- Chaque annonce affichée sur Lou-Ka **pointe vers l'annonce "574               "d'origine** (colonne `url`) — la source garde le trafic de "575               "conversion.")576    out.append("- Retrait sur demande : contact@spboucher.ai.")577    out.append("")578579    # -- Historique ----------------------------------------------------------------------580    out.append("## Historique")581    out.append("")582    out.extend(history_lines(reg, stats))583    out.append("")584    return "\n".join(out)585586587# -- programme principal -----------------------------------------------------------588589def main() -> None:590    now = datetime.now().strftime("%Y-%m-%d %H:%M")591    registry = json.loads(SOURCES_JSON.read_text(encoding="utf-8"))["sources"]592    by_connector: dict[str, list[dict]] = {}593    for r in registry:594        key = r.get("connector") or ""595        if key:596            by_connector.setdefault(key, []).append(r)597    # l'entrée dont id == connector d'abord (entrée « principale »)598    for key, lst in by_connector.items():599        lst.sort(key=lambda r: (r["id"] != key, r["id"]))600601    con = sqlite3.connect(DB_PATH)602    con.row_factory = sqlite3.Row603604    entries: list[dict] = []605    for path in sorted(CONN_DIR.glob("*.py")):606        if path.stem in SKIP_MODULES:607            continue608        entries.extend(introspect_module(path))609    entries.sort(key=lambda e: e["source_id"])610611    DOCS_DIR.mkdir(parents=True, exist_ok=True)612    for old in DOCS_DIR.glob("*.md"):613        old.unlink()614615    index_rows = []616    covered = set()617    tot_active = 0618    for entry in entries:619        sid = entry["source_id"]620        reg = by_connector.get(sid) or by_connector.get(entry["module"]) or []621        for r in reg:622            covered.add(r["id"])623        stats = db_stats(con, sid)624        (DOCS_DIR / f"{sid}.md").write_text(625            render_fiche(entry, reg, stats, now), encoding="utf-8")626        agg = stats["agg"]627        tot_active += agg["act"] or 0628        lo = stats["last_ok"]629        main_r = reg[0] if reg else {}630        index_rows.append(631            f"| [`{sid}`]({sid}.md) | {esc(main_r.get('name', sid), 40)} "632            f"| {esc(main_r.get('region', '—'), 20)} "633            f"| {esc(entry['flavor'], 34)} | {entry['backend_family']} "634            f"| {agg['act']}/{agg['total']} "635            f"| {pct(agg['f_lat'], agg['act'])} "636            f"| {pct(agg['f_price'], agg['act'])} "637            f"| {pct(agg['f_images'], agg['act'])} "638            f"| {esc(short_status(entry, reg), 26)} "639            f"| {fmt_ts(lo['ts']) if lo else '—'} |")640641    # INDEX.md ------------------------------------------------------------------642    n_act = sum(1 for e in entries if not e["disabled"])643    idx = [644        "# Lou-Ka — Index des connecteurs", "",645        f"_Généré automatiquement par `scripts/gen_connector_docs.py` le {now} "646        f"— ne pas éditer à la main, régénérer._", "",647        f"**{len(entries)} connecteurs documentés** ({n_act} activés, "648        f"{len(entries) - n_act} désactivés) · **{tot_active} annonces "649        f"actives** au total · registre : {len(registry)} entrées.", "",650        "| Connecteur | Nom | Région | Type d'accès | Backend | Actives/Total "651        "| GPS | Prix | Photos | État | Dernier sync OK |",652        "|---|---|---|---|---|---|---|---|---|---|---|",653    ]654    idx.extend(index_rows)655    leftovers = [r for r in registry if r["id"] not in covered]656    if leftovers:657        idx += ["", "## Entrées du registre sans module connecteur", "",658                "Sources recensées mais non connectées (voir le champ `status` "659                "du registre pour la raison détaillée) :", ""]660        for r in sorted(leftovers, key=lambda x: x["id"]):661            reason = esc((r.get("status") or "").split("—")[0], 60)662            idx.append(f"- `{r['id']}` — {esc(r.get('name', ''), 60)} "663                       f"({reason or '—'})")664    idx.append("")665    (DOCS_DIR / "INDEX.md").write_text("\n".join(idx), encoding="utf-8")666    con.close()667    print(f"[gen_connector_docs] {len(entries)} fiches + INDEX.md écrits dans "668          f"{DOCS_DIR}")669670671if __name__ == "__main__":672    main()673
Files main
Menu

Theme