Spaces:
Running
Running
Download utils.py from NbAiLab/allmennkunnskap: direct link, hf CLI and curl.
- Browser
- Download file 4.43 kB
-
https://huggingface.co/spaces/NbAiLab/allmennkunnskap/resolve/main/utils.py
- Command line
-
hf download hf://spaces/NbAiLab/allmennkunnskap/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/NbAiLab/allmennkunnskap/resolve/main/utils.py
4.43 kB
| import re | |
| import unicodedata | |
| from collections import Counter | |
| from string import punctuation | |
| QUESTION_COLUMN = {"nob": "Question", "eng": "Question English Translation"} | |
| ANSWER_COLUMN = {"nob": "Answer", "eng": "Answer English Translation"} | |
| def split_answers(answers): | |
| # Accepted answers are ";"-separated in the source CSV | |
| if isinstance(answers, str): | |
| answers = answers.split(";") | |
| return [answer.strip() for answer in answers or [] if answer and answer.strip()] | |
| def prepare_doc(doc, language="nob"): | |
| # nob accepts only the Norwegian answers. eng accepts the English and the Norwegian ones: many answers are names | |
| # that are the same in both ("Horten"), and the English column only lists the ones that differ ("Trolljegeren" / | |
| # "Trollhunter"). The English answers come first, so accepted_completions[0] (the few-shot target) is in English. | |
| answers = split_answers(doc[ANSWER_COLUMN[language]]) | |
| if language == "eng": | |
| answers += split_answers(doc[ANSWER_COLUMN["nob"]]) | |
| completions = list(dict.fromkeys(answers)) | |
| if not completions: | |
| raise ValueError(f"Question {doc.get('ID')} has no accepted answers") | |
| return {"question": (doc[QUESTION_COLUMN[language]] or "").strip(), "accepted_completions": completions} | |
| def process_docs(dataset): | |
| return dataset.map(lambda doc: prepare_doc(doc, "nob")) | |
| def process_docs_eng(dataset): | |
| return dataset.map(lambda doc: prepare_doc(doc, "eng")) | |
| # Hyphens, dashes (incl. the non-breaking hyphen U+2011) and slashes | |
| SEPARATORS = re.compile(r"[-\u2010-\u2015/]") | |
| def strip_accents(text): | |
| # "André" equals "Andre" and "pâté" equals "pate", but å, æ and ø are kept: they are letters | |
| # of their own in Norwegian. æ and ø have no decomposition, and å's ring (U+030A) is kept. | |
| decomposed = unicodedata.normalize("NFD", text) | |
| return unicodedata.normalize("NFC", "".join(ch for ch in decomposed if not unicodedata.combining(ch) or ch == "̊")) | |
| def normalize(text, separator=""): | |
| # Match NorIdiom: score only the first line, ignoring punctuation and case. | |
| # Same as scripts/make_datasets/new_tasks/metrics.py, which was used to label the dataset, | |
| # except that accents are also ignored here. | |
| # Hyphens and slashes are replaced by `separator`: "" joins "Russe-kort" into "russekort", | |
| # " " splits "NAV-kontoret" into "nav kontoret". process_results tries both. | |
| text = text.split("\n")[0] | |
| text = SEPARATORS.sub(separator, text) | |
| # string.punctuation is ASCII only, so also drop Unicode punctuation such as «» and quotes | |
| text = "".join(ch for ch in text if ch not in punctuation and not unicodedata.category(ch).startswith("P")).lower() | |
| text = strip_accents(text) | |
| text = " ".join(text.split()) # also turns non-breaking and narrow spaces into normal spaces | |
| return re.sub(r"^(en|et|ei|a|an|the) ", "", text) # a leading article, so "En potet" equals "Potet" | |
| def f1(prediction, answer): | |
| pred_toks, gold_toks = prediction.split(), answer.split() | |
| if not pred_toks or not gold_toks: | |
| return int(pred_toks == gold_toks) | |
| num_same = sum((Counter(pred_toks) & Counter(gold_toks)).values()) | |
| if num_same == 0: | |
| return 0 | |
| precision, recall = num_same / len(pred_toks), num_same / len(gold_toks) | |
| return 2 * precision * recall / (precision + recall) | |
| def answer_match(prediction, answer): | |
| # The accepted answer appears as a whole word or phrase ("oslo" matches "oslo sentrum", not "oslofjorden"). | |
| return int(bool(answer) and re.search(rf"(?<!\w){re.escape(answer)}(?!\w)", prediction) is not None) | |
| def score_one(doc, response): | |
| # Best score over both normalizations (hyphens removed / as spaces) and all accepted answers | |
| pairs = [ | |
| (normalize(response, sep), normalize(answer, sep)) | |
| for sep in ("", " ") | |
| for answer in doc["accepted_completions"] | |
| ] | |
| return { | |
| "em": max(int(prediction == answer) for prediction, answer in pairs), | |
| "f1": max(f1(prediction, answer) for prediction, answer in pairs), | |
| "answer_match": max(answer_match(prediction, answer) for prediction, answer in pairs), | |
| } | |
| def process_results(doc, results): | |
| # results[0] holds the K sampled generations; average their scores | |
| scored = [score_one(doc, response) for response in results[0]] | |
| return {key: sum(s[key] for s in scored) / len(scored) for key in scored[0]} | |