File size: 7,151 Bytes
399f588 | 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | import json
from pathlib import Path
from src.schemas.labels import LABEL_REMAP, SENTIMENT_LABELS
VALID_LABELS = set(SENTIMENT_LABELS.classes)
def _deduplicate_articles(samples: list[dict]) -> list[dict]:
"""Remove samples with duplicate article text, keeping the first."""
seen_texts = set()
deduped = []
removed = 0
for s in samples:
if s["text"] in seen_texts:
removed += 1
continue
seen_texts.add(s["text"])
deduped.append(s)
print(f"Deduplicated articles: removed {removed}, kept {len(deduped)}")
return deduped
def _remap_labels(samples: list[dict]) -> list[dict]:
"""Remap non-standard labels and drop entities with unmappable labels."""
mapping = LABEL_REMAP.mapping
remapped_count = 0
dropped_count = 0
for s in samples:
cleaned_entities = []
for e in s["entities"]:
label = e["label"]
if label in VALID_LABELS:
cleaned_entities.append(e)
elif label in mapping:
e["label"] = mapping[label]
cleaned_entities.append(e)
remapped_count += 1
else:
dropped_count += 1
s["entities"] = cleaned_entities
print(f"Labels remapped: {remapped_count}, dropped (unmappable): {dropped_count}")
return samples
def _fix_position_text(samples: list[dict]) -> list[dict]:
"""Overwrite position_text with actual span from article text when case differs."""
fixed = 0
for s in samples:
text = s["text"]
for e in s["entities"]:
for p in e["positions"]:
end = p["offset"] + p["length"]
if end > len(text):
continue
actual = text[p["offset"]:end]
if actual != p["position_text"] and actual.lower() == p["position_text"].lower():
p["position_text"] = actual
fixed += 1
print(f"Position text case mismatches fixed: {fixed}")
return samples
def _merge_entities(samples: list[dict]) -> list[dict]:
"""Merge entity records sharing (entity_text, label) within a sample.
Collects all positions into a single entity record per unique
(entity_text.lower(), label) pair.
"""
total_merged = 0
different_label = 0
for s in samples:
merged: dict[str, dict] = {}
label_seen: dict[str, str] = {}
for e in s["entities"]:
key = e["entity_text"].lower()
if key in label_seen and label_seen[key] != e["label"]:
different_label += 1
merge_key = (key, e["label"])
if merge_key in merged:
merged[merge_key]["positions"].extend(e["positions"])
total_merged += 1
else:
merged[merge_key] = {
"entity_id": e["entity_id"],
"entity_text": e["entity_text"],
"entity_type": e["entity_type"],
"positions": list(e["positions"]),
"label": e["label"],
}
label_seen[key] = e["label"]
s["entities"] = list(merged.values())
print(f"Entities merged: {total_merged}, different-label pairs: {different_label}")
return samples
def _deduplicate_positions(samples: list[dict]) -> list[dict]:
"""Remove exact-duplicate positions (same offset + length) within each entity."""
removed = 0
for s in samples:
for e in s["entities"]:
seen = set()
unique = []
for p in e["positions"]:
span = (p["offset"], p["length"])
if span in seen:
removed += 1
continue
seen.add(span)
unique.append(p)
e["positions"] = unique
print(f"Exact-duplicate positions removed: {removed}")
return samples
def _resolve_same_offset(samples: list[dict]) -> list[dict]:
"""For positions sharing the same offset, keep the longest span."""
resolved = 0
for s in samples:
for e in s["entities"]:
by_offset: dict[int, dict] = {}
for p in e["positions"]:
off = p["offset"]
if off not in by_offset or p["length"] > by_offset[off]["length"]:
if off in by_offset:
resolved += 1
by_offset[off] = p
e["positions"] = sorted(by_offset.values(), key=lambda p: p["offset"])
print(f"Same-offset positions resolved (kept longest): {resolved}")
return samples
def _resolve_partial_overlaps(samples: list[dict]) -> list[dict]:
"""Resolve positions that partially overlap (different offset, shared characters).
Positions are already sorted by offset. When two positions overlap,
the longer span is kept and the shorter one is discarded.
"""
resolved = 0
for s in samples:
for e in s["entities"]:
positions = sorted(e["positions"], key=lambda p: p["offset"])
kept: list[dict] = []
for p in positions:
if not kept:
kept.append(p)
continue
prev = kept[-1]
prev_end = prev["offset"] + prev["length"]
if p["offset"] < prev_end:
resolved += 1
if p["length"] > prev["length"]:
kept[-1] = p
else:
kept.append(p)
e["positions"] = kept
print(f"Partial overlaps resolved (kept longest): {resolved}")
return samples
def preprocess(samples: list[dict]) -> list[dict]:
"""Run the full preprocessing pipeline on raw samples."""
samples = _deduplicate_articles(samples)
samples = _remap_labels(samples)
samples = _fix_position_text(samples)
samples = _merge_entities(samples)
samples = _deduplicate_positions(samples)
samples = _resolve_same_offset(samples)
samples = _resolve_partial_overlaps(samples)
total_entities = sum(len(s["entities"]) for s in samples)
print(f"Preprocessing complete: {len(samples)} samples, {total_entities} entities")
return samples
def save_jsonl(samples: list[dict], path: str | Path) -> None:
"""Write preprocessed samples as JSONL (one JSON object per line)."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
for s in samples:
f.write(json.dumps(s, ensure_ascii=False) + "\n")
print(f"Saved {len(samples)} samples to {path}")
def main(
input_path: str | Path = "data/data_raw.json",
output_path: str | Path = "data/data_preprocessed.jsonl",
) -> list[dict]:
"""Load raw data, preprocess, and save."""
with open(input_path, "r", encoding="utf-8") as f:
raw = json.load(f)
print(f"Loaded {len(raw)} raw samples from {input_path}")
samples = preprocess(raw)
save_jsonl(samples, output_path)
return samples
if __name__ == "__main__":
main()
|