SPB Git

Repository Public

reprobe.py 10.9 KB 281 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.py11# Description      : Re-sondage agressif pour augmenter le nombre de boutiques12#                    connectables.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1216# Last Modified    : 2026-08-1217#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"""Re-sondage agressif pour augmenter le nombre de boutiques connectables.9192Phase A — boutiques actives SANS endpoint catalogue : re-tester directement les934 endpoints (Shopify products.json via curl, WooCommerce Store API, Wix94access-tokens + app Stores, Squarespace ?format=json), même si la plateforme95détectée est « unknown/wordpress » (thèmes headless, signatures manquées).9697Phase B — candidats INACTIFS (sites « morts ») : nouvelle tentative directe,98puis via Scrapfly (asp anti-bot) — beaucoup de « morts » sont en fait des murs99anti-bot qui bloquent python-requests.100101Met à jour data/verify_cache/<domain>.json ; relancer ensuite102build_registry.py puis sync.103"""104import concurrent.futures as cf105import json106import os107import re108import subprocess109import sys110import time111112import requests113114ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))115sys.path.insert(0, os.path.join(ROOT, "scripts"))116sys.path.insert(0, ROOT)117CACHE = os.path.join(ROOT, "data", "verify_cache")118119# .env120for line in open(os.path.join(ROOT, ".env")).read().splitlines():121    if "=" in line and not line.startswith("#"):122        k, _, v = line.partition("=")123        os.environ.setdefault(k.strip(), v.strip())124125from verify import detect_platform, MADE_RE, POSTAL_RE, AREA_RE, QC_WORD_RE, CART_RE, SOCIAL_RE, HDRS  # noqa: E402126from fabrika.connectors.scrapfly import scrapfly_get, available  # noqa: E402127128WIX_STORES_APP = "1380b703-ce81-ff05-f115-39571d94dfcd"129130131def curl_get(url, timeout=20):132    p = subprocess.run(["curl", "-sS", "-L", "--compressed", "--max-time", str(timeout),133                        "-A", HDRS["User-Agent"].split(" FabriKaBot")[0],134                        "-w", "\n%{http_code}", url],135                       capture_output=True, text=True, errors="replace")136    body, _, code = p.stdout.rpartition("\n")137    return (int(code) if code.isdigit() else 0), body138139140def probe_endpoints(domain):141    """Teste tous les endpoints catalogue ; retourne (platform, endpoint) ou (None, None)."""142    base = f"https://{domain}"143    # Shopify (via curl : la moitié des blocages TLS disparaissent)144    code, body = curl_get(f"{base}/products.json?limit=1")145    if code == 200 and body.lstrip().startswith("{") and '"products"' in body[:200]:146        return "shopify", "/products.json"147    # WooCommerce Store API148    try:149        r = requests.get(f"{base}/wp-json/wc/store/v1/products?per_page=1", headers=HDRS, timeout=15)150        if r.status_code == 200 and r.text.strip().startswith("["):151            return "woocommerce", "/wp-json/wc/store/v1/products"152    except Exception:153        pass154    # Wix Stores155    try:156        r = requests.get(f"{base}/_api/v1/access-tokens", headers=HDRS, timeout=15, allow_redirects=True)157        if r.status_code == 200 and WIX_STORES_APP in (r.text or ""):158            return "wix", "/_api/wix-ecommerce-storefront-web/api"159    except Exception:160        pass161    # Squarespace162    for path in ("/shop", "/boutique", "/store"):163        try:164            r = requests.get(f"{base}{path}?format=json-pretty", headers=HDRS, timeout=12)165            if r.status_code == 200 and '"items"' in r.text[:5000]:166                return "squarespace", path + "?format=json"167        except Exception:168            pass169    return None, None170171172def phase_a():173    reg = json.load(open(os.path.join(ROOT, "data", "stores.json")))["stores"]174    targets = [s["id"] for s in reg if not s.get("catalog_endpoint")]175    print(f"[A] {len(targets)} boutiques actives sans endpoint — re-sondage direct")176    found = 0177178    def work(dom):179        plat, ep = probe_endpoints(dom)180        if not ep:181            return None182        cpath = os.path.join(CACHE, dom + ".json")183        try:184            rec = json.load(open(cpath))185        except Exception:186            rec = {"domain": dom, "active": True, "final_domain": dom}187        rec["platform"] = plat188        rec["catalog_endpoint"] = ep189        json.dump(rec, open(cpath, "w"))190        return dom, plat191192    with cf.ThreadPoolExecutor(12) as ex:193        for res in ex.map(work, targets):194            if res:195                found += 1196                print(f"  + {res[0]} -> {res[1]}", flush=True)197    print(f"[A] nouveaux connectables: {found}")198199200def build_record_from_html(domain, status, final_url, html):201    text = html[:400000]202    title = re.search(r"<title[^>]*>(.*?)</title>", text, re.S | re.I)203    rec = {204        "domain": domain, "checked_at": time.strftime("%Y-%m-%d"), "status": status,205        "final_url": final_url or f"https://{domain}", "active": True,206        "final_domain": domain,207        "title": re.sub(r"\s+", " ", title.group(1)).strip()[:200] if title else "",208        "platform": detect_platform(text, {}),209        "catalog_endpoint": None, "catalog_count_hint": None,210        "has_cart": bool(CART_RE.search(text)),211        "made_in_qc_wording": bool(MADE_RE.search(text)),212        "qc_postal": (POSTAL_RE.search(text) or [None]) and (POSTAL_RE.search(text).group(0) if POSTAL_RE.search(text) else None),213        "qc_phone": AREA_RE.search(text).group(0) if AREA_RE.search(text) else None,214        "mentions_quebec": bool(QC_WORD_RE.search(text)),215        "tld_quebec": domain.endswith(".quebec") or domain.endswith(".qc.ca"),216        "socials": list(dict.fromkeys(SOCIAL_RE.findall(text)))[:4],217        "language": None, "via": "scrapfly",218    }219    return rec220221222def phase_b(limit=None):223    if not available():224        print("[B] SCRAPFLY_API_KEY manquant — phase B sautée")225        return226    cands = [json.loads(l)["domain"] for l in open(os.path.join(ROOT, "data", "enriched", "candidates.jsonl"))]227    dead = []228    for dom in cands:229        cpath = os.path.join(CACHE, dom + ".json")230        try:231            rec = json.load(open(cpath))232            if not rec.get("active"):233                dead.append(dom)234        except Exception:235            dead.append(dom)236    if limit:237        dead = dead[:limit]238    print(f"[B] {len(dead)} candidats inactifs — retentative directe puis Scrapfly")239    revived = 0240241    def work(dom):242        # 1) direct rapide (les échecs transitoires)243        try:244            r = requests.get(f"https://{dom}", headers=HDRS, timeout=12, allow_redirects=True)245            if r.status_code == 200 and len(r.text) > 2000:246                return dom, 200, r.url, r.text, "direct"247        except Exception:248            pass249        # 2) scrapfly anti-bot250        try:251            status, content = scrapfly_get(f"https://{dom}")252            if status == 200 and len(content) > 2000:253                return dom, 200, f"https://{dom}", content, "scrapfly"254        except Exception:255            pass256        return None257258    with cf.ThreadPoolExecutor(6) as ex:259        for res in ex.map(work, dead):260            if not res:261                continue262            dom, status, final_url, html, via = res263            rec = build_record_from_html(dom, status, final_url, html)264            rec["via"] = via265            # sonde les endpoints catalogue dans la foulée266            plat, ep = probe_endpoints(dom)267            if ep:268                rec["platform"], rec["catalog_endpoint"] = plat, ep269            json.dump(rec, open(os.path.join(CACHE, dom + ".json"), "w"))270            revived += 1271            print(f"  ✚ {dom} (via {via}, plat={rec['platform'] or '-'}, ep={rec['catalog_endpoint'] or '-'})", flush=True)272    print(f"[B] ressuscités: {revived}/{len(dead)}")273274275if __name__ == "__main__":276    what = sys.argv[1] if len(sys.argv) > 1 else "ab"277    if "a" in what:278        phase_a()279    if "b" in what:280        phase_b()281
Files main
Menu

Theme