SPB Git

Repository Public

export_deliverables.py 9.5 KB 217 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/export_deliverables.py11# Description      : Export research deliverables from the pipeline outputs.12# Module           : scripts13# Repository       : https://git.spboucher.ai/fabri-ka14# Created          : 2026-08-1215# Last Modified    : 2026-08-1216#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author           : Simon-Pierre Boucher22# Position         : Professor of Finance23# Institution      : Université du Québec en Outaouais (UQO)24# Department       : Département des sciences administratives25# Organization     : SP Boucher26#27# Website          : https://spboucher.ai28# Git              : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General          : info@spboucher.ai35# Professional     : contact@spboucher.ai36# Direct           : simon@spboucher.ai37# Research         : research@spboucher.ai38# Development      : dev@spboucher.ai39# Support          : support@spboucher.ai40# Security/Admin   : admin@spboucher.ai41# Notifications    : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification   : Public68# Distribution     : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License          : None specified (no license file in this repository)82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Export research deliverables from the pipeline outputs.9091Produces in deliverables/:92  quebec_stores.csv / quebec_stores.json   (deduplicated verified dataset)93  unverified_candidates.csv                (dead/unreachable/name-only candidates)94  sources.csv                              (all sources used)95"""96import csv97import json98import os99from datetime import date100101ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))102DEL = os.path.join(ROOT, "deliverables")103os.makedirs(DEL, exist_ok=True)104105FIELDS = ["business_name", "domain", "website_url", "store_url", "city",106          "administrative_region", "postal_code_prefix", "latitude", "longitude",107          "primary_category", "secondary_categories", "business_type",108          "origin_classification", "origin_confidence", "origin_evidence",109          "products_summary", "example_products", "ecommerce", "ecommerce_platform",110          "direct_checkout", "ships_within_quebec", "ships_within_canada",111          "pickup_available", "language", "instagram", "facebook",112          "discovery_source", "discovery_source_url", "verification_source",113          "verification_date", "status"]114115116def store_row(s, product_info):117    insta = next((x for x in s.get("socials", []) if "instagram" in x), "")118    fb = next((x for x in s.get("socials", []) if "facebook" in x), "")119    pinfo = product_info.get(s["id"], {})120    return {121        "business_name": s["name"],122        "domain": s["id"],123        "website_url": s["url"],124        "store_url": s["url"] + (s.get("catalog_endpoint") or ""),125        "city": s.get("city") or "",126        "administrative_region": s.get("region") or "",127        "postal_code_prefix": s.get("postal_prefix") or "",128        "latitude": None, "longitude": None,129        "primary_category": (s.get("categories") or [""])[0],130        "secondary_categories": json.dumps(s.get("categories", [])[1:], ensure_ascii=False),131        "business_type": "producteur/fabricant" if s["origin_class"] == "A"132                          else ("détaillant" if s["origin_class"] == "C" else ""),133        "origin_classification": s["origin_class"],134        "origin_confidence": s["origin_confidence"],135        "origin_evidence": s["origin_evidence"],136        "products_summary": pinfo.get("summary", ""),137        "example_products": json.dumps(pinfo.get("examples", []), ensure_ascii=False),138        "ecommerce": s.get("ecommerce", False),139        "ecommerce_platform": s.get("platform") or "",140        "direct_checkout": bool(s.get("catalog_endpoint")) or s.get("ecommerce", False),141        "ships_within_quebec": None, "ships_within_canada": None, "pickup_available": None,142        "language": json.dumps([s["language"]] if s.get("language") else []),143        "instagram": insta, "facebook": fb,144        "discovery_source": ";".join(s.get("discovery_sources", [])),145        "discovery_source_url": (s.get("discovery_source_urls") or [""])[0],146        "verification_source": "fabri-ka verify pipeline (fetch homepage + catalog probe)",147        "verification_date": s.get("verification_date", ""),148        "status": s.get("status", "probable"),149    }150151152def main():153    reg = json.load(open(os.path.join(ROOT, "data", "stores.json")))["stores"]154155    # infos produits depuis la BD (si présente)156    product_info = {}157    dbp = os.path.join(ROOT, "data", "fabrika.db")158    if os.path.exists(dbp):159        import sqlite3160        con = sqlite3.connect(dbp)161        for sid, n in con.execute("SELECT store_id, COUNT(*) FROM products WHERE active=1 GROUP BY store_id"):162            product_info[sid] = {"summary": f"{n} produits en ligne agrégés", "examples": []}163        for sid in list(product_info):164            ex = [r[0] for r in con.execute(165                "SELECT title FROM products WHERE store_id=? AND active=1 LIMIT 3", (sid,))]166            product_info[sid]["examples"] = ex167        con.close()168169    rows = [store_row(s, product_info) for s in reg]170    with open(os.path.join(DEL, "quebec_stores.csv"), "w", newline="") as f:171        w = csv.DictWriter(f, fieldnames=FIELDS)172        w.writeheader()173        w.writerows(rows)174    with open(os.path.join(DEL, "quebec_stores.json"), "w") as f:175        json.dump({"generated": str(date.today()), "count": len(rows), "stores": rows},176                  f, ensure_ascii=False, indent=1)177    print(f"quebec_stores: {len(rows)} rows")178179    # --- unverified candidates: candidats non actifs + vendeurs nom-seulement180    cands = {}181    with open(os.path.join(ROOT, "data", "enriched", "candidates.jsonl")) as f:182        for line in f:183            c = json.loads(line)184            cands[c["domain"]] = c185    vers = {}186    with open(os.path.join(ROOT, "data", "enriched", "verified.jsonl")) as f:187        for line in f:188            v = json.loads(line)189            vers[v["domain"]] = v190    unv = []191    for dom, c in sorted(cands.items()):192        v = vers.get(dom, {})193        if v.get("active"):194            continue195        unv.append({"business_name": (c.get("names") or [dom])[0], "domain": dom,196                    "reason": "site inaccessible ou hors-ligne lors de la vérification",197                    "http_status": v.get("status"),198                    "discovery_source": ";".join(c.get("sources", [])),199                    "discovery_source_url": (c.get("source_pages") or [""])[0]})200    sl = os.path.join(ROOT, "data", "raw", "signelocal_vendors.json")201    if os.path.exists(sl):202        for vend in json.load(open(sl)):203            unv.append({"business_name": vend["vendor"], "domain": "",204                        "reason": "marque Signé Local — site web propre à identifier",205                        "http_status": None, "discovery_source": "signelocal",206                        "discovery_source_url": "https://www.signelocal.com"})207    with open(os.path.join(DEL, "unverified_candidates.csv"), "w", newline="") as f:208        w = csv.DictWriter(f, fieldnames=["business_name", "domain", "reason",209                                          "http_status", "discovery_source", "discovery_source_url"])210        w.writeheader()211        w.writerows(unv)212    print(f"unverified_candidates: {len(unv)} rows")213214215if __name__ == "__main__":216    main()217
Files main
Menu

Theme