SPB Git

Repository Public

enrich_stores.py 8.7 KB 239 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/enrich_stores.py11# Description      : Enrichissement des boutiques : logo, image de couverture,12#                    description.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"""Enrichissement des boutiques : logo, image de couverture, description.9192Pour chaque boutique du registre : télécharge la page d'accueil, extrait93  - logo : apple-touch-icon > icon (plus grande taille) > og:logo94  - couverture : og:image95  - description : meta description > og:description96  - nom d'affichage : og:site_name (si plus propre que le nom actuel)97Écrit dans la table stores (colonnes logo_url, cover_url, description_meta).98Cache disque data/enrich_cache/<domain>.json ; Scrapfly en secours pour les 403.99"""100import concurrent.futures as cf101import json102import os103import re104import sys105from urllib.parse import urljoin106107import requests108109ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))110sys.path.insert(0, ROOT)111CACHE = os.path.join(ROOT, "data", "enrich_cache")112os.makedirs(CACHE, exist_ok=True)113114for line in open(os.path.join(ROOT, ".env")).read().splitlines():115    if "=" in line and not line.startswith("#"):116        k, _, v = line.partition("=")117        os.environ.setdefault(k.strip(), v.strip())118119from fabrika import db as fdb  # noqa: E402120from fabrika.connectors.scrapfly import scrapfly_get, available  # noqa: E402121122HDRS = {"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",123        "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"}124125LINK_RE = re.compile(r'<link[^>]+>', re.I)126META_RE = re.compile(r'<meta[^>]+>', re.I)127128129def attr(tag, name):130    m = re.search(name + r'\s*=\s*["\']([^"\']+)["\']', tag, re.I)131    return m.group(1) if m else None132133134def extract(base_url, html):135    head = html[:120000]136    logo, cover, desc, site_name = None, None, None, None137    icons = []138    for tag in LINK_RE.findall(head):139        rel = (attr(tag, "rel") or "").lower()140        href = attr(tag, "href")141        if not href:142            continue143        if "apple-touch-icon" in rel:144            icons.append((200 if not attr(tag, "sizes") else int((attr(tag, "sizes") or "180x").split("x")[0] or 180), href))145        elif rel in ("icon", "shortcut icon"):146            sizes = attr(tag, "sizes") or "32x32"147            try:148                s = int(sizes.split("x")[0])149            except ValueError:150                s = 32151            if not href.endswith(".ico"):152                icons.append((s, href))153    if icons:154        icons.sort(reverse=True)155        logo = urljoin(base_url, icons[0][1])156    for tag in META_RE.findall(head):157        prop = (attr(tag, "property") or attr(tag, "name") or "").lower()158        content = attr(tag, "content")159        if not content:160            continue161        if prop == "og:image" and not cover:162            cover = urljoin(base_url, content)163        elif prop in ("description", "og:description") and not desc:164            desc = content.strip()[:400]165        elif prop == "og:site_name" and not site_name:166            site_name = content.strip()[:80]167        elif prop == "og:logo" and not logo:168            logo = urljoin(base_url, content)169    return {"logo_url": logo, "cover_url": cover, "description_meta": desc, "site_name": site_name}170171172def enrich_domain(store):173    dom = store["id"]174    cpath = os.path.join(CACHE, dom + ".json")175    if os.path.exists(cpath):176        return json.load(open(cpath))177    url = store.get("url") or f"https://{dom}"178    html = ""179    try:180        r = requests.get(url, headers=HDRS, timeout=20, allow_redirects=True)181        if r.status_code == 200:182            html, url = r.text, r.url183    except Exception:184        pass185    if not html and available():186        try:187            status, content = scrapfly_get(url)188            if status == 200:189                html = content190        except Exception:191            pass192    rec = {"domain": dom}193    if html:194        rec.update(extract(url, html))195        # fallback logo : favicon.ico si rien trouvé196        if not rec.get("logo_url"):197            rec["logo_url"] = urljoin(url, "/favicon.ico")198    json.dump(rec, open(cpath, "w"))199    return rec200201202def main(only_live=True):203    con = fdb.connect()204    # colonnes d'enrichissement205    for col in ("logo_url", "cover_url", "description_meta"):206        try:207            con.execute(f"ALTER TABLE stores ADD COLUMN {col} TEXT")208        except Exception:209            pass210    con.commit()211    rows = [dict(r) for r in con.execute(212        "SELECT id, url, product_count FROM stores ORDER BY product_count DESC")]213    con.close()214    if only_live:215        pass  # on enrichit tout le registre, les vivantes d'abord (tri ci-dessus)216    print(f"enrichissement de {len(rows)} boutiques…")217    done = 0218    results = []219    with cf.ThreadPoolExecutor(16) as ex:220        for rec in ex.map(enrich_domain, rows):221            results.append(rec)222            done += 1223            if done % 200 == 0:224                print(f"  {done}/{len(rows)}", flush=True)225    con = fdb.connect()226    n = 0227    for rec in results:228        if rec.get("logo_url") or rec.get("description_meta"):229            con.execute("UPDATE stores SET logo_url=?, cover_url=?, description_meta=? WHERE id=?",230                        (rec.get("logo_url"), rec.get("cover_url"),231                         rec.get("description_meta"), rec["domain"]))232            n += 1233    con.commit(); con.close()234    print(f"boutiques enrichies: {n}/{len(results)}")235236237if __name__ == "__main__":238    main()239
Files main
Menu

Theme