SPB Git

Repository Public

serpapi_client.py 6.5 KB 173 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/serpapi_client.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# serpapi_client.py : client SerpApi minimal, STRICTEMENT côté serveur.91#92# Sécurité de la clé (non négociable) :93#   - lue UNIQUEMENT depuis la variable d'environnement SERPAPI_API_KEY94#     (chargée par run.py depuis .env, jamais commitée — voir .env.example) ;95#   - jamais écrite dans les logs, les exceptions ni les réponses API ;96#   - aucune requête SerpApi ne part du navigateur : ce module n'est importé97#     que par les jobs serveur (managers.py).98#99# Robustesse : timeout 30 s, 3 tentatives avec repli exponentiel sur les100# erreurs transitoires (réseau, 429, 5xx). Les erreurs définitives (4xx)101# remontent immédiatement.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import os106import time107108import requests109110BASE = "https://serpapi.com/search.json"111TIMEOUT = 30112RETRIES = 3113BACKOFF = 2.0  # s — doublé à chaque tentative114115116class SerpApiError(RuntimeError):117    pass118119120def api_key() -> str | None:121    return os.environ.get("SERPAPI_API_KEY") or None122123124def available() -> bool:125    return api_key() is not None126127128def search(params: dict) -> dict:129    """GET serpapi.com/search.json — params SANS la clé (ajoutée ici)."""130    key = api_key()131    if not key:132        raise SerpApiError("SERPAPI_API_KEY absente de l'environnement")133    q = dict(params)134    q["api_key"] = key135    last = "erreur inconnue"136    for attempt in range(RETRIES):137        if attempt:138            time.sleep(BACKOFF * (2 ** (attempt - 1)))139        try:140            r = requests.get(BASE, params=q, timeout=TIMEOUT)141        except requests.RequestException as e:142            # ne jamais inclure l'URL complète (elle contient la clé)143            last = f"erreur réseau: {type(e).__name__}"144            continue145        if r.status_code == 429 or r.status_code >= 500:146            last = f"HTTP {r.status_code}"147            continue148        if r.status_code != 200:149            raise SerpApiError(f"SerpApi HTTP {r.status_code}")150        data = r.json()151        if data.get("error"):152            # « fully empty » = zéro résultat, pas une panne153            if "hasn't returned any results" in str(data["error"]):154                return data155            raise SerpApiError(f"SerpApi: {data['error']}")156        return data157    raise SerpApiError(f"SerpApi injoignable après {RETRIES} tentatives ({last})")158159160def google_maps(query: str) -> dict:161    return search({"engine": "google_maps", "q": query, "hl": "fr",162                   "gl": "ca", "google_domain": "google.ca", "type": "search"})163164165def google_maps_reviews(data_id: str, next_page_token: str | None = None) -> dict:166    p = {"engine": "google_maps_reviews", "data_id": data_id,167         "hl": "fr", "sort_by": "newestFirst"}168    if next_page_token:169        # num n'est accepté par SerpApi qu'avec un next_page_token170        p["next_page_token"] = next_page_token171        p["num"] = 20172    return search(p)173
Files main
Menu

Theme