Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : SPSearch10# File : tests/relevance/eval.py11# Description : Mesure la pertinence sur un jeu de requêtes de référence :12# le domaine attendu est-il dans l'index (site:), et à quel13# rang sort-il ?14# Module : tests15# Repository : https://git.spboucher.ai/spweb16# Project Website : https://search.spboucher.ai17# Created : 2026-11-3018# Last Modified : 2026-11-3019#20# =============================================================================21# AUTHOR & PROFESSIONAL AFFILIATION22# =============================================================================23#24# Author : Simon-Pierre Boucher25# Position : Professor of Finance26# Institution : Université du Québec en Outaouais (UQO)27# Department : Département des sciences administratives28# Organization : SP Boucher29#30# Website : https://spboucher.ai31# Git : https://git.spboucher.ai32#33# =============================================================================34# OFFICIAL CONTACT DIRECTORY35# =============================================================================36#37# General : info@spboucher.ai38# Professional : contact@spboucher.ai39# Direct : simon@spboucher.ai40# Research : research@spboucher.ai41# Development : dev@spboucher.ai42# Support : support@spboucher.ai43# Security/Admin : admin@spboucher.ai44# Notifications : notifications@spboucher.ai45#46# Preferred Contact: contact@spboucher.ai47#48# =============================================================================49# COPYRIGHT & INTELLECTUAL PROPERTY50# =============================================================================51#52# Copyright (c) 202653# Simon-Pierre Boucher54#55# All rights reserved where applicable.56#57# This file is governed by the applicable project license,58# copyright notices, institutional agreements and relevant law.59#60# Unless expressly authorized by the applicable license or61# rights holder, copying, redistribution, sublicensing,62# publication and commercial exploitation are not permitted.63#64# Existing third-party rights and notices remain unaffected.65#66# =============================================================================67# CONFIDENTIALITY & SECURITY68# =============================================================================69#70# Classification : Public71# Distribution : Public repository; use is governed by the project license72# Security Contact : admin@spboucher.ai73#74# Access to this source does not independently grant permission75# to redistribute or disclose confidential materials.76#77# Do not embed credentials, private keys, access tokens,78# certificates or confidential personal information.79#80# =============================================================================81# LICENSE & MAINTENANCE82# =============================================================================83#84# License : None specified (no license file in this repository)85# Maintainer : Simon-Pierre Boucher86# Technical Contact: dev@spboucher.ai87#88# =============================================================================89# END OF SP BOUCHER SOURCE HEADER90# =============================================================================9192"""Mesure la pertinence sur un jeu de requêtes de référence : le domaine attendu est-il dans l'index (site:),93et à quel rang sort-il ? Usage : eval.py [base, défaut http://127.0.0.1:8901] [--detail]"""94import json, sys, time, urllib.parse, urllib.request, os95base = next((a for a in sys.argv[1:] if a.startswith("http")), "http://127.0.0.1:8901")96detail = "--detail" in sys.argv97def get(q, limit=20):98 # REGION=ca (ou ca-qc, fr, none) : région simulée de l'utilisateur ; défaut : aucune.99 u = f"{base}/v1/search?limit={limit}&hl=fr®ion={os.environ.get('REGION', 'none')}&q=" + urllib.parse.quote(q)100 for _ in range(3):101 try:102 return json.loads(urllib.request.urlopen(u, timeout=10).read())103 except Exception as e:104 time.sleep(2)105 return {"results": []}106def dom_ok(d, wanted):107 return any(d == w or d.endswith("." + w) for w in wanted)108rows = [l.rstrip("\n").split("\t") for l in open(os.path.join(os.path.dirname(__file__), "queries.tsv"), encoding="utf-8") if l.strip() and not l.startswith("#")]109stats = {"n": 0, "indexed": 0, "top1": 0, "top3": 0, "top10": 0, "mrr": 0.0}110for q, wanted, kind in rows:111 wanted = wanted.split("|")112 res = get(q)["results"]113 rank = next((i + 1 for i, r in enumerate(res) if dom_ok(r["domain"], wanted)), None)114 indexed = rank is not None or any(get(f"{q} site:{w}", 1)["results"] or get(f"site:{w} a", 1)["results"] for w in wanted[:2])115 stats["n"] += 1; stats["indexed"] += bool(indexed)116 if rank:117 stats["top1"] += rank == 1; stats["top3"] += rank <= 3; stats["top10"] += rank <= 10; stats["mrr"] += 1 / rank118 if detail or not rank or rank > 1:119 top = res[0] if res else {}120 print(f"{'OK ' if rank == 1 else ' '}{q:38s} rang={str(rank or '-'):>3} {'indexé' if indexed else 'ABSENT':6s} 1er: {top.get('domain','')} | {top.get('title','')[:46]}")121 time.sleep(1.1)122n = stats["n"]123print(f"\n{n} requêtes · domaine présent dans l'index : {stats['indexed']} · rang 1 : {stats['top1']} · top 3 : {stats['top3']} · top 10 : {stats['top10']} · MRR {stats['mrr']/n:.3f}")124