File size: 4,258 Bytes
736d46c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
"""Compute Execution Accuracy (EX) of a predictions file against SCM-SQL.

Expected input: a JSONL file where each line is
  {"id": "L1-001", "pred_sql": "SELECT ..."}

Usage:
  python examples/evaluate_predictions.py path/to/predictions.jsonl

Requires:
  * The Odoo 17 demo database running on localhost:5432 (see
    https://github.com/AniruddhaPKawarase/scm-nl2sql for the compose file).
  * psycopg  (`pip install psycopg[binary]`)

Emits a per-level table + overall EX / Soft-EX.

Row-multiset equality is order-agnostic and column-name-agnostic (Soft-EX
mode) or column-name-strict (EX mode).
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from collections import Counter, defaultdict
from pathlib import Path

import yaml
import psycopg


HERE = Path(__file__).resolve().parent
DATA = HERE.parent / "data" / "pilot_500.yaml"


def load_pairs() -> dict[str, dict]:
    doc = yaml.safe_load(DATA.read_text(encoding="utf-8"))
    return {p["id"]: p for p in doc["pairs"]}


def load_predictions(path: Path) -> dict[str, str]:
    preds: dict[str, str] = {}
    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line:
            continue
        rec = json.loads(line)
        preds[rec["id"]] = rec.get("pred_sql", "")
    return preds


def execute(conn: psycopg.Connection, sql: str) -> tuple[list[tuple], str]:
    try:
        with conn.cursor() as cur:
            cur.execute("SET LOCAL statement_timeout = 15000")
            cur.execute(sql)
            rows = cur.fetchall()
        return rows, ""
    except Exception as exc:
        conn.rollback()
        return [], str(exc)[:200]


def rows_equal(pred: list[tuple], gold: list[tuple], soft: bool = False) -> bool:
    """Order-agnostic row-multiset equality."""
    if soft:
        p = sorted(tuple(r) for r in pred)
        g = sorted(tuple(r) for r in gold)
        return p == g
    return sorted(pred) == sorted(gold)


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("predictions", type=Path, help="JSONL with lines like {id, pred_sql}")
    ap.add_argument("--host", default=os.environ.get("POSTGRES_HOST", "localhost"))
    ap.add_argument("--db",   default=os.environ.get("POSTGRES_DB", "odoo"))
    ap.add_argument("--user", default=os.environ.get("POSTGRES_USER", "odoo"))
    ap.add_argument("--password", default=os.environ.get("POSTGRES_PASSWORD", "odoo_dev_pwd"))
    args = ap.parse_args()

    pairs = load_pairs()
    preds = load_predictions(args.predictions)

    conn = psycopg.connect(
        host=args.host, dbname=args.db, user=args.user, password=args.password,
    )

    per_level: dict[int, dict[str, int]] = defaultdict(lambda: {"n": 0, "ex": 0, "soft": 0})
    total_n = total_ex = total_soft = 0

    for pid, pair in pairs.items():
        pred_sql = preds.get(pid, "")
        if not pred_sql:
            continue  # not predicted — skip
        # Gold: for L6 we evaluate the LAST turn only in this simple demo
        gold_sql = pair.get("gold_sql") or pair["turns"][-1]["gold_sql"]

        gold_rows, gold_err = execute(conn, gold_sql)
        if gold_err:
            continue
        pred_rows, pred_err = execute(conn, pred_sql)
        ex = 0 if pred_err else int(rows_equal(pred_rows, gold_rows))
        soft = 0 if pred_err else int(rows_equal(pred_rows, gold_rows, soft=True))

        lvl = pair["level"]
        per_level[lvl]["n"] += 1
        per_level[lvl]["ex"] += ex
        per_level[lvl]["soft"] += soft
        total_n += 1
        total_ex += ex
        total_soft += soft

    conn.close()

    print("Per-level results:")
    for lvl in sorted(per_level):
        s = per_level[lvl]
        ex_pct = 100 * s["ex"] / s["n"] if s["n"] else 0
        sf_pct = 100 * s["soft"] / s["n"] if s["n"] else 0
        print(f"  L{lvl}  n={s['n']:4d}  EX={ex_pct:5.1f}%  Soft-EX={sf_pct:5.1f}%")
    if total_n:
        print(f"\nOverall  n={total_n:4d}  "
              f"EX={100*total_ex/total_n:5.1f}%  "
              f"Soft-EX={100*total_soft/total_n:5.1f}%")
    else:
        print("\nNo predictions overlapped with the dataset. Nothing to score.")
    return 0


if __name__ == "__main__":
    sys.exit(main())