SPB Git

Repository Public

tt.py 8.4 KB 218 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/tt.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1214#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Food-Ka — connecteur T&T Supermarket (tntsupermarket.com — supermarché89# asiatique, magasin de Montréal / Saint-Laurent)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# Adobe Commerce (Magento PWA) headless derrière Akamai : requêtes directes92# refusées (403), mais l'API GraphQL /graphql répond via Scrapfly ASP en GET93# — SANS rendu JavaScript (1 requête légère par catégorie). Prix courant et94# prix régulier dans price_range.minimum_price, stock, image et url_key.95# Catégories via categoryList (uid base64) ; magasin « default » (EN).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import json100import re101import urllib.parse102103from ..schema import Product104from .base import BaseConnector105106BASE = "https://www.tntsupermarket.com"107GRAPHQL = f"{BASE}/graphql"108109# format en fin de nom : « Rice Cracker (180g) » -> « 180 g »110_SIZE_IN_NAME_RE = re.compile(111    r"\(([^()]*?(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l|lb|lbs|oz)\b[^()]*)\)",112    re.IGNORECASE)113114# catégories T&T : (uid GraphQL, taxonomie source, catégorie canonique)115COLLECTIONS = [116    ("NTAzNQ==", "Fruits & Vegetables", "Fruits et légumes"),117    ("NTA1MQ==", "Meat & Seafood / Beef", "Viandes et volailles"),118    ("NTA1Mw==", "Meat & Seafood / Fish, Shrimps, Lobsters & Crabs",119     "Poissons et fruits de mer"),120    ("NDk5MQ==", "Dairy & Frozen / Dairy & Plant-Based Milk",121     "Produits laitiers et œufs"),122    ("NDk4Nw==", "Pantry & Sauce", "Garde-manger"),123    ("NDk4OA==", "Snacks & Drinks", "Collations et confiseries"),124    ("NTE3Ng==", "T&T Bakery", "Boulangerie"),125    ("NDk5NQ==", "Dairy & Frozen / Frozen Meals", "Surgelés"),126]127128_QUERY = """query {129  products(filter: {category_uid: {eq: "%s"}} pageSize: %d currentPage: 1) {130    total_count131    items {132      sku133      name134      url_key135      stock_status136      price_range {137        minimum_price {138          final_price { value }139          regular_price { value }140        }141      }142      small_image { url }143    }144  }145}"""146147148class TntConnector(BaseConnector):149    source_id = "tt"150    request_delay = 1.0151152    page_size: int = 50       # produits par catégorie — 1 requête GraphQL chacune153154    # -- une catégorie = une requête GraphQL (GET, ASP sans rendu JS) -----------155    def _fetch_collection(self, uid: str) -> list[dict]:156        query = _QUERY % (uid, self.page_size)157        url = f"{GRAPHQL}?query={urllib.parse.quote(query)}"158        body = self.get_scrapfly(159            url, render_js=False, asp=True,160            headers={"Content-Type": "application/json"},161            must_contain='"items"')162        data = json.loads(body)163        return ((data.get("data") or {}).get("products") or {}).get("items") or []164165    def _parse_item(self, item: dict, category_raw: str,166                    category: str) -> Product | None:167        name = (item.get("name") or "").strip()168        sku = str(item.get("sku") or "").strip()169        if not name or not sku:170            return None171        minimum = ((item.get("price_range") or {}).get("minimum_price")) or {}172        price = (minimum.get("final_price") or {}).get("value")173        regular = (minimum.get("regular_price") or {}).get("value")174        if not price or price <= 0:175            return None            # pas de prix affiché = produit inutilisable176177        size_label = ""178        m = _SIZE_IN_NAME_RE.search(name)179        if m:180            size_label = f"{m.group(2)} {m.group(3).lower()}"181182        url_key = item.get("url_key") or ""183        image = ((item.get("small_image") or {}).get("url")) or ""184        stock = item.get("stock_status")185186        return Product(187            source=self.source_id,188            external_id=sku,189            url=f"{BASE}/eng/{url_key}.html" if url_key else BASE,190            name=name,191            category=category,192            category_raw=category_raw,193            size_label=size_label,194            price=float(price),195            regular_price=(float(regular)196                           if regular and regular > price else None),197            on_sale=bool(regular and regular > price),198            in_stock=(True if stock == "IN_STOCK"199                      else False if stock == "OUT_OF_STOCK" else None),200            images=[image] if image.startswith("http") else [],201        )202203    # -- contrat ---------------------------------------------------------------204    def fetch(self) -> list[Product]:205        products: list[Product] = []206        seen: set[str] = set()207        for uid, category_raw, category in COLLECTIONS:208            try:209                items = self._fetch_collection(uid)210            except Exception:   # une catégorie qui casse ne bloque pas le reste211                continue212            for item in items:213                prod = self._parse_item(item, category_raw, category)214                if prod is not None and prod.uid not in seen:215                    seen.add(prod.uid)216                    products.append(prod)217        return products218
Files main
Menu

Theme