from collections import Counter, defaultdict def chars(text, spans): return {i for s in spans for i in range(s["start"], s["end"]) if not text[i].isspace()} def safe_ratio(a, b): return round(a/b, 6) if b else None def prf(tp, pred, gold): return {"precision": safe_ratio(tp, pred), "recall": safe_ratio(tp, gold), "f1": safe_ratio(2*tp, pred+gold)} def score(rows, predictions): total = Counter() labels = defaultdict(Counter) for row in rows: text, gold = row["text"], row["gold"] pred = predictions[row["id"]] for source in [gold, pred]: assert all(0 <= s["start"] < s["end"] <= len(text) for s in source) true_chars, pred_chars = chars(text, gold), chars(text, pred) protected = len(true_chars & pred_chars) bounds = lambda values: {(e["start"],e["end"]) for e in values} pb, gb = bounds(pred), bounds(gold) typed = lambda values: {(e["start"],e["end"],e["label"]) for e in values} total.update(documents=1, gold_entities=len(gold), predicted_entities=len(pred), gold_chars=len(true_chars), pred_chars=len(pred_chars), protected_chars=protected, non_gold_chars=sum(not c.isspace() for c in text)-len(true_chars), overmasked_chars=len(pred_chars-true_chars), exact_bounds=len(pb & gb), exact_typed=len(typed(gold) & typed(pred))) if not gold: total.update(negative_documents=1, negative_documents_flagged=int(bool(pred))) missed = 0 for entity in gold: truth = chars(text, [entity]) covered = int(truth <= pred_chars) all_alnum = all(i in pred_chars for i in truth if text[i].isalnum()) total.update(only_punctuation_unmasked=int(bool(all_alnum) and not covered)) missed += 1 - covered labels[entity["label"]].update(total=1, fully_masked=covered, all_alnum_masked=int(all_alnum), completely_missed=int(not truth & pred_chars)) total.update(fully_masked=len(gold)-missed, positive_documents_with_any_leak=int(bool(missed))) out = dict(total) out["full_entity_mask_rate"] = safe_ratio(total["fully_masked"], total["gold_entities"]) out["non_gold_mask_rate"] = safe_ratio(total["overmasked_chars"], total["non_gold_chars"]) out["negative_doc_mask_rate"] = safe_ratio(total["negative_documents_flagged"], total["negative_documents"]) out["source_char"] = prf(total["protected_chars"], total["pred_chars"], total["gold_chars"]) out["exact_bounds"] = prf(total["exact_bounds"], total["predicted_entities"], total["gold_entities"]) out["exact_typed"] = prf(total["exact_typed"], total["predicted_entities"], total["gold_entities"]) out["per_gold_class"] = {k:dict(v) for k,v in sorted(labels.items())} return out def marks(text, word_list): """Recover word-indexed insertions; an unalignable lexical edit invalidates the row.""" observed=set() i=0 for word in text.split(): if i and word=="-": observed.add((i-1,"-")) continue if i==len(word_list) or not word.startswith(word_list[i]): return observed,True added=word[len(word_list[i]):] if any(c not in ".,?:;!-" for c in added): return observed,True if added: observed.add((i,added)) i+=1 return observed,i!=len(word_list) def punctuation_score(rows,pred): tp=fp=fn=changed=negative=flagged=exact=0 for r in rows: expected={(s["index"],s["mark"]) for s in r["gold"]} actual,edit=marks(pred[r["id"]],r["text"].split()) changed+=edit tp+=len(actual & expected) fp+=len(actual-expected) fn+=len(expected-actual) negative+=not expected flagged+=int(not expected and (bool(actual) or edit)) exact+=int(pred[r["id"]]==r["reference"]) return {"documents":len(rows),"correct":tp,"extra_marks":fp,"missed_marks":fn, "mark_f1":2*tp/max(1,2*tp+fp+fn),"word_changed_documents":changed, "negative_documents":negative,"negative_documents_flagged":flagged,"exact_documents":exact}