SPB Git

Repository Public

enrich_shipping.py 10.9 KB 290 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_shipping.py11# Description      : Vague 2 — délais et politiques de livraison des boutiques12#                    productives.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1816# 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"""Vague 2 — délais et politiques de livraison des boutiques productives.9192Pour chaque boutique avec produits (product_count > 0) et sans shipping_info :93  1. essaie les pages politiques usuelles selon la plateforme94     (Shopify : /policies/shipping-policy ; sinon /politique-de-livraison,95      /livraison, /pages/livraison, /shipping, /expedition, …) ;96  2. à défaut, cherche un lien « livraison / shipping / expédition » sur97     la page d'accueil et le suit (1 requête de plus) ;98  3. extrait un résumé texte (≤ 400 caractères) centré sur les mentions de99     délais/tarifs (jours, $, gratuit, Postes Canada…).100101Écrit stores.shipping_info (colonne additive). Cache disque102data/enrich_cache/shipping/<domain>.json (y compris les échecs, pour ne pas103re-marteler les mêmes sites). Throttle poli : requêtes séquentielles par104domaine (0,4 s), 8 domaines en parallèle.105106Usage : python3 scripts/enrich_shipping.py [--cap 300]107"""108import argparse109import concurrent.futures as cf110import html as _html111import json112import os113import re114import sys115import threading116import time117from urllib.parse import urljoin118119import requests120121ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))122sys.path.insert(0, ROOT)123CACHE = os.path.join(ROOT, "data", "enrich_cache", "shipping")124os.makedirs(CACHE, exist_ok=True)125126for line in open(os.path.join(ROOT, ".env")).read().splitlines():127    if "=" in line and not line.startswith("#"):128        k, _, v = line.partition("=")129        os.environ.setdefault(k.strip(), v.strip())130131from fabrika import db as fdb  # noqa: E402132133HDRS = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "134                      "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",135        "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}136137PATHS_SHOPIFY = ["/policies/shipping-policy"]138PATHS_COMMON = ["/politique-de-livraison", "/pages/livraison", "/livraison",139                "/pages/politique-de-livraison", "/expedition", "/pages/expedition",140                "/shipping", "/pages/shipping", "/shipping-policy",141                "/politique-dexpedition", "/pages/shipping-policy"]142LINK_RE = re.compile(143    r'href="([^"]*(?:livraison|exp[ée]dition|shipping|delivery)[^"]*)"', re.I)144KW_RE = re.compile(r"(livraison|exp[ée]dition|shipping|delivery|d[ée]lai)", re.I)145DENSITY_RE = re.compile(r"(\d|\$|gratuit|free|jours?|days?|ouvrable|business|"146                        r"postes canada|canada post|purolator|ramassage|cueillette|pickup)", re.I)147STEP = 0.4148149# throttle global Shopify : le CDN limite par IP cliente, toutes boutiques150# confondues (même règle que connectors/shopify.py : 0,7 s entre requêtes)151_SHOPIFY_LOCK = threading.Lock()152_last_shopify = [0.0]153154155def _text(html):156    html = re.sub(r"(?is)<(script|style|noscript|svg|header|nav|footer)[^>]*>.*?</\1>", " ", html)157    html = re.sub(r"<[^>]+>", " ", html)158    return _html.unescape(re.sub(r"\s+", " ", html)).strip()159160161# bruit fréquent : sélecteurs de devises/pays des thèmes Shopify («(USD $)» ×30),162# menus. Une fenêtre qui en contient est rejetée.163NOISE_RE = re.compile(r"\((?:USD|EUR|GBP|CAD)\s*\$?\s*\)|currency|log in|wishlist", re.I)164165166def summarize(html):167    """Fenêtre ≤400 c. autour de la mention livraison la plus « dense »."""168    text = _text(html)169    if len(text) < 40:170        return None171    best, best_score = None, -1172    for m in KW_RE.finditer(text):173        start = max(0, m.start() - 60)174        if start:                       # démarre à une frontière de mot175            sp = text.find(" ", start)176            if 0 <= sp < m.start():177                start = sp + 1178        window = text[start:start + 460]179        if len(NOISE_RE.findall(window)) >= 2:180            continue181        score = len(DENSITY_RE.findall(window))182        if score > best_score:183            best, best_score = window, score184    if best is None or best_score < 1:185        return None186    # coupe proprement au dernier espace187    out = best[:400]188    if len(best) > 400:189        out = out.rsplit(" ", 1)[0]190    return out.strip() or None191192193def fetch(url, timeout=15, shopify=False):194    for attempt in range(2):195        if shopify:196            with _SHOPIFY_LOCK:197                wait = 0.7 - (time.time() - _last_shopify[0])198                if wait > 0:199                    time.sleep(wait)200                _last_shopify[0] = time.time()201        try:202            r = requests.get(url, headers=HDRS, timeout=timeout, allow_redirects=True)203            if r.status_code == 200 and len(r.text) > 300:204                return r.text, str(r.url)205            if r.status_code not in (429, 403):206                return None, None207        except Exception:208            pass209        time.sleep(3)210    return None, None211212213def work(store):214    dom, base, platform = store["id"], (store["url"] or f"https://{store['id']}").rstrip("/"), store["platform"]215    cpath = os.path.join(CACHE, dom + ".json")216    if os.path.exists(cpath):217        return json.load(open(cpath))218    rec = {"domain": dom, "shipping_info": None, "source_url": None,219           "checked_at": time.strftime("%Y-%m-%d")}220    sh = platform == "shopify"221    paths = (PATHS_SHOPIFY + PATHS_COMMON) if sh else PATHS_COMMON222    for p in paths:223        html, final = fetch(base + p, timeout=12, shopify=sh)224        if not sh:225            time.sleep(STEP)226        if html:227            info = summarize(html)228            if info:229                rec["shipping_info"], rec["source_url"] = info, final230                break231    if not rec["shipping_info"]:232        # repli : lien « livraison » sur la page d'accueil233        html, _ = fetch(base + "/", timeout=15, shopify=sh)234        if not sh:235            time.sleep(STEP)236        if html:237            m = LINK_RE.search(html)238            if m:239                href = urljoin(base + "/", _html.unescape(m.group(1)))240                if href.startswith("http") and dom in href:241                    page, final = fetch(href, timeout=12)242                    if page:243                        info = summarize(page)244                        if info:245                            rec["shipping_info"], rec["source_url"] = info, final246    json.dump(rec, open(cpath, "w"), ensure_ascii=False)247    return rec248249250def main():251    ap = argparse.ArgumentParser()252    ap.add_argument("--cap", type=int, default=300)253    ap.add_argument("--workers", type=int, default=8)254    args = ap.parse_args()255256    con = fdb.connect()257    try:258        con.execute("ALTER TABLE stores ADD COLUMN shipping_info TEXT")259        con.commit()260    except Exception:261        pass262    rows = [dict(r) for r in con.execute(263        "SELECT id, url, platform FROM stores WHERE product_count > 0 "264        "AND (shipping_info IS NULL OR shipping_info = '') "265        "ORDER BY product_count DESC LIMIT ?", (args.cap,))]266    con.close()267    print(f"[shipping] {len(rows)} boutiques ciblées (cap {args.cap})", flush=True)268269    results, done = [], 0270    with cf.ThreadPoolExecutor(args.workers) as ex:271        for rec in ex.map(work, rows):272            results.append(rec)273            done += 1274            if done % 50 == 0:275                print(f"  {done}/{len(rows)}", flush=True)276277    con = fdb.connect()278    n = 0279    for rec in results:280        if rec.get("shipping_info"):281            con.execute("UPDATE stores SET shipping_info=? WHERE id=?",282                        (rec["shipping_info"], rec["domain"]))283            n += 1284    con.commit(); con.close()285    print(f"[shipping] shipping_info rempli : {n}/{len(results)}")286287288if __name__ == "__main__":289    main()290
Files main
Menu

Theme