Download src/shl/evaluator.py from Enternal1/docker: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/spaces/Enternal1/docker/resolve/main/src/shl/evaluator.py
- Command line
-
hf download hf://spaces/Enternal1/docker/src/shl/evaluator.py
-
curl -L -o evaluator.py https://huggingface.co/spaces/Enternal1/docker/resolve/main/src/shl/evaluator.py
10.9 kB
| import os | |
| try: | |
| import pandas as pd # type: ignore | |
| except Exception: | |
| pd = None | |
| from typing import List, Dict, Any | |
| import zipfile | |
| import xml.etree.ElementTree as ET | |
| import json | |
| import urllib.request | |
| DATASET_PATH = "Gen_AI Dataset.xlsx" | |
| OUTPUT_DIR = "outputs" | |
| def ensure_dirs(): | |
| os.makedirs(OUTPUT_DIR, exist_ok=True) | |
| def read_train() -> List[Dict[str, Any]]: | |
| if pd is None: | |
| return [] | |
| xls = pd.ExcelFile(DATASET_PATH) | |
| sn = None | |
| for s in xls.sheet_names: | |
| if "train" in s.lower(): | |
| sn = s | |
| break | |
| if sn is None: | |
| sn = xls.sheet_names[0] | |
| df = xls.parse(sn) | |
| cols = [c for c in df.columns] | |
| q_col = None | |
| gt_col = None | |
| for c in cols: | |
| lc = c.lower() | |
| if "query" in lc: | |
| q_col = c | |
| if "url" in lc or "ground" in lc or "relevant" in lc: | |
| gt_col = c | |
| if q_col is None or gt_col is None: | |
| raise RuntimeError("train columns not found") | |
| rows = [] | |
| for _, r in df.iterrows(): | |
| q = str(r[q_col]).strip() | |
| gt = str(r[gt_col]).strip() | |
| gts = [x.strip() for x in gt.split(",") if x.strip()] | |
| rows.append({"query": q, "ground_truth": gts}) | |
| return rows | |
| def read_test() -> List[str]: | |
| if pd is None: | |
| return [] | |
| xls = pd.ExcelFile(DATASET_PATH) | |
| sn = None | |
| for s in xls.sheet_names: | |
| if "test" in s.lower(): | |
| sn = s | |
| break | |
| if sn is None: | |
| sn = xls.sheet_names[-1] | |
| df = xls.parse(sn) | |
| cols = [c for c in df.columns] | |
| q_col = None | |
| for c in cols: | |
| if "query" in c.lower(): | |
| q_col = c | |
| break | |
| if q_col is None: | |
| q_col = cols[0] | |
| qs = [str(x).strip() for x in df[q_col].tolist() if str(x).strip()] | |
| return qs | |
| def recall_at_10(pred: List[str], gt: List[str]) -> float: | |
| if not gt: | |
| return 0.0 | |
| s_pred = set([x.strip().lower() for x in pred[:10]]) | |
| s_gt = set([x.strip().lower() for x in gt]) | |
| inter = s_pred.intersection(s_gt) | |
| return float(len(inter)) / float(len(s_gt)) | |
| def evaluate() -> Dict[str, Any]: | |
| ensure_dirs() | |
| from .recommender import Recommender | |
| rec = Recommender() | |
| train = read_train() | |
| rows = [] | |
| vals = [] | |
| for row in train: | |
| q = row["query"] | |
| gt = row["ground_truth"] | |
| items = rec.recommend(q, k=10) | |
| pred = [it["url"] for it in items] | |
| r = recall_at_10(pred, gt) | |
| rows.append({"query": q, "recall_at_10": r}) | |
| vals.append(r) | |
| m = sum(vals) / len(vals) if vals else 0.0 | |
| df = pd.DataFrame(rows) | |
| df.to_csv(os.path.join(OUTPUT_DIR, "train_recall.csv"), index=False) | |
| return {"mean_recall_at_10": m, "count": len(vals)} | |
| def predict_test() -> str: | |
| ensure_dirs() | |
| from .recommender import Recommender | |
| rec = Recommender() | |
| tests = read_test() | |
| out_rows = [] | |
| for q in tests: | |
| items = rec.recommend(q, k=10) | |
| for it in items: | |
| out_rows.append({"Query": q, "Assessment_URL": it["url"]}) | |
| df = pd.DataFrame(out_rows) | |
| outp = os.path.join(OUTPUT_DIR, "test_predictions.csv") | |
| df.to_csv(outp, index=False) | |
| return outp | |
| def predict_test_via_api(base_url: str) -> str: | |
| ensure_dirs() | |
| tests = [] | |
| try: | |
| tests = read_test() | |
| except Exception: | |
| tests = read_test_raw(DATASET_PATH) | |
| out_rows = [] | |
| for q in tests: | |
| try: | |
| url = f"{base_url.rstrip('/')}/api/recommend" | |
| data = json.dumps({"input_type": "text", "query": q, "top_k": 10}).encode("utf-8") | |
| req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST") | |
| with urllib.request.urlopen(req, timeout=60) as resp: | |
| body = resp.read().decode("utf-8") | |
| j = json.loads(body) | |
| for it in j.get("items", []): | |
| url = it.get("url", "") | |
| if url: | |
| out_rows.append({"Query": q, "Assessment_URL": url}) | |
| except Exception: | |
| pass | |
| if pd is not None: | |
| df = pd.DataFrame(out_rows) | |
| else: | |
| import csv | |
| outp = os.path.join(OUTPUT_DIR, "firstname_lastname.csv") | |
| with open(outp, "w", newline="", encoding="utf-8") as f: | |
| w = csv.DictWriter(f, fieldnames=["Query", "Assessment_URL"]) | |
| w.writeheader() | |
| for r in out_rows: | |
| w.writerow(r) | |
| return outp | |
| outp = os.path.join(OUTPUT_DIR, "firstname_lastname.csv") | |
| df.to_csv(outp, index=False) | |
| return outp | |
| def read_test_raw(path: str) -> List[str]: | |
| qs: List[str] = [] | |
| with zipfile.ZipFile(path, "r") as z: | |
| wb = ET.fromstring(z.read("xl/workbook.xml")) | |
| ns_main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" | |
| ns_rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" | |
| sheets = [] | |
| for sh in wb.findall(f".//{{{ns_main}}}sheet"): | |
| name = sh.attrib.get("name", "") | |
| rid = sh.attrib.get(f"{{{ns_rel}}}id", "") | |
| sheets.append((name, rid)) | |
| rels = ET.fromstring(z.read("xl/_rels/workbook.xml.rels")) | |
| id_to_target = {} | |
| for rel in rels.findall(".//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship"): | |
| idv = rel.attrib.get("Id", "") | |
| tgt = rel.attrib.get("Target", "") | |
| id_to_target[idv] = tgt | |
| target = None | |
| for name, rid in sheets: | |
| if "test" in name.lower(): | |
| target = id_to_target.get(rid) | |
| break | |
| if target is None and sheets: | |
| target = id_to_target.get(sheets[-1][1]) | |
| if not target: | |
| return qs | |
| sheet_xml = ET.fromstring(z.read(f"xl/{target}")) | |
| shared = [] | |
| if "xl/sharedStrings.xml" in z.namelist(): | |
| sroot = ET.fromstring(z.read("xl/sharedStrings.xml")) | |
| for si in sroot.findall(f".//{{{ns_main}}}si"): | |
| parts = [] | |
| for t in si.findall(f".//{{{ns_main}}}t"): | |
| parts.append(t.text or "") | |
| shared.append("".join(parts)) | |
| for row in sheet_xml.findall(f".//{{{ns_main}}}row"): | |
| a_text = "" | |
| for c in row.findall(f".//{{{ns_main}}}c"): | |
| r = c.attrib.get("r", "") | |
| if r.startswith("A"): | |
| t = c.attrib.get("t", "") | |
| v_el = c.find(f".//{{{ns_main}}}v") | |
| v = (v_el.text if v_el is not None else "") or "" | |
| if t == "s": | |
| try: | |
| idx = int(v) | |
| a_text = shared[idx] if 0 <= idx < len(shared) else "" | |
| except Exception: | |
| a_text = "" | |
| elif t == "inlineStr": | |
| is_el = c.find(f".//{{{ns_main}}}is") | |
| t_el = is_el.find(f".//{{{ns_main}}}t") if is_el is not None else None | |
| a_text = (t_el.text if t_el is not None else "") or "" | |
| else: | |
| a_text = v | |
| break | |
| val = (a_text or "").strip() | |
| if val and val.lower() != "query": | |
| qs.append(val) | |
| return qs | |
| def predict_test_offline() -> str: | |
| ensure_dirs() | |
| qs: List[str] = [] | |
| try: | |
| qs = read_test() | |
| except Exception: | |
| qs = [] | |
| if not qs: | |
| qs = read_test_raw(DATASET_PATH) | |
| catalog = [ | |
| {"name": "Verify - Numerical Ability", "url": "https://www.shl.com/products/product-catalog/view/verify-numerical-ability/", "type": "K", "tags": ["numerical", "quantitative", "cognitive", "numbers"]}, | |
| {"name": "Verify Interactive – Numerical Reasoning", "url": "https://www.shl.com/products/product-catalog/view/shl-verify-interactive-numerical-reasoning/", "type": "K", "tags": ["numerical", "reasoning", "cognitive"]}, | |
| {"name": "Verify Interactive Numerical Calculation", "url": "https://www.shl.com/products/product-catalog/view/shl-verify-interactive-numerical-calculation/", "type": "K", "tags": ["numerical", "calculation", "math"]}, | |
| {"name": "OPQ32 Occupational Personality Questionnaire", "url": "https://www.shl.com/products/product-catalog/view/occupational-personality-questionnaire-opq32r/", "type": "P", "tags": ["opq", "personality", "behavior", "traits"]}, | |
| {"name": "Python (New)", "url": "https://www.shl.com/solutions/products/product-catalog/view/python-new/", "type": "K", "tags": ["python", "programming", "code"]}, | |
| {"name": "SQL Entry Level", "url": "https://www.shl.com/c/global/ibm-kenexa-catalog/view/33381-sql-entry-level/", "type": "K", "tags": ["sql", "database", "queries"]}, | |
| {"name": "ANSI SQL", "url": "https://www.shl.com/c/global/ibm-kenexa-catalog/view/33506-ansi-sql/", "type": "K", "tags": ["sql", "ansi"]}, | |
| {"name": "Verify G+ Ability Test Report", "url": "https://www.shl.com/products/product-catalog/view/verify-g-ability-test-report/", "type": "K", "tags": ["g+", "general", "cognitive", "ability"]}, | |
| ] | |
| def score(q: str, it: Dict[str, Any]) -> float: | |
| tks = [x.lower() for x in q.split() if x.strip()] | |
| name = it["name"].lower() | |
| tags = [x.lower() for x in it.get("tags", [])] | |
| s = 0.0 | |
| for t in tks: | |
| if t in tags: | |
| s += 1.0 | |
| elif t in name: | |
| s += 0.5 | |
| elif t in ("personality", "behavior", "behaviour") and it["type"] == "P": | |
| s += 0.8 | |
| elif t in ("cognitive", "reasoning") and it["type"] == "K": | |
| s += 0.8 | |
| return s | |
| out_rows: List[Dict[str, str]] = [] | |
| for q in qs: | |
| scored = [(it, score(q, it)) for it in catalog] | |
| scored.sort(key=lambda x: x[1], reverse=True) | |
| k_quota = 5 | |
| p_quota = 5 | |
| k_count = 0 | |
| p_count = 0 | |
| items: List[Dict[str, Any]] = [] | |
| for it, sc in scored: | |
| if it["type"] == "K" and k_count >= k_quota: | |
| continue | |
| if it["type"] == "P" and p_count >= p_quota: | |
| continue | |
| items.append(it) | |
| if it["type"] == "K": | |
| k_count += 1 | |
| else: | |
| p_count += 1 | |
| if len(items) >= 10: | |
| break | |
| for it in items: | |
| out_rows.append({"Query": q, "Assessment_URL": it["url"]}) | |
| outp = os.path.join(OUTPUT_DIR, "firstname_lastname.csv") | |
| try: | |
| import csv | |
| with open(outp, "w", newline="", encoding="utf-8") as f: | |
| w = csv.DictWriter(f, fieldnames=["Query", "Assessment_URL"]) | |
| w.writeheader() | |
| for r in out_rows: | |
| w.writerow(r) | |
| except Exception: | |
| pass | |
| return outp | |