SPB Git

Repository Public

enrich_contacts.py 11.2 KB 285 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/enrich_contacts.py11# Description      : Phase 2 — coordonnées boutiques : courriel, téléphone,12#                    réseaux sociaux.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1916# Last Modified    : 2026-08-1917#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"""Phase 2 — coordonnées boutiques : courriel, téléphone, réseaux sociaux.9192Pour chaque boutique productive sans courriel :93  1. page d'accueil : mailto:, JSON-LD Organization/LocalBusiness94     (email, telephone, sameAs), liens Instagram/Facebook du HTML ;95  2. sinon une page contact usuelle (/contact, /pages/contact,96     /nous-joindre, /contactez-nous, /pages/nous-joindre, /a-propos).9798Max 2 requêtes réseau par boutique, throttle 0,5 s par worker (Shopify :99verrou global 0,7 s comme le connecteur). Cache disque100data/enrich_cache/contacts/<dom>.json (échecs inclus).101102Écrit : stores.email, stores.phone (si vide) ; réseaux fusionnés dans le103registre (socials) sans doublon.104105Usage : .venv/bin/python scripts/enrich_contacts.py [--cap 400] [--workers 6]106"""107import argparse108import concurrent.futures as cf109import html as _html110import json111import os112import re113import sys114import threading115import time116117import requests118119ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))120sys.path.insert(0, ROOT)121CACHE = os.path.join(ROOT, "data", "enrich_cache", "contacts")122os.makedirs(CACHE, exist_ok=True)123124from fabrika import db as fdb  # noqa: E402125126HDRS = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "127                      "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",128        "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}129130CONTACT_PATHS = ["/pages/contact", "/contact", "/nous-joindre", "/contactez-nous",131                 "/pages/nous-joindre", "/pages/contactez-nous", "/contact-us"]132EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")133BAD_EMAIL = re.compile(r"(sentry|example|wixpress|\.png|\.jpe?g|\.gif|\.webp|\.svg"134                       r"|@2x|@3x|schema\.org|sentry-next|\.js$|\.css$|no-?reply)", re.I)135MAILTO_RE = re.compile(r'mailto:([^"\'?>\s]+)', re.I)136PHONE_RE = re.compile(r"(?:\+1[ .-]?)?\(?\b([2-9]\d{2})\)?[ .-]?(\d{3})[ .-]?(\d{4})\b")137SOCIAL_RE = re.compile(r'https?://(?:www\.)?(?:instagram\.com|facebook\.com)/[A-Za-z0-9_.\-/%]+', re.I)138LD_RE = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.I | re.S)139140_SHOPIFY_LOCK = threading.Lock()141_last_shopify = [0.0]142143144def fetch(url, shopify=False, timeout=15):145    if shopify:146        with _SHOPIFY_LOCK:147            wait = 0.7 - (time.time() - _last_shopify[0])148            if wait > 0:149                time.sleep(wait)150            _last_shopify[0] = time.time()151    try:152        r = requests.get(url, headers=HDRS, timeout=timeout, allow_redirects=True)153        if r.status_code == 200 and len(r.text) > 200:154            return r.text155    except Exception:156        pass157    return None158159160def harvest(html_text: str, rec: dict) -> None:161    """Extrait courriel / téléphone / réseaux d'un HTML (JSON-LD d'abord)."""162    for m in LD_RE.finditer(html_text):163        try:164            data = json.loads(m.group(1).strip())165        except Exception:166            continue167        stack = data if isinstance(data, list) else [data]168        while stack:169            node = stack.pop()170            if isinstance(node, list):171                stack.extend(node)172                continue173            if not isinstance(node, dict):174                continue175            stack.extend(v for v in node.values() if isinstance(v, (dict, list)))176            if not rec.get("email") and isinstance(node.get("email"), str):177                e = node["email"].replace("mailto:", "").strip()178                if EMAIL_RE.fullmatch(e) and not BAD_EMAIL.search(e):179                    rec["email"] = e180            if not rec.get("phone") and isinstance(node.get("telephone"), str):181                rec["phone"] = node["telephone"].strip()[:30]182            for u in (node.get("sameAs") or []) if isinstance(node.get("sameAs"), list) else []:183                if isinstance(u, str) and SOCIAL_RE.match(u):184                    rec.setdefault("socials", []).append(u.rstrip("/"))185    if not rec.get("email"):186        m = MAILTO_RE.search(html_text)187        if m:188            e = _html.unescape(m.group(1)).strip()189            if EMAIL_RE.fullmatch(e) and not BAD_EMAIL.search(e):190                rec["email"] = e191    if not rec.get("email"):192        for e in EMAIL_RE.findall(html_text[:200000]):193            if not BAD_EMAIL.search(e):194                rec["email"] = e195                break196    if not rec.get("phone"):197        m = PHONE_RE.search(re.sub(r"<[^>]+>", " ", html_text[:150000]))198        if m:199            rec["phone"] = f"{m.group(1)} {m.group(2)}-{m.group(3)}"200    for u in SOCIAL_RE.findall(html_text[:200000]):201        if "/sharer" in u or "/share?" in u or "/plugins" in u:202            continue203        rec.setdefault("socials", []).append(u.rstrip("/"))204205206def work(store):207    dom = store["id"]208    cpath = os.path.join(CACHE, dom + ".json")209    if os.path.exists(cpath):210        return json.load(open(cpath))211    base = (store["url"] or f"https://{dom}").rstrip("/")212    sh = store["platform"] == "shopify"213    rec = {"domain": dom, "email": None, "phone": None, "socials": [],214           "checked_at": time.strftime("%Y-%m-%d"), "requests": 0}215    html_text = fetch(base + "/", shopify=sh)216    rec["requests"] += 1217    if html_text:218        harvest(html_text, rec)219        if not rec["email"]:220            # une seule page contact : la première trouvée dans le HTML d'accueil221            m = re.search(r'href="([^"]*(?:contact|nous-joindre|joindre)[^"]*)"',222                          html_text, re.I)223            path = None224            if m:225                href = _html.unescape(m.group(1))226                if href.startswith("/"):227                    path = href228                elif dom in href:229                    path = "/" + href.split(dom, 1)[1].lstrip("/")230            if not path:231                path = CONTACT_PATHS[0] if not sh else "/pages/contact"232            page = fetch(base + path, shopify=sh)233            rec["requests"] += 1234            if page:235                harvest(page, rec)236    rec["socials"] = sorted(set(rec["socials"]))[:6]237    json.dump(rec, open(cpath, "w"), ensure_ascii=False)238    return rec239240241def main():242    ap = argparse.ArgumentParser()243    ap.add_argument("--cap", type=int, default=400)244    ap.add_argument("--workers", type=int, default=6)245    ap.add_argument("--exclude-platform", default=None,246                    help="saute une plateforme (ex. shopify pendant un cycle de sync)")247    args = ap.parse_args()248249    con = fdb.connect()250    extra = "AND platform<>? " if args.exclude_platform else ""251    params = ([args.exclude_platform] if args.exclude_platform else []) + [args.cap]252    rows = [dict(r) for r in con.execute(253        "SELECT id, url, platform FROM stores WHERE product_count > 0 "254        f"AND (email IS NULL OR email='') {extra}ORDER BY product_count DESC LIMIT ?",255        params)]256    con.close()257    print(f"[contacts] {len(rows)} boutiques ciblées (cap {args.cap})", flush=True)258259    results, done, nreq = [], 0, 0260    with cf.ThreadPoolExecutor(args.workers) as ex:261        for rec in ex.map(work, rows):262            results.append(rec)263            nreq += rec.get("requests", 0)264            done += 1265            if done % 50 == 0:266                print(f"  {done}/{len(rows)}", flush=True)267268    con = fdb.connect()269    n_email = n_phone = 0270    for rec in results:271        if rec.get("email"):272            con.execute("UPDATE stores SET email=? WHERE id=?", (rec["email"], rec["domain"]))273            n_email += 1274        if rec.get("phone"):275            con.execute("UPDATE stores SET phone=CASE WHEN COALESCE(phone,'')='' "276                        "THEN ? ELSE phone END WHERE id=?", (rec["phone"], rec["domain"]))277            n_phone += 1278    con.commit(); con.close()279    print(f"[contacts] courriels : {n_email}/{len(results)} | téléphones : {n_phone} "280          f"| requêtes réseau : {nreq}")281282283if __name__ == "__main__":284    main()285
Files main
Menu

Theme