Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/history.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2413# Last Modified : 2026-09-0414#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# history.py : « Historique Lou-Ka » d'une annonce — timeline construite à91# partir des observations réelles des crawls :92# - price_log (depuis la v1) : chaque changement de prix observé ;93# - listing_events (db.py/_log_events) : description, superficie, dispo,94# inclusions, photos, disparition/réapparition.95# Chaque élément est étiqueté `observed` : rien n'est estimé ni inventé.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import json100import time101102from . import db103104105def timeline(uid: str, con=None) -> dict | None:106 """Historique complet d'une annonce (fiche + API).107108 Retourne : première/dernière observation, jours en ligne, prix initial et109 courant, variation, nombre de modifications et la timeline fusionnée110 (prix + événements), du plus récent au plus ancien.111 """112 own = con is None113 if own:114 con = db.connect()115 row = con.execute(116 "SELECT uid, price, first_seen, last_seen, active FROM listings"117 " WHERE uid=?", (uid,)).fetchone()118 if row is None:119 if own:120 con.close()121 return None122123 prices = con.execute(124 "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts", (uid,)).fetchall()125 events = con.execute(126 "SELECT ts, event, old, new FROM listing_events WHERE uid=? ORDER BY ts",127 (uid,)).fetchall()128129 items: list[dict] = []130 prev_price = None131 for p in prices:132 it = {"ts": p["ts"], "type": "prix", "prix": p["price"],133 "statut": "observed"}134 if prev_price is not None and p["price"] is not None:135 it["prix_avant"] = prev_price136 items.append(it)137 if p["price"] is not None:138 prev_price = p["price"]139 for e in events:140 def _load(v):141 try:142 return json.loads(v) if v is not None else None143 except (ValueError, TypeError):144 return None145 items.append({"ts": e["ts"], "type": e["event"],146 "avant": _load(e["old"]), "apres": _load(e["new"]),147 "statut": "observed"})148 items.sort(key=lambda x: x["ts"], reverse=True)149150 first_price = next((p["price"] for p in prices if p["price"] is not None), None)151 cur_price = row["price"]152 variation = None153 if first_price and cur_price and first_price > 0:154 variation = round((cur_price - first_price) / first_price, 4)155156 now = time.time()157 fin = row["last_seen"] if not row["active"] else now158 jours = max(0, round((fin - (row["first_seen"] or fin)) / 86400))159160 # modifications = éléments de timeline hors point de départ du prix161 n_modif = max(0, len([p for p in prices]) - 1) + len(162 [e for e in events if e["event"] not in ("disparition", "reapparition")])163164 out = {165 "uid": uid,166 "premiere_observation": row["first_seen"],167 "derniere_observation": row["last_seen"],168 "active": bool(row["active"]),169 "jours_en_ligne": jours,170 "prix_initial": first_price,171 "prix_actuel": cur_price,172 "variation": variation,173 "modifications": n_modif,174 "timeline": items[:60],175 "methode": ("Observations directes des synchronisations Lou-Ka "176 "(prix, description, superficie, disponibilité, inclusions, "177 "photos, retraits/retours). Aucune estimation."),178 }179 if own:180 con.close()181 return out182# ---------------------------------------------------------------------------183# padding ka2 (2026-08-31) : garantit une taille superieure a la version184# precedente du fichier : sous APFS sature une reecriture peut ne pas185# tronquer, laissant une queue residuelle apres l'EOF (SyntaxError vue186# ici le 2026-08-31). Fin sur commentaire sans saut de ligne final.187#