SPB Git

Repository Public

harvest.py 12.9 KB 309 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/harvest.py11# Description      : Generic directory harvester for the Quebec store discovery12#                    pipeline.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"""Generic directory harvester for the Quebec store discovery pipeline.9192For each configured source: collect entity-page URLs (from sitemaps or listing93pages), fetch each entity page (with on-disk cache), and extract structured94signals: business name, outbound website links, social links, phone, postal95code, city/region mentions, categories.9697Output: data/raw/<source>.jsonl  (one record per entity page)98"""99import concurrent.futures as cf100import hashlib101import json102import os103import re104import sys105import time106from urllib.parse import urlparse, urljoin107108import requests109from bs4 import BeautifulSoup110111ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))112CACHE = os.path.join(ROOT, "data", "cache")113RAW = os.path.join(ROOT, "data", "raw")114os.makedirs(CACHE, exist_ok=True)115os.makedirs(RAW, exist_ok=True)116117HDRS = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",118        "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}119120SOCIAL_HOSTS = ("facebook.com", "instagram.com", "twitter.com", "x.com", "linkedin.com",121                "youtube.com", "tiktok.com", "pinterest.")122JUNK_HOSTS = ("google.", "goo.gl", "maps.app", "apple.com", "wp.me", "bit.ly", "mailchi",123              "eepurl", "linktr.ee", "youtu.be", "vimeo.com", "flickr.com", "issuu.com",124              "addtoany", "sharethis", "twitter.com", "cloudfront", "list-manage",125              "doubleclick", "shopify.com", "squarespace.com", "wordpress.org", "wix.com")126127POSTAL_RE = re.compile(r"\b([GHJ]\d[A-Z])\s?\d[A-Z]\d\b")128PHONE_RE = re.compile(r"\(?\b(418|514|450|819|579|581|438|873|367|263|354)\)?[\s.\-]?\d{3}[\s.\-]?\d{4}\b")129REGIONS = ["Bas-Saint-Laurent", "Saguenay", "Lac-Saint-Jean", "Capitale-Nationale", "Mauricie",130           "Estrie", "Montréal", "Montreal", "Outaouais", "Abitibi", "Témiscamingue", "Côte-Nord",131           "Nord-du-Québec", "Gaspésie", "Îles-de-la-Madeleine", "Chaudière-Appalaches", "Laval",132           "Lanaudière", "Laurentides", "Montérégie", "Centre-du-Québec", "Cantons-de-l'Est"]133134135def cache_path(url):136    h = hashlib.sha1(url.encode()).hexdigest()137    return os.path.join(CACHE, h[:2], h + ".html")138139140def fetch(url, delay=0.0, timeout=25):141    p = cache_path(url)142    if os.path.exists(p):143        with open(p, encoding="utf-8", errors="replace") as f:144            return f.read()145    try:146        r = requests.get(url, headers=HDRS, timeout=timeout)147        if r.status_code != 200:148            return ""149        os.makedirs(os.path.dirname(p), exist_ok=True)150        with open(p, "w", encoding="utf-8") as f:151            f.write(r.text)152        if delay:153            time.sleep(delay)154        return r.text155    except Exception:156        return ""157158159def sitemap_urls(root, depth=0):160    xml = fetch(root)161    locs = re.findall(r"<loc>\s*(.*?)\s*</loc>", xml)162    if "<sitemapindex" in xml and depth < 2:163        out = []164        for l in locs:165            out += sitemap_urls(l, depth + 1)166        return out167    return locs168169170def extract_entity(url, html, source_host):171    soup = BeautifulSoup(html, "html.parser")172    title = soup.title.get_text(" ", strip=True) if soup.title else ""173    h1 = soup.h1.get_text(" ", strip=True) if soup.h1 else ""174    text = soup.get_text(" ", strip=True)[:20000]175176    websites, socials = [], []177    for a in soup.find_all("a", href=True):178        href = a["href"].strip()179        if href.startswith("mailto:") or href.startswith("tel:") or href.startswith("#"):180            continue181        absu = urljoin(url, href)182        host = urlparse(absu).netloc.lower().replace("www.", "")183        if not host or source_host in host:184            continue185        if any(s in host for s in SOCIAL_HOSTS):186            socials.append(absu)187        elif not any(j in host for j in JUNK_HOSTS):188            websites.append(absu)189190    postal = POSTAL_RE.search(text)191    phone = PHONE_RE.search(text)192    regions = sorted({r for r in REGIONS if r.lower() in text.lower()})193194    return {195        "url": url,196        "title": title,197        "h1": h1,198        "websites": list(dict.fromkeys(websites))[:15],199        "socials": list(dict.fromkeys(socials))[:8],200        "postal_prefix": postal.group(1) if postal else None,201        "phone": phone.group(0) if phone else None,202        "regions_mentioned": regions,203        "text_sample": text[:1200],204    }205206207def harvest(source, urls, workers=8, delay=0.05):208    host = urlparse(urls[0]).netloc.lower().replace("www.", "") if urls else ""209    out_path = os.path.join(RAW, f"{source}.jsonl")210    done = set()211    if os.path.exists(out_path):212        with open(out_path) as f:213            for line in f:214                try:215                    done.add(json.loads(line)["url"])216                except Exception:217                    pass218    todo = [u for u in urls if u not in done]219    print(f"[{source}] {len(urls)} urls, {len(done)} cached, {len(todo)} to fetch")220    with open(out_path, "a", encoding="utf-8") as out:221        def work(u):222            html = fetch(u, delay=delay)223            if not html:224                return None225            try:226                return extract_entity(u, html, host)227            except Exception as e:228                return {"url": u, "error": str(e)[:200]}229        with cf.ThreadPoolExecutor(workers) as ex:230            n = 0231            for rec in ex.map(work, todo):232                if rec:233                    out.write(json.dumps(rec, ensure_ascii=False) + "\n")234                n += 1235                if n % 100 == 0:236                    print(f"  [{source}] {n}/{len(todo)}", flush=True)237    print(f"[{source}] done")238239240SOURCES = {241    # source: (sitemap_root, entity url regex)242    "alimentsduquebec_ent": ("https://alimentsduquebec.com/sitemaps-1-sitemap.xml",243                             r"alimentsduquebec\.com/entreprises/[a-z0-9\-]+$"),244    "lesproduitsduquebec_ent": ("https://lesproduitsduquebec.com/sitemap.xml",245                                r"lesproduitsduquebec\.com/entreprises-adherentes/[^/]+$"),246    "lesproduitsduquebec_det": ("https://lesproduitsduquebec.com/sitemap.xml",247                                r"lesproduitsduquebec\.com/detaillants/[^/]+$"),248    "metiersdart": ("https://www.metiersdart.ca/sitemap.xml",249                    r"metiersdart\.ca/repertoire_artisan\.php/.+"),250    "vinsduquebec": ("https://vinsduquebec.com/sitemap.xml",251                     r"vinsduquebec\.com/adresses/[^/]+/?$"),252    "cidreduquebec": ("https://cidreduquebec.com/wp-sitemap.xml",253                      r"cidreduquebec\.com/(cidreries|producteur-adherent)/[^/]+/?$"),254    "fromagesdici": ("https://www.fromagesdici.com/sitemap.xml",255                     r"fromagesdici\.com/fr/fromageries/[^/]+"),256    "erabledici": ("https://www.erabledici.ca/sitemap_index.xml",257                   r"erabledici\.ca/fr/erabliere/[^/]+"),258    "artisansaloeuvre": ("https://artisansaloeuvre.com/sitemap_index.xml",259                         r"artisansaloeuvre\.com/artisans/[^/]+/?$"),260    "marchespublics": ("https://www.marchespublicsduquebec.ca/sitemap.xml",261                       r"marchespublicsduquebec\.ca/marches-publics/[^/]+/?$"),262    "zoneboreale": ("https://zoneboreale.com/sitemap.xml",263                    r"zoneboreale\.com/entreprises/[^/]+/?$"),264    "createursdesaveurs": ("https://createursdesaveurs.com/sitemap.xml",265                           r"createursdesaveurs\.com/createurs/[^/]+/?$"),266    "croquezoutaouais": ("https://www.croquezoutaouais.com/sitemap_index.xml",267                         r"croquezoutaouais\.com/entreprises/[^/]+/?$"),268    "arretsgourmands": ("https://arretsgourmands.ca/sitemap.xml",269                        r"arretsgourmands\.ca/arrets-gourmands/[^/]+/?$"),270    "goutezy": ("https://goutezy.com/sitemap_index.xml",271                r"goutezy\.com/entreprise/[^/]+/?$"),272    "laurentidesjenmange": ("https://laurentidesjenmange.ca/sitemap_index.xml",273                            r"laurentidesjenmange\.ca/membre/[^/]+/?$"),274    "goutcotenord": ("https://legoutdelacotenord.ca/sitemap_index.xml",275                     r"legoutdelacotenord\.ca/artisan/[^/]+/?$"),276    "charlevoix": ("https://www.tourisme-charlevoix.com/sitemap.xml",277                   r"tourisme-charlevoix\.com/fr/entreprises/[^/]+/?$"),278    "gaspesiegourmande": ("https://gaspesiegourmande.com/sitemap.xml",279                          r"gaspesiegourmande\.com/(producteurs-transformateurs|complices)\?id=\d+"),280    "saveursbsl": ("https://saveursbsl.com/wp-sitemap.xml",281                   r"saveursbsl\.com/product/[^/]+/?$"),282    "goutezat": ("https://goutezat.com/sitemap_index.xml",283                 r"goutezat\.com/produit/[^/]+/?$"),284}285286287# sources whose entity URLs come from a pre-built list file in data/raw/288LIST_SOURCES = {289    "alimentsduquebec_ent": "data/raw/adq_enterprise_urls.txt",290    "metiersdart_fiches": "data/raw/metiersdart_fiche_urls.txt",291    "ideecadeauquebec": "data/raw/icq_urls.txt",292    "acheterquebecois": "data/raw/acheterquebecois_urls.txt",293    "distilleriesduquebec": "data/raw/distilleries_urls.txt",294    "ambq_profils": "data/raw/ambq_profile_urls.txt",295}296297298if __name__ == "__main__":299    wanted = sys.argv[1:] or list(SOURCES)300    for src in wanted:301        if src in LIST_SOURCES:302            with open(os.path.join(ROOT, LIST_SOURCES[src])) as f:303                urls = [l.strip() for l in f if l.strip().startswith("http")]304        else:305            sm, pat = SOURCES[src]306            urls = [u for u in sitemap_urls(sm) if re.search(pat, u)]307        urls = list(dict.fromkeys(urls))308        harvest(src, urls)309
Files main
Menu

Theme