SPB Git

Repository Public

verify.py 11.0 KB 267 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/verify.py11# Description      : Verification pipeline: probe each candidate domain.12# Module           : scripts13# Repository       : https://git.spboucher.ai/fabri-ka14# Created          : 2026-08-1215# Last Modified    : 2026-08-2816#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author           : Simon-Pierre Boucher22# Position         : Professor of Finance23# Institution      : Université du Québec en Outaouais (UQO)24# Department       : Département des sciences administratives25# Organization     : SP Boucher26#27# Website          : https://spboucher.ai28# Git              : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General          : info@spboucher.ai35# Professional     : contact@spboucher.ai36# Direct           : simon@spboucher.ai37# Research         : research@spboucher.ai38# Development      : dev@spboucher.ai39# Support          : support@spboucher.ai40# Security/Admin   : admin@spboucher.ai41# Notifications    : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification   : Public68# Distribution     : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License          : None specified (no license file in this repository)82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Verification pipeline: probe each candidate domain.9091For each domain from data/enriched/candidates.jsonl:92  - fetch homepage (https, with UA), record status + final URL93  - detect ecommerce platform + whether its public catalog endpoint responds94    (Shopify /products.json, WooCommerce /wp-json/wc/store/v1/products,95     Squarespace ?format=json)96  - detect cart/checkout signals97  - detect Quebec-location signals (postal codes GHJ, area codes, mentions)98  - detect language, social links, "made in Quebec" wording99Results cached per-domain in data/verify_cache/. Output:100data/enriched/verified.jsonl101"""102import concurrent.futures as cf103import json104import os105import re106import sys107import time108from urllib.parse import urlparse109110import requests111112ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))113CACHE = os.path.join(ROOT, "data", "verify_cache")114OUT = os.path.join(ROOT, "data", "enriched")115os.makedirs(CACHE, exist_ok=True)116117HDRS = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 FabriKaBot/1.0 (+contact@spboucher.ai)",118        "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}119120POSTAL_RE = re.compile(r"\b[GHJ]\d[A-Z]\s?\d[A-Z]\d\b")121AREA_RE = re.compile(r"\(?\b(418|514|450|819|579|581|438|873|367)\)?[\s.\-]?\d{3}[\s.\-]?\d{4}\b")122MADE_RE = re.compile(r"(?i)(fabriqu[ée]s?\s+(au|ici\s+au)\s+qu[ée]bec|fait(es)?\s+(au|ici\s+au)\s+qu[ée]bec|"123                     r"made\s+in\s+qu[ée]bec|con[çc]u\s+(et\s+fabriqu[ée]?\s+)?au\s+qu[ée]bec|"124                     r"produit\s+du\s+qu[ée]bec|fait\s+[àa]\s+la\s+main\s+au\s+qu[ée]bec|"125                     r"artisanal|fait\s+ici|100\s?%\s?qu[ée]b[ée]cois)")126QC_WORD_RE = re.compile(r"(?i)\bqu[ée]bec\b|\bqc\b")127CART_RE = re.compile(r"(?i)(add[\s_\-]?to[\s_\-]?cart|ajouter\s+au\s+panier|/cart\b|/panier\b|"128                     r"checkout|caisse|mon\s+panier|shopping[\s_\-]?cart|data-product-form)")129130SOCIAL_RE = re.compile(r'https?://(?:www\.)?(facebook\.com|instagram\.com)/[A-Za-z0-9_.\-/%]+')131132133def detect_platform(html, headers):134    h = html.lower()135    hdr = " ".join(f"{k}:{v}" for k, v in headers.items()).lower()136    if "cdn.shopify" in h or "shopify.theme" in h or "x-shopid" in hdr or "myshopify.com" in h:137        return "shopify"138    if "woocommerce" in h:139        return "woocommerce"140    if "wixstatic.com" in h or "wix.com" in h and "wixsite" in h:141        return "wix"142    if "squarespace" in h:143        return "squarespace"144    if "prestashop" in h:145        return "prestashop"146    if "bigcommerce" in h:147        return "bigcommerce"148    if "webshopapp" in h or "lightspeed" in h and "cart" in h:149        return "lightspeed"150    if "ecwid" in h:151        return "ecwid"152    if "snipcart" in h:153        return "snipcart"154    if "sumup" in h and "store" in h:155        return "sumup"156    if "square.site" in h or "squareup.com" in h and "cart" in h:157        return "square"158    if "magento" in h or "mage/cookies" in h:159        return "magento"160    if "wp-content" in h:161        return "wordpress"162    return ""163164165def probe_catalog(domain, platform, sess):166    """Check whether the public catalog endpoint responds; return (endpoint, count_hint)."""167    try:168        if platform == "shopify":169            r = sess.get(f"https://{domain}/products.json?limit=1", headers=HDRS, timeout=15)170            if r.status_code == 200 and "products" in r.text[:200]:171                return "/products.json", None172        elif platform in ("woocommerce", "wordpress"):173            r = sess.get(f"https://{domain}/wp-json/wc/store/v1/products?per_page=1", headers=HDRS, timeout=15)174            if r.status_code == 200 and r.text.strip().startswith("["):175                total = r.headers.get("X-WP-Total")176                return "/wp-json/wc/store/v1/products", int(total) if total else None177        elif platform == "squarespace":178            for path in ("/shop", "/boutique", "/store"):179                r = sess.get(f"https://{domain}{path}?format=json-pretty", headers=HDRS, timeout=15)180                if r.status_code == 200 and '"items"' in r.text[:5000]:181                    return path + "?format=json", None182    except Exception:183        pass184    return None, None185186187def verify_domain(domain):188    cpath = os.path.join(CACHE, domain + ".json")189    if os.path.exists(cpath):190        return json.load(open(cpath))191    rec = {"domain": domain, "checked_at": time.strftime("%Y-%m-%d")}192    sess = requests.Session()193    html, final_url, status = "", "", None194    for scheme_host in (f"https://{domain}", f"https://www.{domain}", f"http://{domain}"):195        try:196            r = sess.get(scheme_host, headers=HDRS, timeout=20, allow_redirects=True)197            status, final_url, html = r.status_code, r.url, r.text198            resp_headers = dict(r.headers)199            if status == 200:200                break201        except Exception as e:202            rec.setdefault("errors", []).append(str(e)[:120])203    rec["status"] = status204    rec["final_url"] = final_url205    if not html or status != 200:206        rec["active"] = False207        json.dump(rec, open(cpath, "w"))208        return rec209210    rec["active"] = True211    final_dom = urlparse(final_url).netloc.lower().removeprefix("www.")212    rec["final_domain"] = final_dom213    text = html[:400000]214    title_m = re.search(r"<title[^>]*>(.*?)</title>", text, re.S | re.I)215    rec["title"] = re.sub(r"\s+", " ", title_m.group(1)).strip()[:200] if title_m else ""216    platform = detect_platform(text, resp_headers)217    rec["platform"] = platform218    endpoint, count = probe_catalog(final_dom, platform, sess)219    rec["catalog_endpoint"] = endpoint220    rec["catalog_count_hint"] = count221    rec["has_cart"] = bool(CART_RE.search(text))222    rec["made_in_qc_wording"] = bool(MADE_RE.search(text))223    postal = POSTAL_RE.search(text)224    rec["qc_postal"] = postal.group(0) if postal else None225    area = AREA_RE.search(text)226    rec["qc_phone"] = area.group(0) if area else None227    rec["mentions_quebec"] = bool(QC_WORD_RE.search(text))228    rec["tld_quebec"] = final_dom.endswith(".quebec") or final_dom.endswith(".qc.ca")229    rec["socials"] = list(dict.fromkeys(SOCIAL_RE.findall(text)))[:4]230    fr_hits = len(re.findall(r"(?i)\b(nous|votre|panier|boutique|livraison|accueil|produits)\b", text))231    en_hits = len(re.findall(r"(?i)\b(shop|cart|shipping|home|about us|products)\b", text))232    rec["language"] = ("fr" if fr_hits >= en_hits else "en") if (fr_hits + en_hits) > 3 else None233    json.dump(rec, open(cpath, "w"))234    return rec235236237def main():238    src = sys.argv[1] if len(sys.argv) > 1 else os.path.join(OUT, "candidates.jsonl")239    domains = []240    with open(src) as f:241        for line in f:242            domains.append(json.loads(line)["domain"])243    domains = list(dict.fromkeys(domains))244    print(f"verifying {len(domains)} domains")245    results = []246    with cf.ThreadPoolExecutor(24) as ex:247        for i, rec in enumerate(ex.map(verify_domain, domains)):248            results.append(rec)249            if (i + 1) % 100 == 0:250                print(f"  {i+1}/{len(domains)}", flush=True)251    out = os.path.join(OUT, "verified.jsonl")252    with open(out, "w") as f:253        for r in results:254            f.write(json.dumps(r, ensure_ascii=False) + "\n")255    active = sum(1 for r in results if r.get("active"))256    plat = {}257    for r in results:258        if r.get("active"):259            plat[r.get("platform") or "unknown"] = plat.get(r.get("platform") or "unknown", 0) + 1260    connectable = sum(1 for r in results if r.get("catalog_endpoint"))261    print(f"active: {active}/{len(results)}  connectable-catalog: {connectable}")262    print("platforms:", json.dumps(plat, indent=1))263264265if __name__ == "__main__":266    main()267
Files main
Menu

Theme