Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Fabri·Ka10# File : scripts/wave5_discovery.py11# Description : Vague 5 (expansion sectorielle) : nouvelles sources de12# fabricants.13# Module : scripts14# Repository : https://git.spboucher.ai/fabri-ka15# Created : 2026-08-2116# Last Modified : 2026-08-2117#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 5 (expansion sectorielle) : nouvelles sources de fabricants.9192Sources moissonnées (fiche d'évaluation datée du 2026-08-21 dans93docs/CONFORMITE.md ; découvertes via Serper/Tavily puis sondées AVANT94connexion — robots.txt lus, répertoires publics de promotion des membres) :9596 modemtl Répertoire de la mode locale montréalaise97 (modemtl.com/repertoire-mode-locale-mtl/). Page98 WordPress statique, ~52 liens directs vers les sites99 des marques. robots.txt permissif (WP standard).100 boeufdici Répertoire Bœuf d'ici — producteurs de bœuf vendant101 à la ferme (boeufdici.com/repertoire/). Page WP102 statique, ~43 liens directs. robots.txt permissif.103 afmq Association des fabricants de meubles du Québec104 (afmq.com/liste_compagnies). Liste -> fiches105 /liste_compagnies/profil/<id>-<slug> (~100 profils),106 site web extrait de chaque fiche (patron CTAQ de la107 vague 4). robots.txt : /catalog /scripts /images108 interdits — jamais requêtés.109 apiculteursduquebec Les Apiculteurs et Apicultrices du Québec — « route110 du miel » (apiculteursduquebec.com). Répertoire111 Drupal paginé par région (/membres/region/<15..31>) :112 chaque carte membre expose nom, adresse (code postal)113 et site web (lien du logo). robots.txt Drupal standard.114 vendors_epipresto Champ `vendor` de la place de marché epipresto.ca115 (connectée en vague 4, 273 vendeurs distincts) —116 patron vendors_collectifs de la vague 4 : résolution117 prudente du site officiel par candidats de domaine,118 validés par correspondance du titre. ⚠️ vendeurs119 hétérogènes (épiceries revendeuses ET producteurs) ->120 prior E 0.4 « nature à vérifier », preuve QC exigée.121122Écartées (raison consignée dans docs/CONFORMITE.md, 2026-08-21) :123ebenistes-quebec.com (coquille lead-gen, 0 fiche extractible),124microentreprendre.ca (répertoire JS sans liens vers les sites ; microcrédit125n'est pas une preuve de fabrication), index-design.ca (répertoire non126QC-only — fournisseurs internationaux), chantier.qc.ca (répertoire127admin-ajax ; entreprises d'économie sociale majoritairement non128fabricantes), apdiq.com / designmontreal.com (designers de services).129130Usage :131 python3 scripts/wave5_discovery.py harvest [source ...]132 python3 scripts/wave5_discovery.py integrate # additif, sérialisé133"""134import argparse135import concurrent.futures as cf136import html as htmllib137import json138import os139import re140import subprocess141import sys142import time143import unicodedata144from collections import Counter145from urllib.parse import urlparse146147import requests148149ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))150RAW = os.path.join(ROOT, "data", "raw")151ENR = os.path.join(ROOT, "data", "enriched")152sys.path.insert(0, ROOT)153sys.path.insert(0, os.path.join(ROOT, "scripts"))154155for line in open(os.path.join(ROOT, ".env")).read().splitlines():156 if "=" in line and not line.startswith("#"):157 k, _, v = line.partition("=")158 os.environ.setdefault(k.strip(), v.strip())159160from verify import HDRS, POSTAL_RE, AREA_RE, verify_domain # noqa: E402161from aggregate import BLOCK, norm_domain # noqa: E402162163TAG_RE = re.compile(r"<[^>]+>")164SESS = requests.Session()165166# domaines utilitaires vus sur les pages répertoires de la vague 5 (agences167# web des annuaires, CDN, boilerplate WordPress) — pas couverts par BLOCK168EXTRA_BLOCK = re.compile(169 r"(?i)(browsehappy\.com|cookiedatabase\.org|gmpg\.org|jarold\.ca|"170 r"viglob\.ca|igminformatique|themeforest|jsdelivr|cloudflare|"171 r"googleapis|gstatic|w3\.org|schema\.org|wp\.org|elementor|"172 # ritkey = agence des fiches AFMQ ; mtl.org = site touristique ;173 # achetezalaferme = place de marché (pas un producteur)174 r"ritkey\.com|mtl\.org|achetezalaferme)")175176SOCIALS = ("facebook", "instagram", "linkedin", "youtube", "tiktok",177 "pinterest", "twitter", "x.com")178179180def strip_tags(s):181 return re.sub(r"\s+", " ", TAG_RE.sub(" ", htmllib.unescape(s or ""))).strip()182183184def get(url, timeout=25):185 try:186 r = SESS.get(url, headers=HDRS, timeout=timeout, allow_redirects=True)187 if r.status_code == 200:188 return r.text189 except Exception:190 pass191 return ""192193194def write_jsonl(name, records):195 os.makedirs(RAW, exist_ok=True)196 path = os.path.join(RAW, name + ".jsonl")197 with open(path, "w") as f:198 for r in records:199 f.write(json.dumps(r, ensure_ascii=False) + "\n")200 print(f"[harvest] {name}: {len(records)} entrées -> {path}", flush=True)201202203def _bad(url, dom):204 return (not dom or BLOCK.search(dom) or BLOCK.search(url)205 or EXTRA_BLOCK.search(url) or any(s in dom for s in SOCIALS))206207208# ------------------------------------------------ répertoires à liens directs209def harvest_single_page(source, page_url, own_domain, region_hint, evidence):210 html = get(page_url, timeout=40)211 records, seen = [], set()212 for url, label in re.findall(r'<a\s[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>',213 html, re.S | re.I):214 url = htmllib.unescape(url)215 host = (urlparse(url).netloc or "").lower()216 if not host or own_domain in host:217 continue218 dom = norm_domain(url)219 if _bad(url, dom) or dom in seen:220 continue221 seen.add(dom)222 label = strip_tags(label)223 generic = label.lower() in {"web", "site", "site web", "voir le site",224 "en savoir plus", "visiter", "boutique"}225 records.append({226 "name": label if 2 < len(label) < 80 and not generic else "",227 "domain": dom, "url": url, "region_hint": region_hint,228 "category_hint": "", "evidence": evidence, "query": page_url,229 })230 write_jsonl(source, records)231232233# ----------------------------------------------------------------------- AFMQ234AFMQ_BASE = "https://www.afmq.com"235AFMQ_PROFIL_RE = re.compile(r'href="(/liste_compagnies/profil/[^"#?]+)"')236237238def harvest_afmq():239 """Liste des membres -> fiches profil -> site web (patron CTAQ vague 4)."""240 html = get(AFMQ_BASE + "/liste_compagnies", timeout=40)241 paths = sorted(set(AFMQ_PROFIL_RE.findall(html)))242 print(f"[afmq] {len(paths)} fiches profil à visiter", flush=True)243 records = []244 for i, path in enumerate(paths, 1):245 page = get(AFMQ_BASE + path, timeout=30)246 time.sleep(0.4)247 if i % 25 == 0:248 print(f" [afmq] {i}/{len(paths)}", flush=True)249 if not page:250 continue251 name = ""252 m = re.search(r"<h1[^>]*>(.*?)</h1>", page, re.S | re.I)253 if m:254 name = strip_tags(m.group(1))255 if not name:256 name = path.rsplit("-", 1)[-1].replace("_", " ").title()257 webs = []258 for u in re.findall(r'href="(https?://[^"]+)"', page):259 dom = norm_domain(u)260 if _bad(u, dom) or "afmq" in (dom or ""):261 continue262 if u not in webs:263 webs.append(u)264 if not webs:265 continue266 text = strip_tags(page[:150000])267 postal = POSTAL_RE.search(text)268 phone = AREA_RE.search(text)269 cat = re.search(r"Catégorie\(s\) de produits:\s*(.{0,120})", text)270 records.append({271 "url": AFMQ_BASE + path,272 "title": name,273 "h1": name,274 "websites": webs[:2],275 "socials": [],276 "postal_prefix": postal.group(0)[:3] if postal else None,277 "phone": phone.group(0) if phone else None,278 "regions_mentioned": [],279 "text_sample": ("Fabricant de meubles membre AFMQ — "280 + (cat.group(1) if cat else ""))[:200],281 "category_hint": "maison",282 })283 write_jsonl("afmq", records)284285286# ------------------------------------------------------- Apiculteurs du Québec287API_BASE = "https://www.apiculteursduquebec.com"288# ids Drupal des vues régionales (constatés sur le sélecteur de la page289# « entreprises apicoles d'ici ») -> nom canonique du registre290API_REGIONS = {291 15: "Abitibi-Témiscamingue", 16: "Bas-Saint-Laurent",292 17: "Capitale-Nationale", 18: "Centre-du-Québec",293 19: "Chaudière-Appalaches", 20: "Côte-Nord", 21: "Estrie",294 22: "Gaspésie–Îles-de-la-Madeleine", 23: "Lanaudière",295 24: "Laurentides", 25: "Laval", 26: "Mauricie", 27: "Montérégie",296 28: "Montréal", 29: "Nord-du-Québec", 30: "Outaouais",297 31: "Saguenay–Lac-Saint-Jean",298}299API_ROW_RE = re.compile(r'<div class="views-row">(.*?)(?=<div class="views-row">|</section>)', re.S)300API_NAME_RE = re.compile(r'field-adresse-organization-1[^>]*>.*?<a href="[^"]*">([^<]+)</a>', re.S)301API_ADDR_RE = re.compile(r'views-field-field-adresse"[^>]*><div class="field-content">(.*?)</div>', re.S)302303304def harvest_apiculteurs():305 records, seen = [], set()306 for rid, region in API_REGIONS.items():307 for page in range(0, 12):308 url = f"{API_BASE}/membres/region/{rid}" + (f"?page={page}" if page else "")309 html = get(url, timeout=30)310 time.sleep(0.5)311 rows = API_ROW_RE.findall(html) if html else []312 if not rows:313 break314 found = 0315 for row in rows:316 webs = []317 for u in re.findall(r'href="(https?://[^"]+)"', row):318 dom = norm_domain(u)319 if _bad(u, dom) or "apiculteursduquebec" in (dom or ""):320 continue321 if u not in webs:322 webs.append(u)323 if not webs:324 continue # membre sans site web -> inconnectable325 nm = API_NAME_RE.search(row)326 name = strip_tags(nm.group(1)) if nm else ""327 key = norm_domain(webs[0])328 if key in seen:329 continue330 seen.add(key)331 found += 1332 addr = API_ADDR_RE.search(row)333 text = strip_tags(addr.group(1)) if addr else ""334 postal = POSTAL_RE.search(text)335 records.append({336 "url": url,337 "title": name,338 "h1": name,339 "websites": webs[:2],340 "socials": [],341 "postal_prefix": postal.group(0)[:3].replace(" ", "") if postal else None,342 "phone": None,343 "regions_mentioned": [region],344 "text_sample": text[:200],345 "category_hint": "erable",346 })347 if not found and page > 0:348 break349 print(f" [apiculteurs] {region}: cumul {len(records)}", flush=True)350 write_jsonl("apiculteursduquebec", records)351352353# --------------------------------------------------- vendors d'EPIPRESTO354COLLECTIFS = ["epipresto.ca"]355STOP_TOKENS = {"inc", "enr", "ltee", "les", "the", "and", "et", "de", "du",356 "la", "le", "des", "by", "par", "studio", "atelier", "co"}357# vendeurs génériques de la place de marché (pas des marques)358VENDOR_SKIP = re.compile(r"(?i)(général|autre choix|mini march|pharmacie|"359 r"dépanneur|depanneur|épicerie|epicerie|march[ée] )")360361362def _slug(name):363 s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()364 return re.sub(r"[^a-z0-9]", "", s.lower())365366367def _norm_name(name):368 s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode().lower()369 return " ".join(t for t in re.findall(r"[a-z0-9]+", s) if t not in STOP_TOKENS)370371372def _curl(url, timeout=20):373 """GET via curl (mécanisme du projet pour éviter le 429 TLS de requests)."""374 try:375 r = subprocess.run(["curl", "-sL", "-A", HDRS["User-Agent"], "--max-time",376 str(timeout), "--max-filesize", "400000", url],377 capture_output=True, timeout=timeout + 10)378 return r.stdout.decode("utf-8", "replace")379 except Exception:380 return ""381382383def harvest_vendors_epipresto(cap=400):384 from fabrika import db as fdb385 con = fdb.connect()386 rows = con.execute(387 "SELECT vendor, COUNT(*) AS n, GROUP_CONCAT(DISTINCT store_id) AS sids "388 "FROM products WHERE active=1 AND vendor<>'' AND store_id IN (%s) "389 "GROUP BY vendor ORDER BY n DESC" % ",".join("?" * len(COLLECTIFS)),390 COLLECTIFS).fetchall()391 known_names = {_norm_name(r[0]) for r in392 con.execute("SELECT name FROM stores") if r[0]}393 known_doms = {r[0] for r in con.execute("SELECT id FROM stores")}394 con.close()395 cand_path = os.path.join(ENR, "candidates.jsonl")396 if os.path.exists(cand_path):397 with open(cand_path) as f:398 known_doms |= {json.loads(l)["domain"] for l in f}399400 records, probes = [], 0401 for vendor, n, sids in rows:402 v = vendor.strip()403 if len(v) < 3 or len(v) > 60 or _norm_name(v) in known_names:404 continue405 if VENDOR_SKIP.search(v):406 continue407 slug = _slug(v)408 if not (4 <= len(slug) <= 30):409 continue410 if probes >= cap:411 break412 found = None413 for dom in (slug + ".com", slug + ".ca"):414 if dom in known_doms or BLOCK.search(dom):415 continue416 probes += 1417 html = _curl(f"https://{dom}")418 time.sleep(0.3)419 if not html:420 continue421 title_m = re.search(r"<title[^>]*>(.*?)</title>", html, re.S | re.I)422 title = _norm_name(strip_tags(title_m.group(1))[:120]) if title_m else ""423 vt = set(_norm_name(v).split())424 if vt and title and len(vt & set(title.split())) / len(vt) >= 0.6:425 found = dom426 break427 if found:428 records.append({429 "name": v,430 "domain": found,431 "url": f"https://{found}",432 "region_hint": "",433 "category_hint": "",434 "evidence": f"Vendeur de la place de marché EPIPRESTO ({n} produits) "435 f"— site officiel résolu et validé par titre",436 "query": f"vendor:{v}",437 })438 print(f"[vendors_epipresto] {probes} sondes, {len(records)} sites résolus", flush=True)439 write_jsonl("vendors_epipresto", records)440441442HARVESTERS = {443 "modemtl": lambda: harvest_single_page(444 "modemtl", "https://modemtl.com/repertoire-mode-locale-mtl/",445 "modemtl.com", "Montréal",446 "Marque de mode locale répertoriée par ModeMTL (répertoire de la "447 "mode montréalaise)"),448 "boeufdici": lambda: harvest_single_page(449 "boeufdici", "https://boeufdici.com/repertoire/",450 "boeufdici.com", "",451 "Producteur membre du répertoire Bœuf d'ici (vente de bœuf à la ferme)"),452 "afmq": harvest_afmq,453 "apiculteursduquebec": harvest_apiculteurs,454 "vendors_epipresto": harvest_vendors_epipresto,455}456457WAVE5_SOURCES = list(HARVESTERS)458459460def harvest(only=None):461 os.makedirs(RAW, exist_ok=True)462 for name, fn in HARVESTERS.items():463 if only and name not in only:464 continue465 print(f"[harvest] === {name} ===", flush=True)466 fn()467468469def integrate():470 """Intégration additive au registre + DB (mêmes garde-fous que la vague 4)."""471 from datetime import date472 import build_registry as br473 from fabrika import db as fdb474475 for s in WAVE5_SOURCES:476 assert s in br.SOURCE_PRIORS, f"prior manquant dans build_registry: {s}"477478 subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "aggregate.py")],479 check=True)480481 cands = {}482 with open(os.path.join(ENR, "candidates.jsonl")) as f:483 for line in f:484 c = json.loads(line)485 cands[c["domain"]] = c486487 verified_path = os.path.join(ENR, "verified.jsonl")488 verified = {}489 with open(verified_path) as f:490 for line in f:491 v = json.loads(line)492 verified[v["domain"]] = v493494 reg_path = os.path.join(ROOT, "data", "stores.json")495 reg = json.load(open(reg_path))496 existing_ids = {s["id"] for s in reg["stores"]}497498 new_domains = sorted(d for d in cands499 if d not in verified and d not in existing_ids)500 print(f"[integrate] {len(new_domains)} nouveaux domaines à vérifier", flush=True)501502 new_recs = []503 with cf.ThreadPoolExecutor(12) as ex:504 for i, rec in enumerate(ex.map(verify_domain, new_domains)):505 new_recs.append(rec)506 if (i + 1) % 100 == 0:507 print(f" verify {i+1}/{len(new_domains)}", flush=True)508 with open(verified_path, "a") as f:509 for r in new_recs:510 f.write(json.dumps(r, ensure_ascii=False) + "\n")511 verified[r["domain"]] = r512513 added, skipped_dup, skipped_qc, skipped_dead = [], 0, 0, 0514 for dom in new_domains:515 cand, ver = cands[dom], verified.get(dom, {})516 if not ver.get("active"):517 skipped_dead += 1518 continue519 final_dom = ver.get("final_domain") or dom520 if final_dom in existing_ids:521 skipped_dup += 1522 continue523 qc_signal = any(ver.get(k) for k in ("qc_postal", "qc_phone", "tld_quebec",524 "mentions_quebec", "made_in_qc_wording"))525 qc_source = any(s in br.QC_ONLY_SOURCES for s in cand.get("sources", []))526 if not qc_signal and not qc_source:527 skipped_qc += 1528 continue529 cls, conf, ev = br.classify(cand, ver)530 default_cat = next((br.SOURCE_PRIORS[s][3] for s in br.PRIORITY531 if s in cand.get("sources", []) and br.SOURCE_PRIORS[s][3]), None)532 platform = ver.get("platform") or ""533 catalog_endpoint = ver.get("catalog_endpoint") or ""534 if platform == "wix" and not catalog_endpoint:535 catalog_endpoint = "/_api/wix-ecommerce-storefront-web/api"536 fu = urlparse(ver.get("final_url") or f"https://{final_dom}")537 store = {538 "id": final_dom,539 "name": br.clean_name(cand, ver),540 "url": f"{fu.scheme}://{fu.netloc}",541 "platform": platform,542 "catalog_endpoint": catalog_endpoint,543 "city": "",544 "region": br.pick_region(cand) or br.region_from_postal(cand, ver),545 "postal_prefix": cand.get("postal_prefix") or (ver.get("qc_postal") or "")[:3] or None,546 "phone": cand.get("phone") or ver.get("qc_phone"),547 "origin_class": cls,548 "origin_confidence": conf,549 "origin_evidence": ev,550 "categories": [default_cat] if default_cat else [],551 "socials": (cand.get("socials") or [])[:4] or ver.get("socials", []),552 "discovery_sources": cand.get("sources", []),553 "discovery_source_urls": cand.get("source_pages", [])[:5],554 "language": ver.get("language"),555 "ecommerce": bool(ver.get("has_cart") or catalog_endpoint),556 "verification_date": ver.get("checked_at") or str(date.today()),557 "status": "verified" if (conf >= 0.6 and ver.get("mentions_quebec")) else "probable",558 "enabled": bool(catalog_endpoint),559 }560 existing_ids.add(final_dom)561 added.append(store)562563 reg["stores"].extend(added)564 reg["count"] = len(reg["stores"])565 reg["generated"] = str(date.today())566 json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)567568 con = fdb.connect()569 for s in added:570 fdb.upsert_store(con, s)571 con.commit(); con.close()572573 enabled = [s["id"] for s in added if s["enabled"]]574 per_plat = Counter(s["platform"] or "(aucune)" for s in added)575 per_src = Counter(src for s in added for src in s["discovery_sources"])576 per_cls = Counter(s["origin_class"] for s in added)577 print(f"[integrate] boutiques ajoutées: {len(added)} | connectables (enabled): {len(enabled)}")578 print(f"[integrate] écartées — mortes/injoignables: {skipped_dead}, "579 f"dédup domaine final: {skipped_dup}, sans preuve QC: {skipped_qc}")580 print("[integrate] par plateforme:", dict(per_plat.most_common()))581 print("[integrate] par source:", dict(per_src.most_common()))582 print("[integrate] par classe:", dict(per_cls))583 with open(os.path.join(ROOT, "data", "wave5_new_enabled.txt"), "w") as f:584 f.write("\n".join(enabled) + "\n")585 if enabled:586 print("[integrate] à synchroniser: python run.py sync $(cat data/wave5_new_enabled.txt)")587588589if __name__ == "__main__":590 ap = argparse.ArgumentParser()591 ap.add_argument("cmd", choices=["harvest", "integrate"])592 ap.add_argument("only", nargs="*", help="sources précises (harvest)")593 args = ap.parse_args()594 harvest(args.only or None) if args.cmd == "harvest" else integrate()595