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/wave4_discovery.py11# Description : Vague 4 (Phase 3 — expansion) : nouvelles sources de12# fabricants.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"""Vague 4 (Phase 3 — expansion) : nouvelles sources de fabricants.9192Sources moissonnées (fiche d'évaluation datée du 2026-08-19 dans93docs/CONFORMITE.md ; chaque source a été sondée AVANT connexion) :9495 cartv_bio Répertoire public des entreprises certifiées biologiques96 du Québec (CARTV / SIPAB, produitsbioquebec.info).97 Formulaire Struts public « recherche par type98 d'opération » ; 7 types × toutes les régions.99 Fiches complètes : adresse, municipalité, région, CP,100 tél, site web, certificateur, date de certification.101 -> découverte + champ `certifications` structuré.102 ctaq Répertoire des membres du Conseil de la transformation103 alimentaire du Québec (conseiltaq.com,104 /ajax-search-organisation). On ne garde PAS les105 « Associés » (fournisseurs de services) — seulement les106 transformateurs. Fiche /organisation/<id> = site web.107 vendors_collectifs Champ `vendor` des boutiques collectives déjà108 connectées (paperole, galerieiris, wachiya — patron109 Signé Local prouvé) -> résolution prudente du site110 officiel par candidats de domaine dérivés du nom,111 validés par correspondance du titre de page.112 cibim Boulangeries artisanales membres de la CIBIM113 (cibim.org/membres) — répertoire recommandé par l'UPA.114 canardduquebec Producteurs — Éleveurs de canards et d'oies du Québec.115 lebongoutfraisdesiles Producteurs/transformateurs des Îles-de-la-Madeleine116 (région sous-couverte).117 acheterquebecois_mtl Catégories « Montréal / Fabriqué à Montréal »118 d'acheterquebecois.ca (Montréal sous-représentée ;119 PME MTL n'a aucun répertoire public « Fabriqué à120 Montréal » — constaté 2026-08-19).121122Écartées (raison consignée dans docs/CONFORMITE.md) : REQ open data123(WAF Cloudflare + licence CC-BY-NC-SA non commerciale), UPA Mangeons local124(app web décommissionnée — redirections vers upa.qc.ca/citoyen), Salon des125métiers d'art (salondesmetiersdart.com = coquille ; liste des exposants déjà126couverte par le répertoire CMAQ), Goûtez Lanaudière (CRM Eudonet toujours en127404, re-testé), PME MTL (aucun répertoire).128129Usage :130 python3 scripts/wave4_discovery.py harvest [source ...]131 python3 scripts/wave4_discovery.py integrate # additif, sérialisé132 # (vérifier qu'aucune passe133 # n'écrit stores.json)134"""135import argparse136import concurrent.futures as cf137import html as htmllib138import json139import os140import re141import subprocess142import sys143import time144import unicodedata145from collections import Counter146from urllib.parse import urlparse147148import requests149150ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))151RAW = os.path.join(ROOT, "data", "raw")152ENR = os.path.join(ROOT, "data", "enriched")153sys.path.insert(0, ROOT)154sys.path.insert(0, os.path.join(ROOT, "scripts"))155156for line in open(os.path.join(ROOT, ".env")).read().splitlines():157 if "=" in line and not line.startswith("#"):158 k, _, v = line.partition("=")159 os.environ.setdefault(k.strip(), v.strip())160161from verify import HDRS, POSTAL_RE, AREA_RE, verify_domain # noqa: E402162from aggregate import BLOCK, norm_domain # noqa: E402163164TAG_RE = re.compile(r"<[^>]+>")165SESS = requests.Session()166167168def strip_tags(s):169 return re.sub(r"\s+", " ", TAG_RE.sub(" ", htmllib.unescape(s or ""))).strip()170171172def get(url, timeout=25):173 try:174 r = SESS.get(url, headers=HDRS, timeout=timeout, allow_redirects=True)175 if r.status_code == 200:176 return r.text177 except Exception:178 pass179 return ""180181182def write_jsonl(name, records):183 os.makedirs(RAW, exist_ok=True)184 path = os.path.join(RAW, name + ".jsonl")185 with open(path, "w") as f:186 for r in records:187 f.write(json.dumps(r, ensure_ascii=False) + "\n")188 print(f"[harvest] {name}: {len(records)} entrées -> {path}", flush=True)189190191# ------------------------------------------------------------------ CARTV bio192# SIPAB (produitsbioquebec.info) : danse Struts en 4 temps, par type193# d'opération. Réponses en ISO-8859-1.194SIPAB_BASE = "http://www.produitsbioquebec.info"195SIPAB_ACTION = SIPAB_BASE + "/produitsbioquebec/DispatcherInterrogationGrandPublicFr.do"196SIPAB_TYPES = {197 "10": "Préparation alimentaire et transformation",198 "11": "Boissons alcoolisées",199 "20": "Production acéricole",200 "30": "Production animale",201 "40": "Production végétale",202 "50": "Récoltes sauvages et PFNL",203 "90": "Conditionnement (emballage et étiquetage)",204}205FIELD_RES = {206 "address": re.compile(r"Adresse:\s*([^<]+)"),207 "city": re.compile(r"Municipalité:\s*([^<]+)"),208 "region": re.compile(r"Région:\s*([^<]+)"),209 "postal": re.compile(r"Code postal:\s*([^<]+)"),210 "phone": re.compile(r"Tél\.:\s*([^<]+)"),211 "cert_date": re.compile(r"Date de certification:\s*([0-9-]+)"),212 "certifier": re.compile(r"Produits certifiés par:\s*([^<]+)"),213}214WEB_RE = re.compile(r'Site web:.*?<a href="([^"]+)"', re.S)215NAME_RE = re.compile(r'<font class="text1Bleu">([^<]+)</font>')216217218def sipab_search(code, label):219 """Une recherche complète pour un type d'opération -> liste de fiches."""220 sess = requests.Session()221 sess.get(SIPAB_BASE + "/interroGrandPublicFr.do", headers=HDRS, timeout=40)222 common = {"rechercheParProduitOuMunicipalite": "4", "langue": "Fr"}223 for action, extra in (224 ("rechercheParTypeOperation", {}),225 ("initInterrogationGrandPublicTypeOperationForm", {"codeTypesOperation": code}),226 ("rechercherDonneesProduitsCertifiesTypeOperationGrandPublic",227 {"codeTypesOperation": code, "codeRegionForChoixMultiple": "-1"})):228 data = dict(common, actionDemandee=action, **extra)229 r = sess.post(SIPAB_ACTION, data=data, headers=HDRS, timeout=180)230 time.sleep(1.0)231 # le serveur SIPAB sert de l'UTF-8 sans le déclarer (constaté : décodage232 # latin-1 = mojibake sur les champs accentués)233 html = r.content.decode("utf-8", "replace")234 out = []235 # chaque entreprise = une cellule class="celluleEntreprise"236 for cell in re.findall(r'<td class="celluleEntreprise">(.*?)</td>', html, re.S):237 nm = NAME_RE.search(cell)238 if not nm:239 continue240 rec = {"name": strip_tags(nm.group(1))[:100], "operation": label}241 for key, rx in FIELD_RES.items():242 m = rx.search(cell)243 rec[key] = strip_tags(m.group(1)).strip("\xa0 ") if m else ""244 # noms de régions SIPAB : « Saguenay--Lac-Saint-Jean » -> tiret cadratin245 # canonique du registre246 rec["region"] = rec.get("region", "").replace("--", "–")247 w = WEB_RE.search(cell)248 rec["website"] = htmllib.unescape(w.group(1)).strip() if w else ""249 out.append(rec)250 print(f" [cartv] {label}: {len(out)} entreprises", flush=True)251 return out252253254def harvest_cartv_bio():255 """7 recherches (une par type d'opération), toutes régions."""256 seen, records = {}, []257 for code, label in SIPAB_TYPES.items():258 for rec in sipab_search(code, label):259 key = (rec["name"].lower(), rec.get("city", "").lower())260 if key in seen: # même entreprise, autre type d'opération261 if label not in seen[key]["operations"]:262 seen[key]["operations"].append(label)263 continue264 postal = (rec.pop("postal") or "").replace(" ", "")265 fiche = {266 "url": SIPAB_BASE + "/interroGrandPublicFr.do",267 "title": rec["name"],268 "h1": rec["name"],269 "websites": [rec["website"]] if rec["website"] else [],270 "socials": [],271 "postal_prefix": postal[:3] if len(postal) >= 6 else None,272 "phone": rec.get("phone") or None,273 "regions_mentioned": [rec["region"]] if rec.get("region") else [],274 "text_sample": f"{rec.get('address','')} {rec.get('city','')}",275 # champs propres à la certification (exploités par276 # scripts/backfill_certifications.py)277 "city": rec.get("city", ""),278 "certifier": rec.get("certifier", ""),279 "cert_date": rec.get("cert_date", ""),280 "operations": [label],281 }282 seen[key] = fiche283 records.append(fiche)284 write_jsonl("cartv_bio", records)285286287# ----------------------------------------------------------------------- CTAQ288CTAQ_LIST = "https://conseiltaq.com/ajax-search-organisation?page={p}&type=&per_page=50&lang=fr"289CTAQ_CARD = re.compile(290 r'member-item-list js-block-link.*?href="(https://conseiltaq\.com/organisation/\d+)">([^<]+)</a>'291 r'.*?<div class="desc[^"]*">\s*([^<]*).*?(?:<div class="sector[^"]*">\s*([^<]*))?</div>', re.S)292293294def harvest_ctaq():295 fiches = {}296 for p in range(1, 30):297 html = get(CTAQ_LIST.format(p=p), timeout=40)298 if not html:299 break300 seg = html[html.find("Tous les membres"):]301 cards = CTAQ_CARD.findall(seg)302 if not cards:303 break304 for url, name, kind, sector in cards:305 kind = htmllib.unescape(kind.strip())306 # on ne garde que les FABRICANTS : transformateurs alimentaires et307 # fabricants d'ingrédients ; les « Associés », « Fournisseur308 # produits et services », « Affilié » etc. sont des fournisseurs309 # de l'industrie, pas des fabricants de produits québécois310 if kind not in ("Transformateur", "Fournisseur d'ingrédients"):311 continue312 fiches.setdefault(url, {"name": strip_tags(name), "kind": kind,313 "sector": strip_tags(sector or "")})314 time.sleep(0.5)315 print(f"[ctaq] {len(fiches)} fiches membres (hors Associés) à visiter", flush=True)316 records, done = [], 0317 for url, meta in fiches.items():318 done += 1319 html = get(url, timeout=30)320 time.sleep(0.4)321 if done % 50 == 0:322 print(f" [ctaq] {done}/{len(fiches)}", flush=True)323 if not html:324 continue325 body = html[html.find("</header>"):] if "</header>" in html else html326 webs = []327 for u in re.findall(r'href="(https?://[^"]+)"', body):328 host = (urlparse(u).netloc or "").lower()329 if not host or "conseiltaq" in host:330 continue331 if any(s in host for s in ("facebook", "instagram", "linkedin", "youtube",332 "twitter", "google", "w3.org", "jsdelivr",333 "fonts.", "gstatic", "recaptcha")):334 continue335 webs.append(u)336 text = strip_tags(body[:150000])337 postal = POSTAL_RE.search(text)338 phone = AREA_RE.search(text)339 records.append({340 "url": url,341 "title": meta["name"],342 "h1": meta["name"],343 "websites": list(dict.fromkeys(webs))[:2],344 "socials": [],345 "postal_prefix": postal.group(0)[:3] if postal else None,346 "phone": phone.group(0) if phone else None,347 "regions_mentioned": [],348 "text_sample": (meta["kind"] + " — " + meta["sector"])[:200],349 "category_hint": meta["sector"],350 })351 records = [r for r in records if r["websites"]]352 write_jsonl("ctaq", records)353354355# ------------------------------------------------- vendors des collectifs356COLLECTIFS = ["paperole.com", "galerieiris.com", "wachiya.com"]357STOP_TOKENS = {"inc", "enr", "ltee", "les", "the", "and", "et", "de", "du",358 "la", "le", "des", "by", "par", "studio", "atelier", "co"}359360361def _slug(name):362 s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()363 return re.sub(r"[^a-z0-9]", "", s.lower())364365366def _norm_name(name):367 s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode().lower()368 return " ".join(t for t in re.findall(r"[a-z0-9]+", s) if t not in STOP_TOKENS)369370371def _curl(url, timeout=20):372 """GET via curl (mécanisme du projet pour éviter le 429 TLS de requests)."""373 try:374 r = subprocess.run(["curl", "-sL", "-A", HDRS["User-Agent"], "--max-time",375 str(timeout), "--max-filesize", "400000", url],376 capture_output=True, timeout=timeout + 10)377 return r.stdout.decode("utf-8", "replace")378 except Exception:379 return ""380381382def harvest_vendors_collectifs(cap=400):383 from fabrika import db as fdb384 con = fdb.connect()385 rows = con.execute(386 "SELECT vendor, COUNT(*) AS n, GROUP_CONCAT(DISTINCT store_id) AS sids "387 "FROM products WHERE active=1 AND vendor<>'' AND store_id IN (%s) "388 "GROUP BY vendor ORDER BY n DESC" % ",".join("?" * len(COLLECTIFS)),389 COLLECTIFS).fetchall()390 known_names = {_norm_name(r[0]) for r in391 con.execute("SELECT name FROM stores") if r[0]}392 known_doms = {r[0] for r in con.execute("SELECT id FROM stores")}393 con.close()394 # candidats déjà connus du pipeline (peu importe le statut)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 slug = _slug(v)406 if not (4 <= len(slug) <= 30):407 continue408 if probes >= cap:409 break410 found = None411 for dom in (slug + ".com", slug + ".ca"):412 if dom in known_doms or BLOCK.search(dom):413 continue414 probes += 1415 html = _curl(f"https://{dom}")416 time.sleep(0.3)417 if not html:418 continue419 title_m = re.search(r"<title[^>]*>(.*?)</title>", html, re.S | re.I)420 title = _norm_name(strip_tags(title_m.group(1))[:120]) if title_m else ""421 # garde-fou anti-faux-positif : le titre de la page doit422 # recouper le nom de la marque423 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"Marque vendue par les collectifs d'artisans {sids} "435 f"({n} produits) — site officiel résolu et validé par titre",436 "query": f"vendor:{v}",437 })438 print(f"[vendors] {probes} sondes, {len(records)} sites résolus", flush=True)439 write_jsonl("vendors_collectifs", records)440441442# --------------------------------------------- petits répertoires sectoriels443def harvest_single_page(source, page_url, own_domain, region_hint, evidence):444 html = get(page_url, timeout=40)445 records, seen = [], set()446 for url, label in re.findall(r'<a\s[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>',447 html, re.S | re.I):448 url = htmllib.unescape(url)449 host = (urlparse(url).netloc or "").lower()450 if not host or own_domain in host:451 continue452 if any(s in host for s in ("facebook", "instagram", "linkedin", "youtube",453 "tiktok", "pinterest", "twitter", "x.com")):454 continue455 dom = norm_domain(url)456 if not dom or dom in seen or BLOCK.search(dom) or BLOCK.search(url):457 continue458 seen.add(dom)459 label = strip_tags(label)460 records.append({461 "name": label if 2 < len(label) < 80 else "",462 "domain": dom, "url": url, "region_hint": region_hint,463 "category_hint": "", "evidence": evidence, "query": page_url,464 })465 write_jsonl(source, records)466467468def harvest_aq_mtl():469 """Catégories montréalaises d'acheterquebecois.ca (source déjà couverte,470 pages régionales jamais moissonnées). Pagination /page/N/."""471 base = "https://acheterquebecois.ca"472 cats = ["fabrique-a-montreal", "artisanat", "vetements-2", "alimentation"]473 records, seen = [], set()474 for cat in cats:475 for page in range(1, 8):476 url = f"{base}/montreal/{cat}/" + (f"page/{page}/" if page > 1 else "")477 html = get(url, timeout=30)478 if not html:479 break480 found = 0481 for u, label in re.findall(482 r'<a\s[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>', html, re.S | re.I):483 dom = norm_domain(u)484 if (not dom or dom in seen or "acheterquebecois" in dom485 or BLOCK.search(dom) or BLOCK.search(u)):486 continue487 seen.add(dom)488 found += 1489 records.append({490 "name": strip_tags(label)[:80], "domain": dom, "url": u,491 "region_hint": "Montréal", "category_hint": cat,492 "evidence": "Répertorié « Fabriqué à Montréal » / catégorie "493 "montréalaise sur acheterquebecois.ca",494 "query": url,495 })496 time.sleep(0.4)497 if not found:498 break499 write_jsonl("acheterquebecois_mtl", records)500501502HARVESTERS = {503 "cartv_bio": harvest_cartv_bio,504 "ctaq": harvest_ctaq,505 "vendors_collectifs": harvest_vendors_collectifs,506 "cibim": lambda: harvest_single_page(507 "cibim", "https://cibim.org/membres/", "cibim.org", "",508 "Boulangerie artisanale membre de la CIBIM (Corporation des "509 "boulangers-pâtissiers indépendants)"),510 "canardduquebec": lambda: harvest_single_page(511 "canardduquebec", "https://canardduquebec.com/nos-producteurs/",512 "canardduquebec.com", "",513 "Producteur membre des Éleveurs de canards et d'oies du Québec"),514 "lebongoutfraisdesiles": lambda: harvest_single_page(515 "lebongoutfraisdesiles",516 "https://lebongoutfraisdesiles.com/production-et-transformation/",517 "lebongoutfraisdesiles.com", "Gaspésie–Îles-de-la-Madeleine",518 "Producteur/transformateur membre du Bon goût frais des Îles-de-la-Madeleine"),519 "acheterquebecois_mtl": harvest_aq_mtl,520}521522WAVE4_SOURCES = list(HARVESTERS)523524# Boutiques Shopify re-testées via curl (429 TLS python requests = gotcha525# connu) — grosses places de marché de produits québécois, connectées avec526# leur nature affichée (voir docs/CONFORMITE.md).527KNOWN_SHOPIFY = [528 {"id": "epipresto.ca", "name": "EPIPRESTO", "store_kind": "collectif",529 "origin_class": "C", "origin_confidence": 0.7,530 "origin_evidence": "Place de marché regroupant des épiceries et producteurs "531 "locaux du Québec (re-testée via curl le 2026-08-19 ; "532 "l'ancienne vérification avait échoué sur un 429 TLS)",533 "categories": ["epicerie"], "region": ""},534 {"id": "laboiteagrains.com", "name": "La Boite à Grains",535 "store_kind": "revendeur",536 "origin_class": "C", "origin_confidence": 0.7,537 "origin_evidence": "Épicerie santé de Gatineau (revendeur — produits "538 "québécois et autres ; re-testée via curl le 2026-08-19)",539 "categories": ["epicerie"], "region": "Outaouais"},540]541542543def harvest(only=None):544 os.makedirs(RAW, exist_ok=True)545 for name, fn in HARVESTERS.items():546 if only and name not in only:547 continue548 print(f"[harvest] === {name} ===", flush=True)549 fn()550551552def integrate():553 """Intégration additive au registre + DB (mêmes garde-fous que la vague 3)."""554 from datetime import date555 import build_registry as br556 from fabrika import db as fdb557558 for s in WAVE4_SOURCES:559 assert s in br.SOURCE_PRIORS, f"prior manquant dans build_registry: {s}"560561 subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "aggregate.py")],562 check=True)563564 cands = {}565 with open(os.path.join(ENR, "candidates.jsonl")) as f:566 for line in f:567 c = json.loads(line)568 cands[c["domain"]] = c569570 verified_path = os.path.join(ENR, "verified.jsonl")571 verified = {}572 with open(verified_path) as f:573 for line in f:574 v = json.loads(line)575 verified[v["domain"]] = v576577 reg_path = os.path.join(ROOT, "data", "stores.json")578 reg = json.load(open(reg_path))579 existing_ids = {s["id"] for s in reg["stores"]}580581 new_domains = sorted(d for d in cands582 if d not in verified and d not in existing_ids)583 print(f"[integrate] {len(new_domains)} nouveaux domaines à vérifier", flush=True)584585 new_recs = []586 with cf.ThreadPoolExecutor(12) as ex:587 for i, rec in enumerate(ex.map(verify_domain, new_domains)):588 new_recs.append(rec)589 if (i + 1) % 100 == 0:590 print(f" verify {i+1}/{len(new_domains)}", flush=True)591 with open(verified_path, "a") as f:592 for r in new_recs:593 f.write(json.dumps(r, ensure_ascii=False) + "\n")594 verified[r["domain"]] = r595596 added, skipped_dup, skipped_qc, skipped_dead = [], 0, 0, 0597 for dom in new_domains:598 cand, ver = cands[dom], verified.get(dom, {})599 if not ver.get("active"):600 skipped_dead += 1601 continue602 final_dom = ver.get("final_domain") or dom603 if final_dom in existing_ids:604 skipped_dup += 1605 continue606 qc_signal = any(ver.get(k) for k in ("qc_postal", "qc_phone", "tld_quebec",607 "mentions_quebec", "made_in_qc_wording"))608 qc_source = any(s in br.QC_ONLY_SOURCES for s in cand.get("sources", []))609 if not qc_signal and not qc_source:610 skipped_qc += 1611 continue612 cls, conf, ev = br.classify(cand, ver)613 default_cat = next((br.SOURCE_PRIORS[s][3] for s in br.PRIORITY614 if s in cand.get("sources", []) and br.SOURCE_PRIORS[s][3]), None)615 platform = ver.get("platform") or ""616 catalog_endpoint = ver.get("catalog_endpoint") or ""617 if platform == "wix" and not catalog_endpoint:618 catalog_endpoint = "/_api/wix-ecommerce-storefront-web/api"619 fu = urlparse(ver.get("final_url") or f"https://{final_dom}")620 store = {621 "id": final_dom,622 "name": br.clean_name(cand, ver),623 "url": f"{fu.scheme}://{fu.netloc}",624 "platform": platform,625 "catalog_endpoint": catalog_endpoint,626 "city": "",627 "region": br.pick_region(cand) or br.region_from_postal(cand, ver),628 "postal_prefix": cand.get("postal_prefix") or (ver.get("qc_postal") or "")[:3] or None,629 "phone": cand.get("phone") or ver.get("qc_phone"),630 "origin_class": cls,631 "origin_confidence": conf,632 "origin_evidence": ev,633 "categories": [default_cat] if default_cat else [],634 "socials": (cand.get("socials") or [])[:4] or ver.get("socials", []),635 "discovery_sources": cand.get("sources", []),636 "discovery_source_urls": cand.get("source_pages", [])[:5],637 "language": ver.get("language"),638 "ecommerce": bool(ver.get("has_cart") or catalog_endpoint),639 "verification_date": ver.get("checked_at") or str(date.today()),640 "status": "verified" if (conf >= 0.6 and ver.get("mentions_quebec")) else "probable",641 "enabled": bool(catalog_endpoint),642 }643 existing_ids.add(final_dom)644 added.append(store)645646 # --- boutiques Shopify re-testées via curl (hors pipeline verify) ------647 for spec in KNOWN_SHOPIFY:648 if spec["id"] in existing_ids:649 continue650 probe = _curl(f"https://{spec['id']}/products.json?limit=1")651 if '"products"' not in probe[:200]:652 print(f"[integrate] {spec['id']}: /products.json injoignable — ignorée")653 continue654 store = {655 "id": spec["id"], "name": spec["name"], "url": f"https://{spec['id']}",656 "platform": "shopify", "catalog_endpoint": "/products.json",657 "city": "", "region": spec["region"], "postal_prefix": None,658 "phone": None, "origin_class": spec["origin_class"],659 "origin_confidence": spec["origin_confidence"],660 "origin_evidence": spec["origin_evidence"],661 "categories": spec["categories"], "socials": [],662 "discovery_sources": ["retest_curl_2026_08_19"],663 "discovery_source_urls": [], "language": "fr", "ecommerce": True,664 "verification_date": str(date.today()), "status": "verified",665 "enabled": True, "store_kind": spec["store_kind"],666 }667 existing_ids.add(spec["id"])668 added.append(store)669670 reg["stores"].extend(added)671 reg["count"] = len(reg["stores"])672 reg["generated"] = str(date.today())673 json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)674675 con = fdb.connect()676 for s in added:677 fdb.upsert_store(con, s)678 con.commit(); con.close()679680 enabled = [s["id"] for s in added if s["enabled"]]681 per_plat = Counter(s["platform"] or "(aucune)" for s in added)682 per_src = Counter(src for s in added for src in s["discovery_sources"])683 per_cls = Counter(s["origin_class"] for s in added)684 print(f"[integrate] boutiques ajoutées: {len(added)} | connectables (enabled): {len(enabled)}")685 print(f"[integrate] écartées — mortes/injoignables: {skipped_dead}, "686 f"dédup domaine final: {skipped_dup}, sans preuve QC: {skipped_qc}")687 print("[integrate] par plateforme:", dict(per_plat.most_common()))688 print("[integrate] par source:", dict(per_src.most_common()))689 print("[integrate] par classe:", dict(per_cls))690 with open(os.path.join(ROOT, "data", "wave4_new_enabled.txt"), "w") as f:691 f.write("\n".join(enabled) + "\n")692 if enabled:693 print("[integrate] à synchroniser: python run.py sync $(cat data/wave4_new_enabled.txt)")694695696if __name__ == "__main__":697 ap = argparse.ArgumentParser()698 ap.add_argument("cmd", choices=["harvest", "integrate"])699 ap.add_argument("only", nargs="*", help="sources précises (harvest)")700 args = ap.parse_args()701 harvest(args.only or None) if args.cmd == "harvest" else integrate()702