File size: 4,997 Bytes
715cc5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
from __future__ import annotations

import hashlib
import re
import unicodedata
from typing import Iterable


WHITESPACE_RE = re.compile(r"\s+")
PUNCT_RE = re.compile(r"[^\w\s]", flags=re.UNICODE)
SENTENCE_BOUNDARY_RE = re.compile(r"(?<=[.!?。!?])\s+")


def normalize_whitespace(text: object) -> str:
    if text is None:
        return ""
    return WHITESPACE_RE.sub(" ", str(text).replace("\x00", " ")).strip()


def normalize_for_hash(text: object) -> str:
    normalized = unicodedata.normalize("NFKC", normalize_whitespace(text)).casefold()
    normalized = normalized.replace("’", "'").replace("‘", "'")
    normalized = normalized.replace("“", '"').replace("”", '"')
    normalized = normalized.replace("–", "-").replace("—", "-")
    normalized = PUNCT_RE.sub(" ", normalized)
    return normalize_whitespace(normalized)


def stable_hash(text: object, length: int = 16) -> str:
    return hashlib.sha1(normalize_for_hash(text).encode("utf-8")).hexdigest()[:length]


def stable_hash_raw(*parts: object, length: int = 16) -> str:
    raw = "\u241f".join(normalize_whitespace(part) for part in parts)
    return hashlib.sha1(raw.encode("utf-8")).hexdigest()[:length]


def word_count(text: object) -> int:
    text = normalize_whitespace(text)
    if not text:
        return 0
    return len(text.split())


def split_sentences(text: object) -> list[str]:
    text = normalize_whitespace(text)
    if not text:
        return []
    parts = [normalize_whitespace(part) for part in SENTENCE_BOUNDARY_RE.split(text)]
    return [part for part in parts if part]


def split_long_text_by_words(text: str, max_words: int, overlap_words: int = 30) -> list[str]:
    words = text.split()
    if len(words) <= max_words:
        return [text] if text else []
    chunks: list[str] = []
    step = max(1, max_words - overlap_words)
    for start in range(0, len(words), step):
        chunk_words = words[start : start + max_words]
        if chunk_words:
            chunks.append(" ".join(chunk_words))
        if start + max_words >= len(words):
            break
    return chunks


def make_sentence_chunks(
    sentences: Iterable[str],
    max_words: int = 180,
    overlap_sentences: int = 1,
) -> list[dict[str, object]]:
    sentence_list = [normalize_whitespace(sentence) for sentence in sentences if normalize_whitespace(sentence)]
    chunks: list[dict[str, object]] = []
    i = 0
    while i < len(sentence_list):
        current: list[str] = []
        start_i = i
        total_words = 0
        while i < len(sentence_list):
            sentence_words = word_count(sentence_list[i])
            if current and total_words + sentence_words > max_words:
                break
            if not current and sentence_words > max_words:
                for sub_idx, sub_chunk in enumerate(split_long_text_by_words(sentence_list[i], max_words=max_words)):
                    chunks.append(
                        {
                            "text": sub_chunk,
                            "start_sent_id": i,
                            "end_sent_id": i,
                            "subchunk": sub_idx,
                        }
                    )
                i += 1
                break
            current.append(sentence_list[i])
            total_words += sentence_words
            i += 1
        if current:
            chunks.append(
                {
                    "text": normalize_whitespace(" ".join(current)),
                    "start_sent_id": start_i,
                    "end_sent_id": i - 1,
                    "subchunk": None,
                }
            )
        if overlap_sentences > 0 and i < len(sentence_list):
            i = max(start_i + 1, i - overlap_sentences)
    return chunks


def canonical_label(dataset: str, raw_label: object) -> str | None:
    if raw_label is None:
        return None
    label = normalize_whitespace(raw_label)
    if dataset == "vifactcheck":
        return {"0": "SUPPORTS", "1": "REFUTES", "2": "NEI"}.get(label)
    normalized = normalize_for_hash(label)
    if dataset == "averitec":
        mapping = {
            "supported": "SUPPORTS",
            "refuted": "REFUTES",
            "not enough evidence": "NEI",
            "conflicting evidence cherrypicking": "CONFLICTING",
            "conflicting evidence cherry picking": "CONFLICTING",
            "conflicting evidence cherry-picking": "CONFLICTING",
        }
        return mapping.get(normalized)
    if dataset == "healthver":
        mapping = {
            "supports": "SUPPORTS",
            "support": "SUPPORTS",
            "refutes": "REFUTES",
            "refute": "REFUTES",
            "neutral": "NEI",
            "nei": "NEI",
        }
        return mapping.get(normalized)
    return label.upper() if label else None


def json_safe(value: object) -> object:
    if value is None:
        return None
    if isinstance(value, (str, int, float, bool)):
        return value
    return str(value)