SPB Git

Repository Public

thrace.py 26.3 KB 626 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/thrace.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-10-2214#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# connectors/thrace.py : connecteur Gestions Thrace (gestionsthrace.com)91#   Plus gros gestionnaire de la Mauricie (~2 500 logements — Trois-Rivières,92#   Cap-de-la-Madeleine, Bécancour). Site WordPress (Bricks) ; la page93#   /fr/residential embarque le module « inventory » Livya (app.livya.com,94#   client « thrace », sélecteur résidentiel).95#   Depuis la refonte Livya du 2026-10-22, le flux RSC des pages « plans » des96#   projets ne contient plus les unités (ancienne source de ce connecteur).97#   La page INVENTAIRE /fr/thrace/inventory/<sel> reste rendue serveur mais98#   son flux RSC est TRONQUÉ (464 unités rendues sur 564 annoncées par99#   totalUnitsBySegments au relevé 2026-10-22) : il ne peut servir seul de100#   source de vérité. On rend donc la page inventaire en navigateur (Scrapfly101#   render_js, scroll des conteneurs internes — patron quartier_sila/somex) :102#   le compteur « N résultats » et les data-unit-id du DOM définissent103#   l'ENSEMBLE des unités affichées (relevé : 109 = résidentielles AVAILABLE104#   ou NOT_AVAILABLE avec date de libération future), puis chaque unité est105#   enrichie par son objet JSON du flux RSC de la même page (statut, loyer,106#   pièces, inclusions, adresse civique, GPS, photos) — recoupé 109/109 au107#   2026-10-22. Si une unité affichée sortait du SSR tronqué, repli sur les108#   données du DOM (carte : nom, prix, adresse, photos ; tableau : étage,109#   chambres, sdb, pi² ; GPS via l'objet immeuble du RSC). Unités locatives110#   et résidentielles seulement (rental, segment — les unités en vente sont111#   affichées par le module mais exclues). external_id = UUID unitId Livya,112#   identique à l'historique — zéro churn à travers la migration.113# -----------------------------------------------------------------------------114from __future__ import annotations115116import html as _html117import json118import re119import time120from urllib.parse import unquote121122from ..schema import Listing123from .base import BaseConnector124125BASE = "https://www.gestionsthrace.com"126LIST_URL = f"{BASE}/fr/residential"127LIVYA = "https://app.livya.com"128129# Valeurs observées au 2026-10-22 — replis si la découverte dynamique casse130DEFAULT_CLIENT = "thrace"131DEFAULT_ENTITY = "fb25970c-6c5f-4253-a396-7669992522b0"     # sélecteur Résidentiel132133# fragments RSC de Next.js : self.__next_f.push([1,"…"])134_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')135136# DOM rendu : cartes de la grille + lignes de la vue tableau + compteur137_CARD_RE = re.compile(r'<div[^>]*data-unit-id="([0-9a-f-]{36})"')138_ROW_RE = re.compile(r'<tr data-unit-id="([0-9a-f-]{36})"')139_TH_RE = re.compile(r'<th[^>]*>(.*?)</th>', re.S)140_TD_RE = re.compile(r'<td[^>]*>(.*?)</td>', re.S)141_ID_RE = re.compile(r'data-unit-id="([0-9a-f-]{36})"')142_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')143_COUNT_RE = re.compile(r'(\d+)\s*résultats?')144# adresse civique des cartes : « 675 Rue Bonaventure, Trois-Rivières, QC G9A 2B9, Canada »145_ADDR_RE = re.compile(146    r'(\d[^,<>]{2,60}),\s*([^,<>]{2,40}),\s*QC\s*([A-Z]\d[A-Z]\s?\d[A-Z]\d)', re.I)147_PRICE_RE = re.compile(r'(\d[\d\s  ]*)\s*\$')148149_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,150         "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,151         "novembre": 11, "décembre": 12}152_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)153154# scrolle tous les conteneurs à overflow interne (grille et tableau155# lazy-loadés : le scroll de la fenêtre ne charge rien — auto_scroll Scrapfly156# inopérant). 16 itérations : 8 ne chargeaient que 100/109 unités.157_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"158              "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")159160161def _flight_blob(html: str) -> str:162    """Concatène et décode les fragments RSC d'une page Livya (JSON en clair)."""163    return "".join(json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))164165166def _cell_text(cell: str) -> str:167    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", cell))).strip()168169170def _cell_num(s: str) -> float | None:171    digits = re.sub(r"[^\d.]", "", s or "")172    try:173        return float(digits) if digits else None174    except ValueError:175        return None176177178def _unit_type(rooms) -> str:179    """3.5 -> « 3½ » ; < 1 -> « Studio » (finalize gère 6½+)."""180    try:181        r = float(rooms or 0)182    except (TypeError, ValueError):183        return ""184    if not r:185        return ""186    if r < 1:187        return "Studio"188    return f"{int(r)}½"189190191def _date_fr(text: str) -> str | None:192    """« 1 avril 2027 » -> « 2027-04-01 » (None si pas de date française)."""193    m = _DATE_FR_RE.search(text or "")194    if not m:195        return None196    mois = _MOIS.get(m.group(2).lower())197    if not mois:198        return None199    return f"{int(m.group(3)):04d}-{mois:02d}-{int(m.group(1)):02d}"200201202class ThraceConnector(BaseConnector):203    source_id = "thrace"204    request_delay = 0.8205    max_units = 1500            # garde-fou (~560 unités résidentielles publiées)206207    # -- découverte des paramètres Livya ----------------------------------------208    def _module_params(self) -> tuple[str, str]:209        """(client, sélecteur résidentiel) lus sur /fr/residential, replis210        constants."""211        client, entity = DEFAULT_CLIENT, DEFAULT_ENTITY212        try:213            page = self.get(LIST_URL).text214            mc = re.search(r'<script[^>]*data-client="([^"]+)"', page)215            if mc:216                client = mc.group(1).strip() or client217            md = re.search(218                r'<[^>]*livya-module-container-inventory[^>]*'219                r'data-entity="([0-9a-f-]+)"', page)220            if md:221                entity = md.group(1)222        except Exception:223            pass    # replis : les constantes observées224        return client, entity225226    # -- rendu navigateur ---------------------------------------------------------227    def get_rendered(self, url: str, wait_ms: int = 0) -> str:228        """HTML rendu Scrapfly, scroll des conteneurs internes (grille et229        tableau lazy-loadés). Surchargée (même nom que base) pour rester230        compatible avec le record/replay des fixtures — clé de rejeu = URL."""231        steps: list[dict] = []232        for _ in range(16):233            steps.append({"execute": {"script": _SCROLL_JS}})234            steps.append({"wait": 1100})235        html = self.get_scrapfly(url, render_js=True, asp=True,236                                 rendering_wait=wait_ms or 4000,237                                 js_scenario=steps)238        if not html:239            raise RuntimeError(f"Scrapfly : rendu vide — {url}")240        return html241242    def _render_ok(self, url: str) -> str:243        """Rendu complet : le compteur « N résultats » doit être présent244        (sinon gabarit changé) et les data-unit-id uniques du DOM doivent245        l'atteindre — erreur franche après 3 tentatives plutôt qu'un rendu246        tronqué qui dépublierait des unités."""247        last_err: Exception | None = None248        for attempt in range(3):249            html = self.get_rendered(url, wait_ms=4000)250            m = _COUNT_RE.search(251                _html.unescape(re.sub(r"<[^>]+>", " ", html)))252            if not m:253                last_err = RuntimeError(254                    "app.livya.com (thrace) : compteur « N résultats » "255                    f"absent du rendu — gabarit Livya changé ? ({url})")256            else:257                announced = int(m.group(1))258                uniques = len(set(_ID_RE.findall(html)))259                if uniques >= announced:260                    return html          # announced == 0 : vrai zéro accepté261                last_err = RuntimeError(262                    f"app.livya.com (thrace) : {uniques} unité(s) unique(s) "263                    f"dans le DOM pour {announced} annoncées — rendu "264                    f"incomplet ? ({url})")265            if attempt < 2:266                time.sleep(5 * (attempt + 1))267        assert last_err is not None268        raise last_err269270    # -- extraction du flux RSC ---------------------------------------------------271    @staticmethod272    def _units(blob: str) -> dict[str, dict]:273        """Objets unité complets ({"unitId": …}) du flux, dédoublonnés."""274        dec = json.JSONDecoder()275        units: dict[str, dict] = {}276        for m in re.finditer(r'\{"unitId"', blob):277            try:278                obj, _ = dec.raw_decode(blob[m.start():m.start() + 60000])279            except Exception:280                continue281            uid = obj.get("unitId")282            if uid and uid not in units and obj.get("number"):283                units[uid] = obj284        return units285286    @staticmethod287    def _buildings(blob: str) -> dict[str, dict]:288        """Objets immeuble complets ({"buildingId": …} : nom, slug, adresse,289        GPS) du flux — toujours rendus serveur, servent d'enrichissement."""290        dec = json.JSONDecoder()291        buildings: dict[str, dict] = {}292        for m in re.finditer(r'\{"buildingId"', blob):293            try:294                obj, _ = dec.raw_decode(blob[m.start():m.start() + 20000])295            except Exception:296                continue297            bid = obj.get("buildingId")298            if bid and bid not in buildings and obj.get("name"):299                buildings[bid] = obj300        return buildings301302    # -- cartes et tableau du DOM rendu -------------------------------------------303    @staticmethod304    def _dom_units(html: str) -> dict[str, dict]:305        """Données DOM par unité affichée : cartes (texte, photos) et lignes306        de la vue tableau (cellules mappées par en-têtes)."""307        dom: dict[str, dict] = {}308309        cards = list(_CARD_RE.finditer(html))310        for i, m in enumerate(cards):311            end = cards[i + 1].start() if i + 1 < len(cards) else m.start() + 8000312            seg = html[m.start():min(end, m.start() + 8000)]313            d = dom.setdefault(m.group(1), {})314            text = _cell_text(seg)315            if text and not d.get("card_text"):316                d["card_text"] = text317            imgs = [unquote(u) for u in _IMG_RE.findall(seg)]318            if imgs and not d.get("images"):319                d["images"] = list(dict.fromkeys(imgs))320321        thead = re.search(r"<thead.*?</thead>", html, re.S)322        cols: dict[str, int] = {}323        if thead:324            for i, th in enumerate(_TH_RE.findall(thead.group(0))):325                t = _cell_text(th).lower()326                for key, label in (("name", "nom"), ("floor", "étage"),327                                   ("beds", "chambre"), ("baths", "salle"),328                                   ("area", "superficie"), ("price", "prix"),329                                   ("status", "statut")):330                    if t.startswith(label):331                        cols[key] = i332        rows = list(_ROW_RE.finditer(html))333        for i, m in enumerate(rows):334            end = rows[i + 1].start() if i + 1 < len(rows) else m.start() + 8000335            cells = [_cell_text(c) for c in336                     _TD_RE.findall(html[m.start():min(end, m.start() + 8000)])]337            row = {k: (cells[j] if j < len(cells) else "")338                   for k, j in cols.items()}339            if row:340                dom.setdefault(m.group(1), {})["row"] = row341        return dom342343    def fetch(self) -> list[Listing]:344        client, entity = self._module_params()345        inv_url = f"{LIVYA}/fr/{client}/inventory/{entity}"346347        # 1) flux RSC direct : JSON riche (tronqué côté Livya, mais couvre348        #    toutes les unités affichées au relevé 2026-10-22)349        blob = _flight_blob(self.get(inv_url).text)350        units = self._units(blob)351        buildings = self._buildings(blob)352353        # 2) rendu navigateur : l'ensemble des unités AFFICHÉES (compteur354        #    « N résultats » + data-unit-id) est la source de vérité355        html = self._render_ok(inv_url)356        dom = self._dom_units(html)357        shown = list(dict.fromkeys(_ID_RE.findall(html)))358359        listings: list[Listing] = []360        for uid in shown[: self.max_units]:361            u = units.get(uid)362            if u is not None:363                # unités en vente et locaux commerciaux affichés par le module364                if not u.get("rental", True):365                    continue366                if (u.get("segment") or "").upper() != "RESIDENTIAL":367                    continue368                if (u.get("stateCode") or "QC").upper() != "QC":369                    continue370                listings.append(self._listing(u, buildings, dom.get(uid)))371            else:372                # unité affichée mais sortie du SSR tronqué : repli DOM373                lst = self._listing_dom(uid, dom.get(uid) or {}, buildings)374                if lst is not None:375                    listings.append(lst)376        return listings377378    # -- annonce depuis l'objet JSON du flux RSC ----------------------------------379    def _listing(self, u: dict, buildings: dict[str, dict],380                 d: dict | None) -> Listing:381        num = str(u.get("number") or "").strip()382        b = buildings.get(u.get("buildingId") or "", {})383        bname = str(b.get("name") or "").strip()384        bslug = str(b.get("slug") or "").strip()385386        # le portail WordPress accepte ?building=<slug> (module inventory)387        url = f"{LIST_URL}?building={bslug}" if bslug else LIST_URL388        title = (f"Gestions Thrace ({bname}) — unité {num}" if bname389                 else f"Gestions Thrace — unité {num}")390391        address = ", ".join(x for x in (392            (u.get("address") or "").strip(), (u.get("city") or "").strip(),393            (u.get("postalCode") or "").strip()) if x)394395        price = u.get("rentalPrice")396        price = float(price) if isinstance(price, (int, float)) and price > 0 else None397398        # disponibilité : date de libération future publiée, sinon « Disponible »399        availability = "Disponible"400        avail_date = None401        fut = u.get("futureAvailability") or {}402        starts = str(fut.get("startsOn") or "")[:10]403        if re.fullmatch(r"20\d{2}-\d{2}-\d{2}", starts):404            avail_date = starts405            availability = f"Disponible à partir du {starts}"406407        # superficie structurée (measurementSystem IMPERIAL -> déjà en pi²)408        area = None409        if (u.get("measurementSystem") or "IMPERIAL").upper() == "IMPERIAL":410            size = u.get("unitSize")411            if isinstance(size, (int, float)) and size > 0:412                area = float(size)413414        # inclusions et caractéristiques publiées par unité (« Eau chaude »,415        # « Animaux interdits », « Stationnement: 1 extérieur »…)416        amenities = [a["name"] for a in (u.get("attributes") or [])417                     if isinstance(a, dict) and a.get("name")]418419        # description : étage, modèle, pièces, balcon, précision de prix, plan420        desc: list[str] = []421        floor_disp = str(u.get("floorDisplayName") or "").strip()422        if floor_disp:423            desc.append(floor_disp)424        if u.get("typeName"):425            desc.append(f"Modèle {u['typeName']}")426        if u.get("roomsBed"):427            desc.append(f"{u['roomsBed']} chambre(s)")428        if u.get("roomsBath"):429            desc.append(f"{u['roomsBath']} salle(s) de bain")430        if u.get("balconySize"):431            desc.append(f"Balcon de {u['balconySize']} pi²")432        precision = str(u.get("pricePrecision") or "").strip()433        if precision:434            desc.append(precision)435        libre = str(u.get("description") or "").strip()436        if libre:437            desc.append(libre)438        if u.get("floorPlanUrl"):439            desc.append(f"Plan : {u['floorPlanUrl']}")440441        details: dict = {}442        if bname:443            details["building"] = bname444        floor_no = str(u.get("floorNumber") or "")445        if floor_no.isdigit():446            details["floor"] = int(floor_no)447        if u.get("roomsBed"):448            details["bedrooms"] = int(u["roomsBed"])449        if u.get("roomsBath"):450            details["bathrooms"] = int(u["roomsBath"])451452        images = [img.get("fullUrl") for img in (u.get("typeImages") or [])453                  if isinstance(img, dict) and img.get("fullUrl")]454        if u.get("floorPlanImageUrl"):455            images.append(u["floorPlanImageUrl"])456        if not images and d and d.get("images"):457            images = list(d["images"])      # photos de la carte du DOM458459        try:460            lat = float(u["latitude"]) if u.get("latitude") else None461            lng = float(u["longitude"]) if u.get("longitude") else None462        except (TypeError, ValueError):463            lat = lng = None464465        beds = u.get("roomsBed")466        baths = u.get("roomsBath")467468        return Listing(469            source=self.source_id,470            external_id=str(u["unitId"]),          # UUID Livya : stable471            url=url,472            title=title,473            address=address,474            sector="",                             # non exposé par le flux475            city=(u.get("city") or "").strip() or "Trois-Rivières",476            unit_type=_unit_type(u.get("rooms")),477            bedrooms=(float(beds)478                      if isinstance(beds, (int, float)) and beds else None),479            bathrooms=(float(baths)480                       if isinstance(baths, (int, float)) and baths else None),481            price=price,482            price_label=f"{price:.0f} $ /mois" if price else "",483            availability=availability,484            availability_date=avail_date,485            area_sqft=area,486            description=" | ".join(desc),487            amenities=amenities,488            details=details,489            images=images[:12],490            lat=lat,491            lng=lng,492        )493494    # -- annonce de repli depuis le DOM rendu -------------------------------------495    def _listing_dom(self, uid: str, d: dict,496                     buildings: dict[str, dict]) -> Listing | None:497        """Unité affichée par le module mais absente du flux RSC tronqué :498        carte (nom, prix, adresse, photos) + ligne du tableau (étage,499        chambres, sdb, pi²) + objet immeuble du RSC (GPS)."""500        row = d.get("row") or {}501        card = str(d.get("card_text") or "")502        name = str(row.get("name") or "").strip()503        if not name:504            m = re.search(r"([\w| /-]{2,60})\s+Disponible", card)505            name = m.group(1).strip() if m else ""506        if not name and not card:507            return None                  # aucune donnée exploitable508509        # « 201 - 675 BONAVENTURE » / « 17 | 75 BOULEVARD SAINTE-MADELEINE »510        num, bpart = name, ""511        m = re.match(r"^\s*([\w.-]+)\s*[-|]\s*(.+)$", name)512        if m:513            num, bpart = m.group(1).strip(), m.group(2).strip()514515        # adresse civique de la carte516        address = ""517        city = "Trois-Rivières"518        civic = ""519        ma = _ADDR_RE.search(card)520        if ma:521            civic, city, postal = (ma.group(1).strip(), ma.group(2).strip(),522                                   ma.group(3).strip())523            address = f"{civic}, {city}, {postal}"524525        # immeuble du RSC correspondant (GPS, nom officiel, slug)526        bobj: dict = {}527        for b in buildings.values():528            baddr = str(b.get("address") or "").strip().lower()529            bname_l = str(b.get("name") or "").strip().lower()530            if civic and baddr and civic.lower() == baddr:531                bobj = b532                break533            if bpart and bname_l and bpart.lower() in (bname_l, baddr):534                bobj = b535                break536        bname = str(bobj.get("name") or "").strip() or bpart537        bslug = str(bobj.get("slug") or "").strip()538        if not address and bobj:539            address = ", ".join(x for x in (540                str(bobj.get("address") or "").strip(),541                str(bobj.get("city") or "").strip(),542                str(bobj.get("postalCode") or "").strip()) if x)543            city = str(bobj.get("city") or "").strip() or city544        try:545            lat = float(bobj["latitude"]) if bobj.get("latitude") else None546            lng = float(bobj["longitude"]) if bobj.get("longitude") else None547        except (TypeError, ValueError):548            lat = lng = None549550        # statut : « Disponible » ou « Disponible - 1 avril 2027 »551        status = str(row.get("status") or "").strip()552        if not status:553            ms = re.search(r"Disponible(?:\s*-\s*[^|<]{0,40})?", card)554            status = ms.group(0).strip() if ms else "Disponible"555        availability = status or "Disponible"556        avail_date = _date_fr(status)557        if avail_date:558            availability = f"Disponible à partir du {avail_date}"559560        # prix : cellule « Prix /mois » du tableau, sinon carte — le dernier561        # montant est le prix courant (« Prix régulier 1 595 $ 1 445 $ »)562        price = None563        for src in (str(row.get("price") or ""), card):564            amounts = [_cell_num(a) for a in _PRICE_RE.findall(src)]565            amounts = [a for a in amounts if a and a > 100]566            if amounts:567                price = float(amounts[-1])568                break569570        beds = _cell_num(str(row.get("beds") or ""))571        baths = _cell_num(str(row.get("baths") or ""))572        area = _cell_num(str(row.get("area") or ""))573574        desc: list[str] = []575        floor = str(row.get("floor") or "").strip()576        if floor:577            desc.append(f"Étage : {floor}")578        if beds:579            desc.append(f"{int(beds)} chambre(s)")580        if baths:581            desc.append(f"{int(baths)} salle(s) de bain")582583        details: dict = {}584        if bname:585            details["building"] = bname586        mf = re.match(r"(\d+)", floor)587        if mf:588            details["floor"] = int(mf.group(1))589        if beds:590            details["bedrooms"] = int(beds)591        if baths:592            details["bathrooms"] = int(baths)593594        # type dérivé des chambres (patron quartier_sila/somex : 1 -> 3½)595        unit_type = ""596        if beds is not None:597            unit_type = "Studio" if beds < 1 else f"{int(beds) + 2}½"598599        url = f"{LIST_URL}?building={bslug}" if bslug else LIST_URL600        title = (f"Gestions Thrace ({bname}) — unité {num}" if bname601                 else f"Gestions Thrace — unité {num}")602603        return Listing(604            source=self.source_id,605            external_id=uid,                       # UUID Livya : stable606            url=url,607            title=title,608            address=address,609            sector="",610            city=city,611            unit_type=unit_type,612            bedrooms=beds if beds else None,613            bathrooms=baths if baths else None,614            price=price,615            price_label=f"{price:.0f} $ /mois" if price else "",616            availability=availability,617            availability_date=avail_date,618            area_sqft=area if area and area > 100 else None,619            description=" | ".join(desc),620            amenities=[],621            details=details,622            images=list(d.get("images") or [])[:12],623            lat=lat,624            lng=lng,625        )626
Files main
Menu

Theme