AstraWeave / eval /run_eval.py
sam2009897's picture
Upload folder using huggingface_hub
99d77de verified
Raw History Blame Contribute Delete
2.38 kB
import json, os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from app.tools import web_search, compute, answer_from_llm, extract_answer
import re
_NUM_WORDS = {"zero":"0","one":"1","two":"2","three":"3","four":"4","five":"5","six":"6","seven":"7","eight":"8","nine":"9","ten":"10"}
def _norm(s: str) -> str:
s = s.lower().replace(",", "")
for word, digit in _NUM_WORDS.items():
s = s.replace(word, digit)
return s
def answer_question(question: str) -> str:
q = question.lower()
has_math = bool(re.search(r'[+\-*/]|\b(sum|average|calculate|compute|multiply|divide|add|subtract|evaluate)\b', q, re.I))
if has_math:
r = compute(q)
if not r.startswith("Error"):
return r
evidence = web_search(question)
if evidence.startswith("[Search error"):
evidence = ""
result = answer_from_llm(question, evidence)
return extract_answer(result)
def run_eval(path="eval/sample_questions.json", output_path="eval/results.json"):
with open(path) as f:
questions = json.load(f)
results = []
for i, q in enumerate(questions):
question = q["question"]
expected = q.get("expected", "")
print(f"[{i+1}/{len(questions)}] {question[:60]}...", end=" ")
try:
answer = answer_question(question)
correct = _norm(expected) in _norm(answer) if expected else None
status = "pass" if correct else "fail"
except Exception as e:
answer = f"[ERROR: {e}]"
correct = False
status = "error"
print(status)
results.append({"question": question, "expected": expected, "answer": answer, "correct": correct, "status": status})
passed = sum(1 for r in results if r["status"] == "pass")
total = len(results)
print(f"\nResults: {passed}/{total} pass ({round(passed/total*100,1)}%)")
summary = {"total": total, "passed": passed, "accuracy": round(passed/total*100, 1)}
if output_path:
with open(output_path, "w") as f:
json.dump({"summary": summary, "results": results}, f, indent=2)
print(f"Saved to {output_path}")
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "eval/sample_questions.json"
out = sys.argv[2] if len(sys.argv) > 2 else "eval/results.json"
run_eval(path, out)