SPB Git

Repository Public

backfill_certifications.py 8.7 KB 227 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/backfill_certifications.py11# Description      : Champ structuré `certifications` sur les fiches boutiques12#                    (vague 4).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"""Champ structuré `certifications` sur les fiches boutiques (vague 4).9192Deux gisements :93  1. Les sources de découverte qui SONT des certifications/labels vérifiés94     (Aliments du Québec, Les Produits du Québec, Économusée, Arrêts95     gourmands) -> label dérivé de discovery_sources.96  2. Le répertoire public CARTV/SIPAB des entreprises certifiées bio97     (data/raw/cartv_bio.jsonl, moissonné par wave4_discovery.py) ->98     appariement par domaine (fort) puis par nom normalisé unique99     (prudent), avec certificateur + date.100101Écrit dans la DB (stores.certifications, JSON) ET dans data/stores.json102(champ `certifications`) — ⚠ sérialiser avec les autres écrivains du103registre. Rejouable (fusion sans doublon par `label`).104105Usage : .venv/bin/python scripts/backfill_certifications.py106"""107import json108import re109import sys110import unicodedata111from pathlib import Path112113ROOT = Path(__file__).resolve().parent.parent114sys.path.insert(0, str(ROOT))115sys.path.insert(0, str(ROOT / "scripts"))116117from fabrika import db            # noqa: E402118from aggregate import norm_domain  # noqa: E402119120SOURCE_LABELS = {121    "alimentsduquebec_ent": ("Aliments du Québec",122                             "Certification Aliments du Québec (adhérent vérifié)"),123    "lesproduitsduquebec_ent": ("Les Produits du Québec",124                                "Certification Les Produits du Québec"),125    "artisansaloeuvre": ("Économusée", "Accréditation réseau Économusée / "126                                       "Artisans à l'œuvre"),127    "arretsgourmands": ("Arrêt gourmand certifié",128                        "Arrêt gourmand certifié (Chaudière-Appalaches)"),129}130131STOP = {"inc", "enr", "ltee", "les", "la", "le", "de", "du", "des", "et"}132133134def norm_name(name):135    s = unicodedata.normalize("NFKD", name or "").encode("ascii", "ignore").decode().lower()136    return " ".join(t for t in re.findall(r"[a-z0-9]+", s) if t not in STOP)137138139def main():140    con = db.connect()141    stores = {r["id"]: dict(r) for r in con.execute(142        "SELECT id, name, discovery_sources, certifications FROM stores")}143    certs = {sid: {c["label"]: c for c in json.loads(s.get("certifications") or "[]")}144             for sid, s in stores.items()}145146    # 1) labels dérivés des sources de découverte certifiantes147    n_src = 0148    for sid, s in stores.items():149        for src in json.loads(s.get("discovery_sources") or "[]"):150            if src in SOURCE_LABELS:151                label, detail = SOURCE_LABELS[src]152                if label not in certs[sid]:153                    certs[sid][label] = {"label": label, "detail": detail,154                                         "source": src}155                    n_src += 1156157    # 2) répertoire CARTV bio158    cartv_path = ROOT / "data" / "raw" / "cartv_bio.jsonl"159    n_dom = n_name = 0160    if cartv_path.exists():161        recs = [json.loads(l) for l in open(cartv_path)]162        by_dom = {}163        for r in recs:164            for w in r.get("websites", []):165                d = norm_domain(w)166                if d:167                    by_dom.setdefault(d, r)168        # index nom normalisé -> fiches CARTV (pour l'appariement prudent)169        by_name = {}170        for r in recs:171            by_name.setdefault(norm_name(r["title"]), []).append(r)172        name_to_sids = {}173        for sid, s in stores.items():174            name_to_sids.setdefault(norm_name(s["name"]), []).append(sid)175176        def add_bio(sid, r, how):177            label = "Biologique — CARTV"178            if label in certs[sid]:179                return 0180            certs[sid][label] = {181                "label": label,182                "detail": "Appellation biologique du Québec (répertoire public "183                          "CARTV/SIPAB)",184                "certifier": r.get("certifier") or None,185                "since": r.get("cert_date") or None,186                "operations": r.get("operations") or [],187                "source": "cartv_bio", "match": how,188            }189            return 1190191        for sid in stores:192            if sid in by_dom:193                n_dom += add_bio(sid, by_dom[sid], "domaine")194        for nname, rs in by_name.items():195            if len(rs) != 1 or not nname or len(nname) < 6:196                continue197            sids = name_to_sids.get(nname, [])198            if len(sids) == 1 and "Biologique — CARTV" not in certs[sids[0]]:199                n_name += add_bio(sids[0], rs[0], "nom_unique")200201    # écriture DB202    n_stores = 0203    for sid, cmap in certs.items():204        if not cmap:205            continue206        con.execute("UPDATE stores SET certifications=? WHERE id=?",207                    (json.dumps(list(cmap.values()), ensure_ascii=False), sid))208        n_stores += 1209    con.commit(); con.close()210211    # écriture registre (champ informatif, la DB fait foi pour l'API)212    reg_path = ROOT / "data" / "stores.json"213    reg = json.load(open(reg_path))214    for s in reg["stores"]:215        cmap = certs.get(s["id"])216        if cmap:217            s["certifications"] = list(cmap.values())218    json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)219220    print(f"certifications : {n_stores} boutiques porteuses "221          f"(+{n_src} labels de sources, +{n_dom} bio par domaine, "222          f"+{n_name} bio par nom unique)")223224225if __name__ == "__main__":226    main()227
Files main
Menu

Theme