SPB Git

Repository Public

eval_louka.py 5.9 KB 147 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : KA Enrich7# File             : tools/eval_louka.py8# Module           : Scripts9# Repository       : https://git.spboucher.ai/ka-enrich10# Project Website  : Not specified11# Created          : 2026-12-0312# Last Modified    : 2026-12-0313#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Compare les faits rendus par un modèle aux valeurs déjà connues de Lou-Ka.4243Pour chaque champ : faits retenus, rejets par motif, puis accord avec la base44là où la base connaît déjà la valeur (source structurée ou text mining). Les45désaccords sont listés avec la citation, pour relecture humaine.4647    python3 tools/eval_louka.py --db data/louka.db --out <lot de sortie>.jsonl [--show 40]48"""49from __future__ import annotations5051import argparse52import collections53import json54import sqlite3555657def known(row) -> dict:58    d = json.loads(row["details"] or "{}")59    faits = (json.loads(row["digest"] or "{}") or {}).get("faits") or {}60    park = d.get("parking") if isinstance(d.get("parking"), dict) else {}61    furn = d.get("furnished")62    if furn is None and row["furnished"] is not None:63        furn = bool(row["furnished"])64    out = {65        "area_sqft": row["area_sqft"],66        "bathrooms": row["bathrooms"],67        "availability": row["availability_date"],68        "pets": row["pets"],69        "furnished": {True: "oui", False: "non", "semi": "semi"}.get(furn),70        "construction_year": d.get("construction_year"),71        "parking": ("inclus" if park.get("included") is True else72                    "payant" if park.get("price") or park.get("included") is False else73                    "disponible" if park.get("available") else None),74        "parking_price": park.get("price"),75        "floor": d.get("floor"),76        "smoking": {False: "interdit", True: "permis"}.get(d.get("smoking")),77        "lease_min_months": faits.get("duree_bail_minimale_mois"),78    }79    return {k: v for k, v in out.items() if v not in (None, "")}808182def same(field: str, a, b) -> bool:83    if isinstance(a, (int, float)) and isinstance(b, (int, float)):84        return abs(float(a) - float(b)) <= max(0.02 * abs(float(b)), 0.01)85    if field == "parking":86        # « disponible » en base ne contredit ni « inclus » ni « payant »87        return a == b or "disponible" in (a, b)88    return str(a) == str(b)899091def main() -> int:92    ap = argparse.ArgumentParser()93    ap.add_argument("--db", required=True)94    ap.add_argument("--out", required=True)95    ap.add_argument("--show", type=int, default=30)96    a = ap.parse_args()97    con = sqlite3.connect(f"file:{a.db}?mode=ro", uri=True)98    con.row_factory = sqlite3.Row99    rows = [json.loads(l) for l in open(a.out).read().split("\n") if l.strip()]100    kept = collections.Counter()101    new = collections.Counter()102    agree = collections.Counter()103    differ = collections.Counter()104    rej = collections.defaultdict(collections.Counter)105    diffs, news = [], []106    ms = []107    for r in rows:108        ms.append(r.get("ms") or 0)109        row = con.execute("SELECT * FROM listings WHERE uid=?", (r["uid"],)).fetchone()110        base = known(row) if row else {}111        for f, why in (r.get("rejected") or {}).items():112            rej[f][why] += 1113        for f, item in (r.get("facts") or {}).items():114            kept[f] += 1115            if f in base:116                if same(f, item["v"], base[f]):117                    agree[f] += 1118                else:119                    differ[f] += 1120                    diffs.append((f, r["uid"], item["v"], base[f], item["q"]))121            else:122                new[f] += 1123                news.append((f, r["uid"], item["v"], item["q"]))124    n = len(rows)125    print(f"{n} annonces, {sum(kept.values())} faits retenus, "126          f"{sum(sum(c.values()) for c in rej.values())} rejetés, "127          f"erreurs {sum(1 for r in rows if r.get('error'))}, "128          f"médiane {sorted(ms)[n // 2]} ms")129    print(f"{'champ':18s} {'retenus':>7s} {'nouveaux':>8s} {'accord':>6s} {'désacc.':>7s}  rejets")130    for f in sorted(set(kept) | set(rej)):131        print(f"{f:18s} {kept[f]:7d} {new[f]:8d} {agree[f]:6d} {differ[f]:7d}  {dict(rej[f]) or ''}")132    tot_a, tot_d = sum(agree.values()), sum(differ.values())133    if tot_a + tot_d:134        print(f"accord global avec la base : {tot_a}/{tot_a + tot_d} = {100 * tot_a / (tot_a + tot_d):.1f} %")135    print("\n== désaccords (champ | uid | modèle | base | citation)")136    for d in diffs[:a.show]:137        print(" | ".join(str(x) for x in d))138    print("\n== nouveaux faits (champ | uid | valeur | citation)")139    step = max(1, len(news) // a.show)140    for d in news[::step][:a.show]:141        print(" | ".join(str(x) for x in d))142    return 0143144145if __name__ == "__main__":146    raise SystemExit(main())147
Files main
Menu

Theme