Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/managers.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2413# Last Modified : 2026-08-2514#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# managers.py : « Qui gère ce logement? » — fiche du gestionnaire/propriétaire.91#92# 1) Amorçage : les gestionnaires sont les sources DIRECTES de Lou-Ka93# (data/sources.json, hors portails et petites annonces) qui ont au moins94# une annonce collectée. Aucun gestionnaire n'est inventé.95# 2) Résolution Google Maps (SerpApi, serveur seulement) : la fiche Google96# n'est associée QUE si la confiance est suffisante (similarité de nom,97# domaine du site web, ville) — jamais « le premier résultat » aveuglément.98# Signaux et confiance stockés (match_confidence, match_signals).99# 3) Avis Google : synchronisation paginée (next_page_token, hl=fr, plus100# récents d'abord), dédupliqués par (manager_id, review_id Google) avec101# repli sur un hash de contenu. Les avis vivent dans NOTRE base : les pages102# ne déclenchent jamais d'appel SerpApi.103# 4) Analyse : statistiques réelles (distribution, récence, tendance — pas104# seulement la moyenne Google) + thèmes par lexique français, sentiment105# dérivé de la note, sévérité et confiance. Statut « inferred » assumé.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import difflib110import hashlib111import json112import re113import time114import unicodedata115from datetime import datetime, timezone116117from . import db, serpapi_client118from .dedup import CLASSIFIEDS, PORTALS119120VERSION = "gestionnaire-1.0"121SEUIL_CONFIANCE = 0.60 # sous ce seuil : fiche Google NON associée122MAX_PAGES = 10 # garde-fou pagination avis (par synchronisation)123SYNC_TTL = 7 * 86400 # re-synchroniser les avis au plus aux 7 jours124RESOLVE_RETRY = 30 * 86400 # re-tenter une résolution échouée après 30 jours125126# suffixes/génériques retirés pour comparer les noms d'entreprises127_LEGAL = re.compile(128 r"\b(inc|ltee|ltée|ltd|senc|s\.e\.n\.c|enr|corp|corporation|groupe|group|"129 r"gestion|gestions|immobilier|immobiliere|immobilière|immeubles?|"130 r"appartements?|apartments?|properties|proprietes|propriétés|residences?|"131 r"résidences?|habitations?|siege|social|bureau|head|office|"132 r"les|le|la|de|du|des|et|and)\b")133134# types Google d'une fiche d'ENTREPRISE (vs fiche d'un immeuble précis)135_CORP_TYPES = re.compile(136 r"agence immobili|gestion immobili|property management|real estate|"137 r"societe de gestion|immobilier", re.I)138139140def _norm_name(s: str | None) -> str:141 s = unicodedata.normalize("NFKD", (s or "").lower())142 s = "".join(c for c in s if not unicodedata.combining(c))143 s = re.sub(r"[^a-z0-9 ]+", " ", s)144 s = _LEGAL.sub(" ", s)145 return " ".join(s.split())146147148def _domain(url: str | None) -> str | None:149 if not url:150 return None151 m = re.search(r"^(?:https?://)?(?:www\.)?([^/:?#]+)", url.strip().lower())152 return m.group(1) if m else None153154155# --- 1) amorçage depuis sources.json ----------------------------------------156157def seed(con=None) -> dict:158 """Crée/actualise un gestionnaire par source directe ayant des annonces."""159 own = con is None160 if own:161 con = db.connect()162 try:163 sources = json.loads((db.DB_PATH.parent / "sources.json")164 .read_text("utf-8"))["sources"]165 with_ads = {r["source"] for r in con.execute(166 "SELECT DISTINCT source FROM listings")}167 n = 0168 for s in sources:169 sid = s.get("id")170 if not sid or sid in PORTALS or sid in CLASSIFIEDS:171 continue172 if sid not in with_ads and s.get("connector") not in with_ads:173 continue174 con.execute(175 "INSERT INTO managers (source_id, name, website, aliases)"176 " VALUES (?,?,?,?)"177 " ON CONFLICT(source_id) DO UPDATE SET name=excluded.name,"178 " website=excluded.website",179 (sid, s.get("name"), s.get("url"),180 json.dumps({"region": s.get("region"),181 "connector": s.get("connector")},182 ensure_ascii=False)))183 n += 1184 con.commit()185 return {"managers": n}186 finally:187 if own:188 con.close()189190191# --- 2) résolution Google Maps (jamais « le premier résultat ») --------------192193def _score_candidate(mgr: dict, cand: dict) -> tuple[float, dict]:194 signals: dict = {}195 sim = difflib.SequenceMatcher(196 None, _norm_name(mgr["name"]), _norm_name(cand.get("title"))).ratio()197 signals["similarite_nom"] = round(sim, 3)198 conf = 0.6 * sim199 d_mgr, d_cand = _domain(mgr.get("website")), _domain(cand.get("website"))200 if d_mgr and d_cand and d_mgr == d_cand:201 conf += 0.3202 signals["meme_domaine_web"] = d_mgr203 region = None204 try:205 region = (json.loads(mgr.get("aliases") or "{}") or {}).get("region")206 except (ValueError, TypeError):207 pass208 addr = (cand.get("address") or "").lower()209 if region and _norm_name(region) and _norm_name(region) in _norm_name(addr):210 conf += 0.1211 signals["ville_correspondante"] = region212 if _CORP_TYPES.search(cand.get("type") or ""):213 signals["fiche_entreprise"] = cand.get("type")214 signals["type_fiche"] = cand.get("type")215 signals["nombre_avis"] = cand.get("reviews")216 return min(1.0, conf), signals217218219def resolve(manager_id: int, con=None) -> dict:220 """Associe (ou refuse d'associer) la fiche Google Maps du gestionnaire."""221 own = con is None222 if own:223 con = db.connect()224 try:225 mgr = con.execute("SELECT * FROM managers WHERE id=?",226 (manager_id,)).fetchone()227 if mgr is None:228 return {"ok": False, "raison": "gestionnaire inconnu"}229 mgr = dict(mgr)230 region = ""231 try:232 region = (json.loads(mgr.get("aliases") or "{}") or {}).get(233 "region") or ""234 except (ValueError, TypeError):235 pass236 q = f"{mgr['name']} {region} Québec".strip()237 data = serpapi_client.google_maps(q)238 cands = data.get("local_results") or []239 if not cands and data.get("place_results"):240 cands = [data["place_results"]]241 for c in cands:242 # SerpApi renvoie parfois `type` en liste (multi-catégories)243 if isinstance(c.get("type"), list):244 c["type"] = ", ".join(str(t) for t in c["type"])245246 scored = [( *_score_candidate(mgr, c), c) for c in cands[:8]]247 best, best_conf, best_sig = None, 0.0, {}248 if scored:249 top = max(s[0] for s in scored)250 # une chaîne a souvent une fiche Google PAR IMMEUBLE en plus du251 # siège : parmi les candidats plausibles (confiance proche du252 # meilleur ET au-dessus du seuil), préférer la fiche d'entreprise253 # puis la plus représentative (le plus d'avis)254 near = [s for s in scored255 if s[0] >= max(SEUIL_CONFIANCE, top - 0.15)]256 if near:257 best_conf, best_sig, best = max(258 near, key=lambda s: (bool(_CORP_TYPES.search(259 s[2].get("type") or "")),260 s[2].get("reviews") or 0, s[0]))261 else:262 best_conf, best_sig, best = max(scored, key=lambda s: s[0])263 now = time.time()264 if best is None or best_conf < SEUIL_CONFIANCE:265 con.execute(266 "UPDATE managers SET resolve_failed=1, resolved_at=?,"267 " match_confidence=?, match_signals=? WHERE id=?",268 (now, round(best_conf, 3) if best else None,269 json.dumps({"refus": "confiance insuffisante",270 "candidats": len(cands), **best_sig},271 ensure_ascii=False), manager_id))272 con.commit()273 return {"ok": False, "raison": "confiance insuffisante",274 "confiance": round(best_conf, 3)}275 con.execute(276 "UPDATE managers SET gmaps_place_id=?, gmaps_data_id=?,"277 " gmaps_name=?, gmaps_address=?, gmaps_rating=?, gmaps_reviews=?,"278 " match_confidence=?, match_signals=?, resolved_at=?,"279 " resolve_failed=0, phone=COALESCE(phone, ?) WHERE id=?",280 (best.get("place_id"), best.get("data_id"), best.get("title"),281 best.get("address"), best.get("rating"), best.get("reviews"),282 round(best_conf, 3), json.dumps(best_sig, ensure_ascii=False),283 now, best.get("phone"), manager_id))284 con.commit()285 return {"ok": True, "gmaps_name": best.get("title"),286 "confiance": round(best_conf, 3)}287 finally:288 if own:289 con.close()290291292# --- 3) synchronisation des avis (paginée, dédupliquée, en base) -------------293294def _content_hash(author: str | None, rating, text: str | None) -> str:295 raw = f"{author or ''}|{rating}|{(text or '')[:200]}"296 return hashlib.sha1(raw.encode("utf-8")).hexdigest()297298299def sync_reviews(manager_id: int, con=None, max_pages: int = MAX_PAGES) -> dict:300 """Rapatrie les avis Google (les plus récents d'abord) dans NOTRE base."""301 own = con is None302 if own:303 con = db.connect()304 try:305 mgr = con.execute("SELECT * FROM managers WHERE id=?",306 (manager_id,)).fetchone()307 if mgr is None or not mgr["gmaps_data_id"]:308 return {"ok": False, "raison": "fiche Google non associée"}309 known = {r["external_review_id"] for r in con.execute(310 "SELECT external_review_id FROM manager_reviews WHERE manager_id=?",311 (manager_id,))}312 known_hash = {r["content_hash"] for r in con.execute(313 "SELECT content_hash FROM manager_reviews WHERE manager_id=?"314 " AND external_review_id IS NULL", (manager_id,))}315316 token, new, pages = None, 0, 0317 while pages < max_pages:318 data = serpapi_client.google_maps_reviews(319 mgr["gmaps_data_id"], next_page_token=token)320 reviews = data.get("reviews") or []321 pages += 1322 page_new = 0323 now = time.time()324 for rv in reviews:325 ext = rv.get("review_id")326 text = rv.get("snippet") or rv.get("extracted_snippet",327 {}).get("original")328 user = rv.get("user") or {}329 chash = _content_hash(user.get("name"), rv.get("rating"), text)330 if (ext and ext in known) or (not ext and chash in known_hash):331 continue332 resp = rv.get("response") or {}333 analysis = _analyze_review(rv.get("rating"), text)334 con.execute(335 "INSERT INTO manager_reviews (manager_id,"336 " external_review_id, source, rating, text, published_at,"337 " relative_date_raw, author_name, author_review_count,"338 " owner_response, owner_response_date, source_url,"339 " fetched_at, content_hash, analysis) VALUES"340 " (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"341 " ON CONFLICT(manager_id, external_review_id) DO NOTHING",342 (manager_id, ext, "google_maps", rv.get("rating"), text,343 rv.get("iso_date"), rv.get("date"), user.get("name"),344 user.get("reviews"), resp.get("snippet"),345 resp.get("iso_date") or resp.get("date"), rv.get("link"),346 now, chash, json.dumps(analysis, ensure_ascii=False)))347 if ext:348 known.add(ext)349 else:350 known_hash.add(chash)351 page_new += 1352 new += page_new353 token = (data.get("serpapi_pagination") or {}).get(354 "next_page_token")355 # tri « plus récents d'abord » : une page entièrement connue356 # signifie qu'on a rejoint l'historique déjà synchronisé357 if not token or (reviews and page_new == 0):358 break359 stats = _aggregate(con, manager_id)360 con.execute("UPDATE managers SET review_stats=?, last_synced_at=?"361 " WHERE id=?",362 (json.dumps(stats, ensure_ascii=False), time.time(),363 manager_id))364 con.commit()365 return {"ok": True, "nouveaux": new, "pages": pages,366 "total": stats.get("n")}367 finally:368 if own:369 con.close()370371372# --- 4) analyse : thèmes (lexique fr), sentiment, sévérité, agrégats ---------373374TOPICS = {375 "entretien": ["entretien", "entreten", "maintenance", "neglige", "négligé",376 "delabre", "délabré", "moisissure"],377 "réparations": ["reparation", "réparation", "reparer", "réparer", "bris",378 "brise", "brisé", "fuite", "degat", "dégât", "plomberie"],379 "communication": ["communication", "repond", "répond", "reponse",380 "réponse", "rappel", "courriel", "joindre",381 "injoignable", "appel", "message"],382 "personnel": ["personnel", "employe", "employé", "concierge", "equipe",383 "équipe", "gerant", "gérant", "agent", "proprietaire",384 "propriétaire"],385 "propreté": ["propre", "proprete", "propreté", "sale", "salete", "saleté",386 "malpropre"],387 "chauffage": ["chauffage", "chauffe", "chauffé", "froid", "temperature",388 "température"],389 "eau chaude": ["eau chaude"],390 "vermine": ["punaise", "coquerelle", "souris", "rat ", "rats", "insecte",391 "vermine", "fourmi", "extermina"],392 "bruit": ["bruit", "bruyant", "tapage", "insonoris"],393 "sécurité": ["securite", "sécurité", "securitaire", "sécuritaire", "vol",394 "intrusion", "serrure", "camera", "caméra"],395 "ascenseur": ["ascenseur"],396 "stationnement": ["stationnement", "parking", "deneigement",397 "déneigement"],398 "dépôt et remboursement": ["depot", "dépôt", "rembours", "caution"],399 "augmentation de loyer": ["augmentation", "hausse"],400 "bail et location": ["bail", "signature", "visite", "location"],401 "service client": ["service", "clientele", "clientèle", "professionnel",402 "courtois", "arrogant", "impoli", "respect"],403}404_GRAVES = {"vermine", "sécurité", "chauffage", "eau chaude"}405406407def _analyze_review(rating, text: str | None) -> dict:408 t = (text or "").lower()409 topics = sorted({name for name, kws in TOPICS.items()410 if any(k in t for k in kws)})411 if rating is None:412 sentiment = "inconnu"413 elif rating <= 2:414 sentiment = "négatif"415 elif rating >= 4:416 sentiment = "positif"417 else:418 sentiment = "neutre"419 severity = "faible"420 if sentiment == "négatif":421 severity = "élevée" if any(x in _GRAVES for x in topics) else "moyenne"422 if len(t) >= 80 and topics:423 confidence = 0.7424 elif t:425 confidence = 0.4426 else:427 confidence = 0.2428 return {"topics": topics, "sentiment": sentiment, "severite": severity,429 "confiance": confidence, "statut": "inferred",430 "methode": "lexique de thèmes fr + sentiment dérivé de la note"}431432433def _aggregate(con, manager_id: int) -> dict:434 rows = con.execute(435 "SELECT rating, published_at, owner_response, analysis"436 " FROM manager_reviews WHERE manager_id=?", (manager_id,)).fetchall()437 rated = [r for r in rows if r["rating"] is not None]438 out: dict = {"n": len(rows), "version": VERSION, "statut": "calculated",439 "methode": ("statistiques calculées sur les avis Google "440 "synchronisés en base (pas seulement la moyenne "441 "affichée par Google) — l'échantillon peut être "442 "plus petit que le total annoncé par Google, il "443 "s'accumule à chaque synchronisation ; thèmes "444 "par lexique — inférence, pas une lecture "445 "humaine")}446 if not rated:447 return out448 out["moyenne"] = round(sum(r["rating"] for r in rated) / len(rated), 2)449 dist = {str(i): 0 for i in range(1, 6)}450 for r in rated:451 k = str(int(round(r["rating"])))452 if k in dist:453 dist[k] += 1454 out["distribution"] = dist455 out["pct_negatif"] = round(100 * (dist["1"] + dist["2"]) / len(rated))456 out["pct_positif"] = round(100 * (dist["4"] + dist["5"]) / len(rated))457 out["avec_reponse_proprietaire"] = sum(458 1 for r in rows if r["owner_response"])459460 cutoff = datetime.now(timezone.utc).timestamp() - 365 * 86400461 rec, old = [], []462 for r in rated:463 ts = _iso_ts(r["published_at"])464 (rec if ts and ts >= cutoff else old).append(r["rating"])465 if rec:466 out["moyenne_12m"] = round(sum(rec) / len(rec), 2)467 out["n_12m"] = len(rec)468 if len(rec) >= 5 and len(old) >= 5:469 delta = out["moyenne_12m"] - sum(old) / len(old)470 out["tendance"] = ("en amélioration" if delta >= 0.3 else471 "en dégradation" if delta <= -0.3 else "stable")472 out["tendance_delta"] = round(delta, 2)473474 themes: dict[str, dict] = {}475 for r in rows:476 try:477 a = json.loads(r["analysis"] or "{}")478 except (ValueError, TypeError):479 continue480 for tp in a.get("topics") or []:481 d = themes.setdefault(tp, {"mentions": 0, "negatif": 0,482 "positif": 0})483 d["mentions"] += 1484 if a.get("sentiment") == "négatif":485 d["negatif"] += 1486 elif a.get("sentiment") == "positif":487 d["positif"] += 1488 out["themes"] = dict(sorted(themes.items(),489 key=lambda kv: -kv[1]["mentions"]))490 out["plaintes_frequentes"] = [491 k for k, v in sorted(themes.items(), key=lambda kv: -kv[1]["negatif"])492 if v["negatif"] >= 2][:5]493 return out494495496def _iso_ts(iso: str | None) -> float | None:497 if not iso:498 return None499 try:500 return datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()501 except ValueError:502 return None503504505# --- fiche API + boucle de fond ----------------------------------------------506507def fiche(source_id: str, con=None) -> dict | None:508 """Fiche gestionnaire pour l'API — tout vient de NOTRE base (0 SerpApi)."""509 own = con is None510 if own:511 con = db.connect()512 try:513 mgr = con.execute("SELECT * FROM managers WHERE source_id=?",514 (source_id,)).fetchone()515 if mgr is None:516 return None517 m = dict(mgr)518 n_active = con.execute(519 "SELECT COUNT(*) n FROM listings WHERE source=? AND active=1"520 " AND published=1 AND dup_of IS NULL", (source_id,)).fetchone()["n"]521 out = {522 "source_id": m["source_id"], "nom": m["name"],523 "site_web": m["website"], "telephone": m["phone"],524 "annonces_actives": n_active, "version": VERSION,525 }526 if m["gmaps_place_id"] and not m["resolve_failed"]:527 out["google_maps"] = {528 "nom": m["gmaps_name"], "adresse": m["gmaps_address"],529 "note": m["gmaps_rating"], "nombre_avis": m["gmaps_reviews"],530 "place_id": m["gmaps_place_id"],531 "confiance_association": m["match_confidence"],532 "signaux": json.loads(m["match_signals"] or "{}"),533 "statut": "inferred",534 "methode": ("fiche associée par similarité de nom, domaine "535 "web et ville — association refusée sous "536 f"{SEUIL_CONFIANCE:.2f} de confiance"),537 }538 try:539 out["avis"] = json.loads(m["review_stats"] or "null")540 except (ValueError, TypeError):541 out["avis"] = None542 out["avis_recents"] = [543 {"note": r["rating"], "texte": r["text"],544 "date": r["published_at"] or r["relative_date_raw"],545 "auteur": r["author_name"],546 "reponse_proprietaire": bool(r["owner_response"]),547 "analyse": json.loads(r["analysis"] or "{}"),548 "statut": "observed"}549 for r in con.execute(550 "SELECT rating, text, published_at, relative_date_raw,"551 " author_name, owner_response, analysis"552 " FROM manager_reviews WHERE manager_id=?"553 " ORDER BY published_at DESC, fetched_at DESC LIMIT 10",554 (m["id"],))]555 out["derniere_synchro"] = m["last_synced_at"]556 elif m["resolved_at"]:557 out["google_maps"] = {558 "statut": "non_associe",559 "note_methode": ("aucune fiche Google Maps n'a pu être "560 "associée avec une confiance suffisante — "561 "Lou-Ka préfère ne rien afficher plutôt que "562 "d'attribuer les avis d'une autre entreprise"),563 }564 return out565 finally:566 if own:567 con.close()568569570def precompute(budget_s: float = 120.0, con=None) -> dict:571 """Boucle de fond : amorce, résout et synchronise dans un budget temps."""572 if not serpapi_client.available():573 return {"skipped": "SERPAPI_API_KEY absente"}574 own = con is None575 if own:576 con = db.connect()577 t0 = time.time()578 resolved = synced = errors = 0579 try:580 seed(con)581 now = time.time()582 # 1) résolutions manquantes (ou échecs anciens à retenter)583 for r in con.execute(584 "SELECT id FROM managers WHERE resolved_at IS NULL"585 " OR (resolve_failed=1 AND resolved_at < ?)"586 " ORDER BY resolved_at IS NOT NULL, id",587 (now - RESOLVE_RETRY,)).fetchall():588 if time.time() - t0 > budget_s:589 break590 try:591 if resolve(r["id"], con).get("ok"):592 resolved += 1593 except serpapi_client.SerpApiError:594 errors += 1595 break # panne API : ne pas insister ce tour-ci596 # 2) avis périmés (les jamais-synchronisés d'abord)597 for r in con.execute(598 "SELECT id FROM managers WHERE gmaps_data_id IS NOT NULL"599 " AND resolve_failed=0 AND (last_synced_at IS NULL"600 " OR last_synced_at < ?)"601 " ORDER BY last_synced_at IS NOT NULL, last_synced_at",602 (now - SYNC_TTL,)).fetchall():603 if time.time() - t0 > budget_s:604 break605 try:606 if sync_reviews(r["id"], con).get("ok"):607 synced += 1608 except serpapi_client.SerpApiError:609 errors += 1610 break611 return {"resolved": resolved, "synced": synced, "errors": errors,612 "elapsed_s": round(time.time() - t0, 1)}613 finally:614 if own:615 con.close()616617618if __name__ == "__main__":619 print(precompute())620