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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned entity sentiment and query relevance mirrors; no generated labels or negatives."""
|
| 2 |
+
import ast
|
| 3 |
+
from collections import Counter
|
| 4 |
+
import csv
|
| 5 |
+
import hashlib
|
| 6 |
+
import heapq
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import re
|
| 11 |
+
import urllib.request
|
| 12 |
+
|
| 13 |
+
from datasets import Dataset, DatasetDict, Features, Value
|
| 14 |
+
from huggingface_hub import snapshot_download
|
| 15 |
+
import pyarrow.parquet as pq
|
| 16 |
+
|
| 17 |
+
from .text import _split_of
|
| 18 |
+
|
| 19 |
+
SENTFIN_REVISION = 'eba43610fe3cb57a3e5773cd6c037da1f8992ad5'
|
| 20 |
+
WANDS_REVISION = '16cff4fbe4b46ee0b382e7901ee62461f88a2cb1'
|
| 21 |
+
SEARCH_REVISION = '781d35d1bf87253b3dcd0fadcb82bfbee9c244f1'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def text_key(text):
|
| 25 |
+
return hashlib.sha256(' '.join(text.casefold().split()).encode()).hexdigest()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_sentfin(value):
|
| 29 |
+
"""Repair only the released unescaped-apostrophe dictionary representation."""
|
| 30 |
+
try:
|
| 31 |
+
result = ast.literal_eval(value)
|
| 32 |
+
repaired = False
|
| 33 |
+
except (ValueError, SyntaxError):
|
| 34 |
+
pattern = r"'(.*?)'\s*:\s*'(positive|neutral|negative)'(?=\s*[,}])"
|
| 35 |
+
pairs = re.findall(pattern, value)
|
| 36 |
+
remainder = re.sub(pattern, '', value).strip()
|
| 37 |
+
if not pairs or re.sub(r'[{},\s]', '', remainder) or len(dict(pairs)) != len(pairs):
|
| 38 |
+
raise ValueError('Unrecognized SEntFiN annotation representation')
|
| 39 |
+
result, repaired = dict(pairs), True
|
| 40 |
+
if not isinstance(result, dict) or not result or any(
|
| 41 |
+
not isinstance(k, str) or not k.strip() or v not in ('negative', 'neutral', 'positive')
|
| 42 |
+
for k, v in result.items()):
|
| 43 |
+
raise ValueError('Invalid SEntFiN entity sentiment')
|
| 44 |
+
return result, repaired
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def write_mirror(name, splits, label_type, report):
|
| 48 |
+
directory = Path('build') / (name + '-release')
|
| 49 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
features = Features(dict(sentence1=Value('string'), sentence2=Value('string'),
|
| 51 |
+
labels=Value(label_type), metadata=Value('string')))
|
| 52 |
+
data = DatasetDict({split:Dataset.from_list(rows,features=features) for split,rows in splits.items()})
|
| 53 |
+
report.update(conversion_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 54 |
+
splits={s:len(d) for s,d in data.items()})
|
| 55 |
+
for split, rows in data.items():
|
| 56 |
+
rows.to_parquet(str(directory / (split + '.parquet')))
|
| 57 |
+
(directory/'excluded-questions.jsonl').write_text('')
|
| 58 |
+
(directory/'provenance.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
|
| 59 |
+
return data
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sentfin():
|
| 63 |
+
"""SEntFiN entity sentiment, one native headline/entity judgment per row.
|
| 64 |
+
|
| 65 |
+
Pinned original CSV: https://github.com/pyRis/SEntFiN (repository MIT license).
|
| 66 |
+
Only malformed dictionary quoting is repaired; the original annotation string
|
| 67 |
+
and source row ID remain in metadata. Identical normalized headlines stay in
|
| 68 |
+
one deterministic 80/10/10 internal partition. These are derived holdouts, not
|
| 69 |
+
an official benchmark split. Duplicate pairs are deduplicated; contradictory
|
| 70 |
+
judgments for the same headline/entity are excluded and reported.
|
| 71 |
+
"""
|
| 72 |
+
url=f'https://raw.githubusercontent.com/pyRis/SEntFiN/{SENTFIN_REVISION}/SEntFiN.csv'
|
| 73 |
+
raw=urllib.request.urlopen(url).read()
|
| 74 |
+
records, repairs, conflicts, duplicates = {}, [], set(), 0
|
| 75 |
+
for row in csv.DictReader(io.StringIO(raw.decode())):
|
| 76 |
+
labels, repaired = parse_sentfin(row['Decisions'])
|
| 77 |
+
if repaired:
|
| 78 |
+
repairs.append(dict(id=row['S No.'], original=row['Decisions'], parsed=labels))
|
| 79 |
+
group=text_key(row['Title'])
|
| 80 |
+
for entity,label in labels.items():
|
| 81 |
+
key=(group,entity.casefold())
|
| 82 |
+
if key in records:
|
| 83 |
+
if records[key]['labels'] != label:
|
| 84 |
+
conflicts.add(key)
|
| 85 |
+
else:
|
| 86 |
+
duplicates += 1
|
| 87 |
+
continue
|
| 88 |
+
meta=dict(id=f"{row['S No.']}:{entity}", headline_id=row['S No.'], entity=entity,
|
| 89 |
+
split_group_id=group, source_url=url, source_revision=SENTFIN_REVISION,
|
| 90 |
+
source_annotation=row['Decisions'], quoting_repaired=repaired)
|
| 91 |
+
records[key]=dict(sentence1=row['Title'],sentence2=entity,labels=label,
|
| 92 |
+
metadata=json.dumps(meta,ensure_ascii=False,sort_keys=True))
|
| 93 |
+
splits={s:[] for s in ('train','validation','test')}
|
| 94 |
+
for (group,entity),row in records.items():
|
| 95 |
+
if (group,entity) not in conflicts:
|
| 96 |
+
splits[_split_of(group)].append(row)
|
| 97 |
+
return write_mirror('sentfin',splits,'string',dict(source_url=url,revision=SENTFIN_REVISION,
|
| 98 |
+
source_sha256=hashlib.sha256(raw).hexdigest(),repairs=repairs,duplicate_pairs=duplicates,
|
| 99 |
+
excluded_conflicting_pairs=[list(k) for k in sorted(conflicts)],
|
| 100 |
+
split_policy='normalized-headline-hash-80/10/10',license='mit',
|
| 101 |
+
license_url=f'https://github.com/pyRis/SEntFiN/blob/{SENTFIN_REVISION}/LICENSE'))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def wands():
|
| 105 |
+
"""WANDS native three-grade product relevance with query-disjoint internal holdouts.
|
| 106 |
+
|
| 107 |
+
Original Wayfair data: https://github.com/wayfair/WANDS (MIT).
|
| 108 |
+
Uses the pinned joined napsternxg/wands Hub copy; its random row splits overlap
|
| 109 |
+
on queries and are replaced by deterministic 80/10/10 normalized-query groups.
|
| 110 |
+
All native judgments are retained. Inputs contain query and product content;
|
| 111 |
+
popularity/rating fields and relevance labels never enter model inputs.
|
| 112 |
+
"""
|
| 113 |
+
root=Path(snapshot_download('napsternxg/wands',repo_type='dataset',revision=WANDS_REVISION,
|
| 114 |
+
allow_patterns=['data/*.parquet']))
|
| 115 |
+
splits={s:[] for s in ('train','validation','test')}
|
| 116 |
+
counts=Counter()
|
| 117 |
+
for path in sorted(root.glob('data/*.parquet')):
|
| 118 |
+
for batch in pq.ParquetFile(path).iter_batches(batch_size=512):
|
| 119 |
+
for row in batch.to_pylist():
|
| 120 |
+
if row['label'] not in (0,1,2):
|
| 121 |
+
raise ValueError('Unknown WANDS relevance grade')
|
| 122 |
+
group=text_key(row['query'])
|
| 123 |
+
fields=('product_name','product_class','category hierarchy','product_description','product_features')
|
| 124 |
+
product='\n'.join(f'{key}: {row[key]}' for key in fields if row.get(key))
|
| 125 |
+
meta=dict(id=str(row['id']),query_id=row['query_id'],product_id=row['product_id'],
|
| 126 |
+
split_group_id=group,original_mirror_split=path.name.split('-')[0],
|
| 127 |
+
source_dataset='napsternxg/wands',source_revision=WANDS_REVISION)
|
| 128 |
+
splits[_split_of(group)].append(dict(sentence1=row['query'],sentence2=product,
|
| 129 |
+
labels=row['label'],metadata=json.dumps(meta,sort_keys=True)))
|
| 130 |
+
counts[row['label']] += 1
|
| 131 |
+
return write_mirror('wands',splits,'int64',dict(source='napsternxg/wands',revision=WANDS_REVISION,
|
| 132 |
+
original_source='https://github.com/wayfair/WANDS',label_counts=dict(counts),
|
| 133 |
+
source_sha256={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in root.glob('data/*.parquet')},
|
| 134 |
+
split_policy='normalized-query-hash-80/10/10',license='mit',
|
| 135 |
+
license_url='https://github.com/wayfair/WANDS/blob/3b74dcf4ba29ab8ff3e6a50b5b09fc627cb882b5/LICENSE'))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def search_record(row, candidate):
|
| 139 |
+
score=candidate['score']
|
| 140 |
+
if not isinstance(score,(int,float)) or not 0 <= score <= 14:
|
| 141 |
+
raise ValueError(f'Unexpected SciRepEval click-derived score: {score}')
|
| 142 |
+
document='\n'.join(v for v in (candidate.get('title'),candidate.get('abstract')) if v)
|
| 143 |
+
if not document.strip() or not row['query'].strip():
|
| 144 |
+
return None
|
| 145 |
+
group=text_key(row['query'])
|
| 146 |
+
meta=dict(id=f"{row['doc_id']}:{candidate['doc_id']}",query_id=row['doc_id'],
|
| 147 |
+
candidate_id=candidate['doc_id'],split_group_id=group,source_revision=SEARCH_REVISION,
|
| 148 |
+
source_score=score,supervision='click-derived score, not a human relevance rating',
|
| 149 |
+
score_anchors=list(range(0,15,2)),score_interpolation='linear; expected score equals native value')
|
| 150 |
+
return dict(sentence1=row['query'],sentence2=document,labels=float(score),metadata=json.dumps(meta,sort_keys=True))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def scirepeval_search(max_rows=5000, max_rows_eval=500, seed=42):
|
| 154 |
+
"""SciRepEval Search native train/validation pairs with raw click-derived numeric scores.
|
| 155 |
+
|
| 156 |
+
No evaluation/test benchmark data is consumed. All training/validation shards
|
| 157 |
+
are scanned; deterministic hash sampling covers eligible pairs from the entire
|
| 158 |
+
source, not an early prefix. Validation queries seen in training are excluded.
|
| 159 |
+
Scores remain unchanged. Jev uses linear interpolation over eight anchors
|
| 160 |
+
0,2,...,14 to preserve the numeric expectation within its 10-level limit.
|
| 161 |
+
Dataset/text licensing is unspecified: the code's Apache license is not used
|
| 162 |
+
as a grant for paper abstracts. Evidence and exclusions remain in provenance.
|
| 163 |
+
"""
|
| 164 |
+
root=Path(snapshot_download('allenai/scirepeval',repo_type='dataset',revision=SEARCH_REVISION,
|
| 165 |
+
allow_patterns=['search/train-*.parquet','search/validation-*.parquet'],max_workers=4))
|
| 166 |
+
splits, counts, train_groups = {}, Counter(), set()
|
| 167 |
+
scores=Counter()
|
| 168 |
+
for split,limit in [('train',max_rows),('validation',max_rows_eval)]:
|
| 169 |
+
pool=[]
|
| 170 |
+
for path in sorted(root.glob(f'search/{split}-*.parquet')):
|
| 171 |
+
for batch in pq.ParquetFile(path).iter_batches(batch_size=64):
|
| 172 |
+
for source in batch.to_pylist():
|
| 173 |
+
group=text_key(source['query'])
|
| 174 |
+
if split=='validation' and group in train_groups:
|
| 175 |
+
counts['validation/excluded/query_overlap'] += len(source['candidates'])
|
| 176 |
+
continue
|
| 177 |
+
if split=='train':
|
| 178 |
+
train_groups.add(group)
|
| 179 |
+
for candidate in source['candidates']:
|
| 180 |
+
record=search_record(source,candidate)
|
| 181 |
+
if record is None:
|
| 182 |
+
counts[split+'/excluded/missing_text'] += 1
|
| 183 |
+
continue
|
| 184 |
+
counts[split+'/eligible'] += 1
|
| 185 |
+
scores[candidate['score']] += 1
|
| 186 |
+
identity=f"{source['doc_id']}:{candidate['doc_id']}"
|
| 187 |
+
rank=-int(hashlib.sha256(f'{seed}:{identity}'.encode()).hexdigest(),16)
|
| 188 |
+
item=(rank,identity,counts[split+'/eligible'],record)
|
| 189 |
+
if len(pool)<limit:
|
| 190 |
+
heapq.heappush(pool,item)
|
| 191 |
+
elif item[:2]>pool[0][:2]:
|
| 192 |
+
heapq.heapreplace(pool,item)
|
| 193 |
+
# Duplicate native query/candidate pairs must not become duplicated training examples.
|
| 194 |
+
selected={identity:record for _,identity,_,record in sorted(pool)}
|
| 195 |
+
splits[split]=list(selected.values())
|
| 196 |
+
return write_mirror('scirepeval-search',splits,'float64',dict(source='allenai/scirepeval',
|
| 197 |
+
revision=SEARCH_REVISION,config='search',counts=dict(counts),source_score_counts=dict(scores),
|
| 198 |
+
selection=dict(max_rows=max_rows,max_rows_eval=max_rows_eval,seed=seed,method='full-source hash sample'),
|
| 199 |
+
split_policy='native train/validation; validation queries in train excluded',license='unspecified'))
|