SPB Git

Repository Public

reprobe_stores.py 14.8 KB 377 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Fabri·Ka10# File             : scripts/reprobe_stores.py11# Description      : Vague 2 — re-sondage des boutiques à 0 produit (enabled=012#                    ou plateforme vide).13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1816# Last Modified    : 2026-08-2417#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Vague 2 — re-sondage des boutiques à 0 produit (enabled=0 ou plateforme vide).9192Beaucoup de boutiques ont migré de plateforme depuis la découverte initiale93(ex. WordPress vitrine -> Shopify, Wix -> WooCommerce), et les boutiques Square94Online sont maintenant connectables (connecteur square.py, vague 2). Pour95chaque cible :9697  1. sondes légères d'endpoints catalogue :98       Shopify        /products.json?limit=1              (curl, throttle 0,7 s global)99       WooCommerce    /wp-json/wc/store/v1/products100       Wix Stores     /_api/v1/access-tokens (app Stores)101       Squarespace    /shop|/boutique|/store ?format=json102       Square Online  user_id/site_id du HTML + /app/store/api/v13 (total>0)103  2. sinon, détection de plateforme via le HTML d'accueil (signatures/generator)104     — plateforme notée mais boutique laissée désactivée (pas d'endpoint).105106Met à jour : data/stores.json (platform/catalog_endpoint/enabled/ecommerce),107data/verify_cache/<dom>.json, data/enriched/verified.jsonl (patch des domaines108touchés) et la table stores (upsert). Additif : ne touche jamais aux boutiques109déjà actives.110111Usage : python3 scripts/reprobe_stores.py [--cap 400] [--dry-run]112"""113import argparse114import concurrent.futures as cf115import json116import os117import subprocess118import sys119import threading120import time121122import requests123124ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))125sys.path.insert(0, ROOT)126sys.path.insert(0, os.path.join(ROOT, "scripts"))127CACHE = os.path.join(ROOT, "data", "verify_cache")128os.makedirs(CACHE, exist_ok=True)129130for line in open(os.path.join(ROOT, ".env")).read().splitlines():131    if "=" in line and not line.startswith("#"):132        k, _, v = line.partition("=")133        os.environ.setdefault(k.strip(), v.strip())134135from verify import detect_platform, HDRS  # noqa: E402136from fabrika import db as fdb  # noqa: E402137from fabrika.connectors.square import extract_ids, API_PATH as SQUARE_API  # noqa: E402138139WIX_STORES_APP = "1380b703-ce81-ff05-f115-39571d94dfcd"140141# throttle global Shopify (même règle que le connecteur : 0,7 s entre requêtes)142_SHOPIFY_LOCK = threading.Lock()143_last_shopify = [0.0]144145STEP_DELAY = 0.5   # politesse entre sondes sur un même domaine146147148def curl_get(url, timeout=15):149    p = subprocess.run(["curl", "-sS", "-L", "--compressed", "--max-time", str(timeout),150                        "-A", HDRS["User-Agent"].split(" FabriKaBot")[0],151                        "-w", "\n%{http_code}", url],152                       capture_output=True, text=True, errors="replace")153    body, _, code = p.stdout.rpartition("\n")154    return (int(code) if code.isdigit() else 0), body155156157def probe_shopify(base):158    with _SHOPIFY_LOCK:159        wait = 0.7 - (time.time() - _last_shopify[0])160        if wait > 0:161            time.sleep(wait)162        _last_shopify[0] = time.time()163    code, body = curl_get(f"{base}/products.json?limit=1")164    if code == 200 and body.lstrip().startswith("{") and '"products"' in body[:200]:165        return "shopify", "/products.json"166    return None167168169def probe_woo(base):170    try:171        r = requests.get(f"{base}/wp-json/wc/store/v1/products?per_page=1",172                         headers=HDRS, timeout=12)173        if r.status_code == 200 and r.text.strip().startswith("["):174            return "woocommerce", "/wp-json/wc/store/v1/products"175    except Exception:176        pass177    return None178179180def probe_wix(base):181    try:182        r = requests.get(f"{base}/_api/v1/access-tokens", headers=HDRS,183                         timeout=12, allow_redirects=True)184        if r.status_code == 200 and WIX_STORES_APP in (r.text or ""):185            return "wix", "/_api/wix-ecommerce-storefront-web/api"186    except Exception:187        pass188    return None189190191def probe_squarespace(base):192    for path in ("/shop", "/boutique", "/store"):193        try:194            r = requests.get(f"{base}{path}?format=json-pretty", headers=HDRS, timeout=10)195            if r.status_code == 200 and '"items"' in r.text[:5000]:196                return "squarespace", path + "?format=json"197        except Exception:198            pass199    return None200201202def probe_square(base, html):203    """html d'accueil déjà téléchargé (peut être vide -> re-fetch)."""204    if not html:205        try:206            r = requests.get(base, headers=HDRS, timeout=15, allow_redirects=True)207            html = r.text if r.status_code == 200 else ""208        except Exception:209            return None210    user, site = extract_ids(html or "")211    if not (user and site):212        return None213    try:214        r = requests.get(f"{base}{SQUARE_API}/editor/users/{user}/sites/{site}"215                         f"/products?page=1&per_page=1", headers=HDRS, timeout=15)216        if r.status_code == 200:217            data = r.json()218            total = ((data.get("meta") or {}).get("pagination") or {}).get("total", 0)219            if total and int(total) > 0:220                return "square", SQUARE_API221    except Exception:222        pass223    return None224225226def probe_store(store):227    """Retourne (store_id, platform, endpoint, detected_platform) — endpoint None si rien."""228    sid = store["id"]229    base = (store.get("url") or f"https://{sid}").rstrip("/")230    homepage = ""231    try:232        r = requests.get(base, headers=HDRS, timeout=15, allow_redirects=True)233        if r.status_code == 200:234            homepage = r.text235    except Exception:236        pass237238    hint = (store.get("platform") or "").lower()239    detected = detect_platform(homepage[:400000], {}) if homepage else None240241    # ordre des sondes : plateforme connue/détectée d'abord, puis le reste242    order = ["shopify", "woocommerce", "wix", "squarespace", "square"]243    for pref in (hint, detected):244        if pref in order:245            order.remove(pref)246            order.insert(0, pref)247248    probes = {"shopify": lambda: probe_shopify(base),249              "woocommerce": lambda: probe_woo(base),250              "wix": lambda: probe_wix(base),251              "squarespace": lambda: probe_squarespace(base),252              "square": lambda: probe_square(base, homepage)}253    for i, name in enumerate(order):254        if i:255            time.sleep(STEP_DELAY)256        res = probes[name]()257        if res:258            return sid, res[0], res[1], detected259    return sid, None, None, detected260261262def main():263    ap = argparse.ArgumentParser()264    ap.add_argument("--cap", type=int, default=400)265    ap.add_argument("--skip", type=int, default=0,266                    help="saute les N premières cibles (déjà sondées par une vague précédente)")267    ap.add_argument("--skip-stamped", action="store_true",268                    help="ignore les boutiques portant déjà un last_reprobe")269    ap.add_argument("--only-file", default=None,270                    help="restreint les cibles aux ids listés dans ce fichier (un par ligne)")271    ap.add_argument("--workers", type=int, default=8)272    ap.add_argument("--dry-run", action="store_true")273    args = ap.parse_args()274275    reg_path = os.path.join(ROOT, "data", "stores.json")276    reg = json.load(open(reg_path))277    by_id = {s["id"]: s for s in reg["stores"]}278    targets = [s for s in reg["stores"]279               if not s.get("enabled", True) or not s.get("platform")]280    # faux positifs de découverte avérés (origin_confidence 0, ex. entreprises de281    # services sans boutique) : ne jamais les réactiver par simple sonde d'endpoint282    targets = [s for s in targets if (s.get("origin_confidence") or 0) > 0]283    if args.skip_stamped:284        targets = [s for s in targets if not s.get("last_reprobe")]285    if args.only_file:286        only = {line.strip() for line in open(args.only_file) if line.strip()}287        targets = [s for s in targets if s["id"] in only]288289    # priorité : Square (nouveau connecteur), puis origin_class A, B, …290    def key(s):291        plat_rank = 0 if (s.get("platform") or "") == "square" else 1292        return (plat_rank, s.get("origin_class") or "E", s["id"])293    targets.sort(key=key)294    targets = targets[args.skip:args.skip + args.cap]295    print(f"[reprobe] {len(targets)} boutiques ciblées (skip {args.skip}, cap {args.cap})", flush=True)296297    reactivated, platform_notes = [], []298    with cf.ThreadPoolExecutor(args.workers) as ex:299        for sid, plat, ep, detected in ex.map(probe_store, targets):300            if ep:301                reactivated.append((sid, plat, ep))302                print(f"  + {sid} -> {plat} {ep}", flush=True)303            elif detected and detected != (by_id[sid].get("platform") or ""):304                platform_notes.append((sid, detected))305306    if args.dry_run:307        print(f"[dry-run] réactivables: {len(reactivated)}, plateformes corrigées: {len(platform_notes)}")308        return309310    # 1) stores.json311    stamp = time.strftime("%Y-%m-%d")312    for s in targets:                      # trace de sondage (pour les vagues suivantes)313        by_id[s["id"]]["last_reprobe"] = stamp314    touched = set()315    for sid, plat, ep in reactivated:316        s = by_id[sid]317        s["platform"], s["catalog_endpoint"] = plat, ep318        s["enabled"], s["ecommerce"] = True, True319        touched.add(sid)320    for sid, detected in platform_notes:321        by_id[sid]["platform"] = detected      # info seulement, reste désactivée322        touched.add(sid)323    json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)324325    # 2) verify_cache (durabilité pour les rebuilds du registre)326    for sid in touched:327        s = by_id[sid]328        cpath = os.path.join(CACHE, sid + ".json")329        try:330            rec = json.load(open(cpath))331        except Exception:332            rec = {"domain": sid, "active": True, "final_domain": sid}333        rec["platform"] = s.get("platform") or rec.get("platform")334        rec["catalog_endpoint"] = s.get("catalog_endpoint") or rec.get("catalog_endpoint")335        rec["active"] = True336        json.dump(rec, open(cpath, "w"))337338    # 3) verified.jsonl — patch des domaines touchés339    vpath = os.path.join(ROOT, "data", "enriched", "verified.jsonl")340    if os.path.exists(vpath):341        lines = []342        for line in open(vpath):343            try:344                rec = json.loads(line)345            except Exception:346                lines.append(line.rstrip("\n"))347                continue348            if rec.get("domain") in touched or rec.get("final_domain") in touched:349                sid = rec.get("final_domain") or rec["domain"]350                if sid in by_id:351                    rec["platform"] = by_id[sid].get("platform") or rec.get("platform")352                    rec["catalog_endpoint"] = (by_id[sid].get("catalog_endpoint")353                                               or rec.get("catalog_endpoint"))354                    rec["active"] = True355            lines.append(json.dumps(rec, ensure_ascii=False))356        with open(vpath, "w") as f:357            f.write("\n".join(lines) + "\n")358359    # 4) base SQLite360    con = fdb.connect()361    for sid in touched:362        fdb.upsert_store(con, by_id[sid])363    con.commit(); con.close()364365    per_plat = {}366    for _, plat, _ in reactivated:367        per_plat[plat] = per_plat.get(plat, 0) + 1368    print(f"[reprobe] réactivées: {len(reactivated)} {json.dumps(per_plat, ensure_ascii=False)}"369          f" | plateformes corrigées (sans endpoint): {len(platform_notes)}")370    if reactivated:371        print("[reprobe] à synchroniser : python run.py sync "372              + " ".join(sid for sid, _, _ in reactivated[:50]) + (" …" if len(reactivated) > 50 else ""))373374375if __name__ == "__main__":376    main()377
Files main
Menu

Theme