SPB Git

Repository Public

wave3_discovery.py 18.7 KB 487 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/wave3_discovery.py11# Description      : Vague 3 — découverte de nouvelles boutiques via 412#                    annuaires québécois frais.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1816# Last Modified    : 2026-08-1817#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 3 — découverte de nouvelles boutiques via 4 annuaires québécois frais.9192Annuaires moissonnés (aucune clé API) :93  lespagesvertes         Les Pages Vertes — répertoire de l'économie verte QC94                         (fiches /entreprise/<slug>/ via business-sitemap*.xml)95  mauriciemiam           MIAM Mauricie — identifiant régional agroalimentaire96                         (liens externes de /repertoire-des-membres/)97  gardemangerduquebec    La Montérégie, le Garde-Manger du Québec — membres98                         « Producteurs et transformateurs » (fiches /membres-complices/)99  gardemangerduquebec_det  idem, mais détaillants/marchés/restaurants (classe C)100  terroiretsaveurs       Terroir et Saveurs (AATGQ) — liste « producteurs et101                         artisans pour acheter local » (liens externes directs)102103Écartés après reconnaissance : Etsy (HTTP 403 anti-bot), Ma Zone Québec104(coquille Drupal vide côté serveur), Goûtez Lanaudière (liste membres dans un105CRM Eudonet inaccessible), Signé Local / CMAQ / économusées / Créateurs de106saveurs (déjà couverts : search_sweep_vendors, search_sweep_cmaq,107artisansaloeuvre, createursdesaveurs).108109Usage :110  python3 scripts/wave3_discovery.py harvest     # -> data/raw/<source>.jsonl111  python3 scripts/wave3_discovery.py integrate   # aggregate + verify + ajout112                                                 #    additif au registre + DB113114`integrate` est strictement additif : il n'ajoute que des domaines absents du115registre, ne touche à aucune boutique existante, et applique les mêmes116garde-fous que build_registry (preuve de localisation QC, classes A–E avec117évidence, dédup par domaine final).118"""119import argparse120import concurrent.futures as cf121import html as htmllib122import json123import os124import re125import sys126import time127from collections import Counter128from urllib.parse import unquote, urlparse, parse_qs129130import requests131132ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))133RAW = os.path.join(ROOT, "data", "raw")134ENR = os.path.join(ROOT, "data", "enriched")135sys.path.insert(0, ROOT)136sys.path.insert(0, os.path.join(ROOT, "scripts"))137138for line in open(os.path.join(ROOT, ".env")).read().splitlines():139    if "=" in line and not line.startswith("#"):140        k, _, v = line.partition("=")141        os.environ.setdefault(k.strip(), v.strip())142143from verify import HDRS, POSTAL_RE, AREA_RE, verify_domain  # noqa: E402144from aggregate import BLOCK, norm_domain                    # noqa: E402145146A_RE = re.compile(r'<a\s[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>', re.S | re.I)147H1_RE = re.compile(r"<h1[^>]*>(.*?)</h1>", re.S | re.I)148TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)149TAG_RE = re.compile(r"<[^>]+>")150SOCIAL_HOSTS = ("facebook.com", "instagram.com", "linkedin.com", "youtube.com",151                "tiktok.com", "pinterest.", "x.com", "twitter.com")152153SESS = requests.Session()154155156def get(url, timeout=20):157    try:158        r = SESS.get(url, headers=HDRS, timeout=timeout, allow_redirects=True)159        if r.status_code == 200:160            return r.text161    except Exception:162        pass163    return ""164165166def strip_tags(s):167    return re.sub(r"\s+", " ", TAG_RE.sub(" ", htmllib.unescape(s or ""))).strip()168169170def unwrap_safelink(url):171    """Déballe les liens Outlook SafeLinks (vus sur MIAM)."""172    if "safelinks.protection.outlook.com" in url:173        q = parse_qs(urlparse(url).query)174        if q.get("url"):175            return unquote(q["url"][0])176    return url177178179def ext_links(html, own_domain):180    out = []181    for url, label in A_RE.findall(html):182        url = unwrap_safelink(htmllib.unescape(url))183        host = (urlparse(url).netloc or "").lower()184        if not host or own_domain in host:185            continue186        if any(s in host for s in SOCIAL_HOSTS):187            continue188        out.append((url, strip_tags(label)))189    return out190191192def fiche_record(url, html, own_domain):193    text = strip_tags(html[:200000])194    h1 = H1_RE.search(html)195    title = TITLE_RE.search(html)196    postal = POSTAL_RE.search(text)197    phone = AREA_RE.search(text)198    return {199        "url": url,200        "title": strip_tags(title.group(1))[:120] if title else "",201        "h1": strip_tags(h1.group(1))[:120] if h1 else "",202        "websites": [u for u, _ in ext_links(html, own_domain)],203        "socials": [],204        "postal_prefix": postal.group(0)[:3] if postal else None,205        "phone": phone.group(0) if phone else None,206        "regions_mentioned": [],207        "text_sample": text[:600],208    }209210211def write_jsonl(name, records):212    path = os.path.join(RAW, name + ".jsonl")213    with open(path, "w") as f:214        for r in records:215            f.write(json.dumps(r, ensure_ascii=False) + "\n")216    print(f"[harvest] {name}: {len(records)} fiches/entrées -> {path}", flush=True)217218219def drop_frequent_domains(records, threshold=0.05):220    """Retire des fiches les domaines « partenaires » présents partout."""221    n = max(len(records), 1)222    freq = Counter()223    for r in records:224        for dom in {norm_domain(w) for w in r["websites"]} - {None}:225            freq[dom] += 1226    noisy = {d for d, c in freq.items() if c / n > threshold and c > 3}227    if noisy:228        print(f"[harvest] domaines partenaires ignorés (>5% des fiches): {sorted(noisy)}")229    for r in records:230        r["websites"] = [w for w in r["websites"] if norm_domain(w) not in noisy]231    return records232233234def crawl_fiches(urls, own_domain, workers=3, delay=0.4, label=""):235    records, done = [], 0236237    def one(u):238        time.sleep(delay)239        html = get(u)240        return fiche_record(u, html, own_domain) if html else None241242    with cf.ThreadPoolExecutor(workers) as ex:243        for rec in ex.map(one, urls):244            done += 1245            if rec and rec["websites"]:246                records.append(rec)247            if done % 100 == 0:248                print(f"  [{label}] {done}/{len(urls)}", flush=True)249    return records250251252# ---------------------------------------------------------------- harvesters253254def harvest_lespagesvertes():255    urls = []256    for sm in ("business-sitemap.xml", "business-sitemap2.xml"):257        xml = get(f"https://lespagesvertes.ca/{sm}")258        urls += re.findall(r"<loc>(https://lespagesvertes\.ca/entreprise/[^<]+)</loc>", xml)259    urls = list(dict.fromkeys(urls))260    print(f"[harvest] lespagesvertes: {len(urls)} fiches à visiter", flush=True)261    records = crawl_fiches(urls, "lespagesvertes.ca", workers=5, delay=0.25, label="lpv")262    write_jsonl("lespagesvertes", drop_frequent_domains(records))263264265GMQ_CATS = {266    "producteur": "producteurs",267    "transformateur": "producteurs",268    "épicerie": "detaillants",269    "epicerie": "detaillants",270    "boutique gourmande": "detaillants",271    "marché public": "detaillants",272    "marche public": "detaillants",273    "restaurant": "detaillants",274    "traiteur": "detaillants",275    "aubergiste": "detaillants",276}277278279def harvest_gardemanger():280    page = get("https://gardemangerduquebec.ca/repertoire-des-membres/", timeout=40)281    fiches = sorted(set(re.findall(282        r'href="(https://gardemangerduquebec\.ca/membres-complices/[^"#]+)"', page)))283    print(f"[harvest] gardemangerduquebec: {len(fiches)} fiches à visiter", flush=True)284    prod, det = [], []285286    def classify_cat(html):287        # classe body Avada : portfolio_category-<slug> = catégorie réelle de la fiche288        if "portfolio_category-producteurs-et-transformateurs" in html:289            return "producteurs"290        return "detaillants"291292    done = 0293294    def one(u):295        time.sleep(0.4)296        html = get(u)297        if not html:298            return None299        return classify_cat(html), fiche_record(u, html, "gardemangerduquebec.ca")300301    with cf.ThreadPoolExecutor(3) as ex:302        for res in ex.map(one, fiches):303            done += 1304            if done % 50 == 0:305                print(f"  [gmq] {done}/{len(fiches)}", flush=True)306            if not res:307                continue308            cat, rec = res309            rec["regions_mentioned"] = ["Montérégie"]310            if not rec["websites"]:311                continue312            (prod if cat == "producteurs" else det).append(rec)313    write_jsonl("gardemangerduquebec", drop_frequent_domains(prod))314    write_jsonl("gardemangerduquebec_det", drop_frequent_domains(det))315316317def harvest_single_page(source, page_url, own_domain, region_hint, evidence):318    page = get(page_url, timeout=40)319    records, seen = [], set()320    for url, label in ext_links(page, own_domain):321        dom = norm_domain(url)322        if not dom or dom in seen or BLOCK.search(dom) or BLOCK.search(url):323            continue324        seen.add(dom)325        name = label if 2 < len(label) < 80 else ""326        records.append({327            "name": name,328            "domain": dom,329            "url": url,330            "region_hint": region_hint,331            "category_hint": "",332            "evidence": evidence,333            "query": page_url,334        })335    write_jsonl(source, records)336337338def harvest():339    os.makedirs(RAW, exist_ok=True)340    harvest_single_page(341        "mauriciemiam", "https://mauriciemiam.ca/repertoire-des-membres/",342        "mauriciemiam.ca", "Mauricie",343        "Membre MIAM Mauricie (identifiant régional agroalimentaire)")344    harvest_single_page(345        "terroiretsaveurs",346        "https://terroiretsaveurs.com/repertoire-terroir-saveurs-liste-des-producteurs-et-artisans-pour-acheter-local/",347        "terroiretsaveurs.com", "",348        "Producteur/artisan du répertoire Terroir et Saveurs (AATGQ)")349    harvest_gardemanger()350    harvest_lespagesvertes()351352353# ---------------------------------------------------------------- integrate354355WAVE3_SOURCES = ["lespagesvertes", "mauriciemiam", "gardemangerduquebec",356                 "gardemangerduquebec_det", "terroiretsaveurs"]357358359def integrate():360    import subprocess361    from datetime import date362    import build_registry as br363    from fabrika import db as fdb364365    for s in WAVE3_SOURCES:366        assert s in br.SOURCE_PRIORS, f"prior manquant dans build_registry: {s}"367368    # 1) ré-agrège tous les raw (inclut la vague 3) -> candidates.jsonl canonique369    subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "aggregate.py")],370                   check=True)371372    cands = {}373    with open(os.path.join(ENR, "candidates.jsonl")) as f:374        for line in f:375            c = json.loads(line)376            cands[c["domain"]] = c377378    verified_path = os.path.join(ENR, "verified.jsonl")379    verified = {}380    with open(verified_path) as f:381        for line in f:382            v = json.loads(line)383            verified[v["domain"]] = v384385    reg_path = os.path.join(ROOT, "data", "stores.json")386    reg = json.load(open(reg_path))387    existing_ids = {s["id"] for s in reg["stores"]}388389    # 2) domaines candidats jamais vérifiés (donc nouveaux pour le pipeline)390    new_domains = sorted(d for d in cands391                         if d not in verified and d not in existing_ids)392    print(f"[integrate] {len(new_domains)} nouveaux domaines à vérifier", flush=True)393394    new_recs = []395    with cf.ThreadPoolExecutor(16) as ex:396        for i, rec in enumerate(ex.map(verify_domain, new_domains)):397            new_recs.append(rec)398            if (i + 1) % 100 == 0:399                print(f"  verify {i+1}/{len(new_domains)}", flush=True)400    with open(verified_path, "a") as f:401        for r in new_recs:402            f.write(json.dumps(r, ensure_ascii=False) + "\n")403            verified[r["domain"]] = r404405    # 3) construit les entrées registre (mêmes règles que build_registry)406    added, skipped_dup, skipped_qc, skipped_dead = [], 0, 0, 0407    for dom in new_domains:408        cand, ver = cands[dom], verified.get(dom, {})409        if not ver.get("active"):410            skipped_dead += 1411            continue412        final_dom = ver.get("final_domain") or dom413        if final_dom in existing_ids:414            skipped_dup += 1415            continue416        qc_signal = any(ver.get(k) for k in ("qc_postal", "qc_phone", "tld_quebec",417                                             "mentions_quebec", "made_in_qc_wording"))418        qc_source = any(s in br.QC_ONLY_SOURCES for s in cand.get("sources", []))419        if not qc_signal and not qc_source:420            skipped_qc += 1421            continue422        cls, conf, ev = br.classify(cand, ver)423        default_cat = next((br.SOURCE_PRIORS[s][3] for s in br.PRIORITY424                            if s in cand.get("sources", []) and br.SOURCE_PRIORS[s][3]), None)425        platform = ver.get("platform") or ""426        catalog_endpoint = ver.get("catalog_endpoint") or ""427        if platform == "wix" and not catalog_endpoint:428            catalog_endpoint = "/_api/wix-ecommerce-storefront-web/api"429        fu = urlparse(ver.get("final_url") or f"https://{final_dom}")430        store = {431            "id": final_dom,432            "name": br.clean_name(cand, ver),433            "url": f"{fu.scheme}://{fu.netloc}",434            "platform": platform,435            "catalog_endpoint": catalog_endpoint,436            "city": "",437            "region": br.pick_region(cand) or br.region_from_postal(cand, ver),438            "postal_prefix": cand.get("postal_prefix") or (ver.get("qc_postal") or "")[:3] or None,439            "phone": cand.get("phone") or ver.get("qc_phone"),440            "origin_class": cls,441            "origin_confidence": conf,442            "origin_evidence": ev,443            "categories": [default_cat] if default_cat else [],444            "socials": (cand.get("socials") or [])[:4] or ver.get("socials", []),445            "discovery_sources": cand.get("sources", []),446            "discovery_source_urls": cand.get("source_pages", [])[:5],447            "language": ver.get("language"),448            "ecommerce": bool(ver.get("has_cart") or catalog_endpoint),449            "verification_date": ver.get("checked_at") or str(date.today()),450            "status": "verified" if (conf >= 0.6 and ver.get("mentions_quebec")) else "probable",451            "enabled": bool(catalog_endpoint),452        }453        existing_ids.add(final_dom)454        added.append(store)455456    reg["stores"].extend(added)457    reg["count"] = len(reg["stores"])458    reg["generated"] = str(date.today())459    json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)460461    con = fdb.connect()462    for s in added:463        fdb.upsert_store(con, s)464    con.commit(); con.close()465466    enabled = [s["id"] for s in added if s["enabled"]]467    per_plat = Counter(s["platform"] or "(aucune)" for s in added)468    per_src = Counter(src for s in added for src in s["discovery_sources"])469    per_cls = Counter(s["origin_class"] for s in added)470    print(f"[integrate] boutiques ajoutées: {len(added)} | connectables (enabled): {len(enabled)}")471    print(f"[integrate] écartées — mortes/injoignables: {skipped_dead}, "472          f"dédup domaine final: {skipped_dup}, sans preuve QC: {skipped_qc}")473    print("[integrate] par plateforme:", dict(per_plat.most_common()))474    print("[integrate] par source:", dict(per_src.most_common()))475    print("[integrate] par classe:", dict(per_cls))476    with open(os.path.join(ROOT, "data", "wave3_new_enabled.txt"), "w") as f:477        f.write("\n".join(enabled) + "\n")478    if enabled:479        print("[integrate] à synchroniser: python run.py sync $(cat data/wave3_new_enabled.txt)")480481482if __name__ == "__main__":483    ap = argparse.ArgumentParser()484    ap.add_argument("cmd", choices=["harvest", "integrate"])485    args = ap.parse_args()486    harvest() if args.cmd == "harvest" else integrate()487
Files main
Menu

Theme