forked from TIL-24/til-24-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_nlp.py
74 lines (64 loc) · 2.21 KB
/
test_nlp.py
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
import json
from typing import Dict, List
import pandas as pd
import requests
from tqdm import tqdm
from pathlib import Path
from scoring.nlp_eval import nlp_eval
from dotenv import load_dotenv
import os
load_dotenv()
TEAM_NAME = os.getenv("TEAM_NAME")
TEAM_TRACK = os.getenv("TEAM_TRACK")
def main():
# input_dir = Path(f"/home/jupyter/{TEAM_TRACK}")
input_dir = Path(f"../../data/{TEAM_TRACK}/train")
# results_dir = Path(f"/home/jupyter/{TEAM_NAME}")
results_dir = Path("results")
results_dir.mkdir(parents=True, exist_ok=True)
with open(input_dir / "nlp.jsonl", "r") as f:
instances = [json.loads(line.strip()) for line in f if line.strip() != ""]
results = run_batched(instances)
df = pd.DataFrame(results)
df.to_csv(results_dir / "nlp_results.csv", index=False)
# calculate eval
eval_result = nlp_eval(
[result["truth"] for result in results],
[result["prediction"] for result in results],
)
print(f"NLP result: {eval_result}")
def run_batched(
instances: List[Dict[str, str | int]], batch_size: int = 4
) -> List[Dict[str, str | int]]:
# split into batches
results = []
for index in tqdm(range(0, len(instances), batch_size)):
_instances = instances[index : index + batch_size]
response = requests.post(
"http://localhost:5002/extract",
data=json.dumps(
{
"instances": [
{"key": _instance["key"], "transcript": _instance["transcript"]}
for _instance in _instances
]
}
),
)
_results = response.json()["predictions"]
results.extend(
[
{
"key": _instances[i]["key"],
"truth": {
field: _instances[i][field]
for field in ("heading", "target", "tool")
},
"prediction": _results[i],
}
for i in range(len(_instances))
]
)
return results
if __name__ == "__main__":
main()