SPB Git

Repository Public

aggregate.py 9.2 KB 223 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/aggregate.py11# Description      : Aggregate raw directory harvests into a deduplicated12#                    candidate-domain list.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1216# Last Modified    : 2026-08-1217#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"""Aggregate raw directory harvests into a deduplicated candidate-domain list.9192Reads every data/raw/*.jsonl produced by harvest.py, extracts outbound93business websites, normalizes domains, merges provenance, and writes94data/enriched/candidates.jsonl (one record per unique domain).95"""96import glob97import json98import os99import re100from collections import defaultdict101from urllib.parse import urlparse102103ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))104RAW = os.path.join(ROOT, "data", "raw")105OUT = os.path.join(ROOT, "data", "enriched")106os.makedirs(OUT, exist_ok=True)107108# Domains that are never an independent Quebec store website109BLOCK = re.compile(r"""(?xi)110  (google\.|gouv\.qc|quebec\.ca$|canada\.ca$|wikipedia|facebook|instagram|linkedin|111   youtube|tiktok|twitter|x\.com$|pinterest|etsy\.com$|amazon\.|ebay\.|walmart|112   saq\.com|iga\.net|metro\.ca|sobeys|provigo|maxi\.ca|costco|canadiantire|113   eventbrite|mailchimp|list-manage|linktr\.ee|bit\.ly|goo\.gl|shopify\.com$|114   squarespace\.com$|wix\.com$|wordpress\.com$|godaddy|weebly\.com$|115   tourisme|bonjourquebec|alimentsduquebec|lesproduitsduquebec|metiersdart|116   vinsduquebec|cidreduquebec|fromagesdici|erabledici|artisansaloeuvre|117   marchespublicsduquebec|signelocal|ideecadeauquebec|acheterquebecois|118   distilleriesduquebec|ambq\.ca|terroiretsaveurs|upa\.qc|mapaq|119   lapresse|radio-canada|journaldemontreal|journaldequebec|tvanouvelles|120   lesaffaires|ledevoir|huffington|narcity|121   ticketmaster|opentable|doordash|ubereats|skipthedishes|122   yelp\.|tripadvisor|booking\.|airbnb|expedia|123   paypal|stripe|square\.site$|interac|124   vimeo|flickr|issuu|calameo|soundcloud|spotify|125   apple\.com|play\.google|microsoft|adobe\.|126   fondationdesgourmands|recettes?\.|allrecipes|ricardocuisine|127   zone\.coop$|desjardins|banquenationale|bmo\.|rbc\.)""")128129QC_HINT_TLD = (".quebec", ".qc.ca")130131132def norm_domain(url):133    try:134        host = urlparse(url).netloc.lower()135    except Exception:136        return None137    host = host.split(":")[0].removeprefix("www.")138    if not host or "." not in host:139        return None140    return host141142143def main():144    cands = {}145    per_source_counts = defaultdict(int)146    for path in sorted(glob.glob(os.path.join(RAW, "*.jsonl"))):147        source = os.path.basename(path)[:-6]148        with open(path) as f:149            for line in f:150                try:151                    rec = json.loads(line)152                except Exception:153                    continue154                if rec.get("error"):155                    continue156                # schéma "search sweep" : {name, domain, url, region_hint, category_hint, evidence, query}157                if "websites" not in rec and rec.get("domain"):158                    rec = {159                        "url": rec.get("query", ""),160                        "h1": rec.get("name", ""),161                        "title": rec.get("name", ""),162                        "websites": [rec.get("url") or f"https://{rec['domain']}"],163                        "socials": [],164                        "postal_prefix": None,165                        "phone": None,166                        "regions_mentioned": [rec["region_hint"]] if rec.get("region_hint") else [],167                        "text_sample": rec.get("evidence", ""),168                        "category_hint": rec.get("category_hint", ""),169                    }170                name = (rec.get("h1") or rec.get("title") or "").strip()171                for w in rec.get("websites", []):172                    dom = norm_domain(w)173                    if not dom or BLOCK.search(dom) or BLOCK.search(w):174                        continue175                    c = cands.setdefault(dom, {176                        "domain": dom,177                        "urls": [],178                        "names": [],179                        "sources": [],180                        "source_pages": [],181                        "socials": [],182                        "postal_prefix": None,183                        "phone": None,184                        "regions_mentioned": [],185                    })186                    if w not in c["urls"]:187                        c["urls"].append(w)188                    if name and name not in c["names"]:189                        c["names"].append(name)190                    if source not in c["sources"]:191                        c["sources"].append(source)192                        per_source_counts[source] += 1193                    if rec["url"] not in c["source_pages"]:194                        c["source_pages"].append(rec["url"])195                    for s in rec.get("socials", []):196                        if s not in c["socials"]:197                            c["socials"].append(s)198                    c["postal_prefix"] = c["postal_prefix"] or rec.get("postal_prefix")199                    c["phone"] = c["phone"] or rec.get("phone")200                    for r in rec.get("regions_mentioned", []):201                        if r not in c["regions_mentioned"]:202                            c["regions_mentioned"].append(r)203204    # signelocal vendors (no website yet -> candidates by name only, kept separately)205    sl_path = os.path.join(RAW, "signelocal_vendors.json")206    vendors = []207    if os.path.exists(sl_path):208        vendors = json.load(open(sl_path))209210    out_path = os.path.join(OUT, "candidates.jsonl")211    with open(out_path, "w") as f:212        for dom in sorted(cands):213            f.write(json.dumps(cands[dom], ensure_ascii=False) + "\n")214    print(f"unique candidate domains: {len(cands)}")215    print("contributions per source (unique domains added):")216    for s, n in sorted(per_source_counts.items(), key=lambda x: -x[1]):217        print(f"  {n:6d}  {s}")218    print(f"signelocal vendors (name-only candidates): {len(vendors)}")219220221if __name__ == "__main__":222    main()223
Files main
Menu

Theme