Datasets:

Modalities:
Text
Formats:
parquet
License:
sileod commited on
Commit
fc20607
·
verified ·
1 Parent(s): c6b2de9

Include reproducible source conversion

Browse files
Files changed (1) hide show
  1. repackage_dataset/specialized_text.py +154 -0
repackage_dataset/specialized_text.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned legal relevance, clinical inference and sexism sources; native labels only."""
2
+ import ast
3
+ from collections import Counter, defaultdict
4
+ import csv
5
+ import hashlib
6
+ import io
7
+ import json
8
+ from pathlib import Path
9
+ import tarfile
10
+ import urllib.request
11
+ import zipfile
12
+
13
+ from huggingface_hub import hf_hub_download
14
+
15
+ from .relevance import text_key, write_mirror
16
+
17
+ ACORD_REVISION = '7ba1c6f2e0baaa32e78c78c2b02e9c57b102af4e'
18
+ EDOS_REVISION = 'b1f1fbcca9d42de0395432ada8fcfb5c35f68c77'
19
+ EVIDENCE_URL = 'https://evidence-inference.ebm-nlp.com/v2.0.tar.gz'
20
+ EVIDENCE_SHA256 = '6abe0d4ec0d331834981c0171c3c79d47515761867f82f1dc6066e43863a1586'
21
+
22
+
23
+ def acord():
24
+ """ACORD attorney-annotated query/clause relevance, preserving native query splits.
25
+
26
+ Join only explicit qrels against the official queries/corpus. Unjudged pairs
27
+ are never converted to negatives. Grades 0–4 correspond to 1–5 attorney stars.
28
+ Original dataset terms: CC BY 4.0. Archive, source revision and counts are
29
+ recorded in provenance.json; metadata retains query and clause identities.
30
+ """
31
+ archive = hf_hub_download('theatticusproject/acord','ACORD Dataset & ReadMe.zip',
32
+ repo_type='dataset',revision=ACORD_REVISION)
33
+ splits, counts, groups = {}, Counter(), {}
34
+ with zipfile.ZipFile(archive) as source:
35
+ prefix = next(n.rsplit('/',1)[0]+'/' for n in source.namelist() if n.endswith('/queries.jsonl'))
36
+ queries = {r['_id']:r['text'] for r in map(json.loads,source.read(prefix+'queries.jsonl').splitlines())}
37
+ clauses = {r['_id']:r['text'] for r in map(json.loads,source.read(prefix+'corpus.jsonl').splitlines())}
38
+ for split,native in [('train','train'),('validation','valid'),('test','test')]:
39
+ records = {}
40
+ for row in csv.DictReader(io.StringIO(source.read(prefix+f'qrels/{native}.tsv').decode()),delimiter='\t'):
41
+ q,c,grade = row['query-id'],row['corpus-id'],int(row['score'])
42
+ if q not in queries or c not in clauses or grade not in range(5):
43
+ raise ValueError('Invalid ACORD qrel')
44
+ key=(q,c)
45
+ if key in records:
46
+ if records[key]['labels'] != str(grade):
47
+ raise ValueError('Conflicting ACORD qrels')
48
+ counts['duplicate_qrels'] += 1
49
+ continue
50
+ meta=dict(id=text_key(q)+':'+c,query_id=q,clause_id=c,split_group_id=text_key(queries[q]))
51
+ records[key]=dict(sentence1=queries[q],sentence2=clauses[c],labels=str(grade),
52
+ metadata=json.dumps(meta,sort_keys=True))
53
+ counts[f'{split}/grade/{grade}'] += 1
54
+ splits[split]=list(records.values())
55
+ groups[split]={text_key(queries[q]) for q,c in records}
56
+ assert all(not groups[a]&groups[b] for a in groups for b in groups if a!=b), 'ACORD query overlap'
57
+ return write_mirror('acord',splits,'string',dict(conversion_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),source='theatticusproject/acord',revision=ACORD_REVISION,
58
+ archive_sha256=hashlib.sha256(Path(archive).read_bytes()).hexdigest(),counts=dict(counts),
59
+ query_counts={s:len(g) for s,g in groups.items()},split_policy='native query partitions',license='cc-by-4.0'))
60
+
61
+
62
+ def edos():
63
+ """EDOS native binary sexism judgments and original train/dev/test assignments.
64
+
65
+ Original source: https://github.com/rewire-online/edos (CC0-1.0).
66
+ Reads the aggregated annotation CSV, retaining all native labels, identities
67
+ and split assignments. Category/vector labels remain in metadata; no generated
68
+ explanations enter inputs. See provenance.json for the pinned source/hash.
69
+ """
70
+ url=f'https://raw.githubusercontent.com/rewire-online/edos/{EDOS_REVISION}/data/edos_labelled_aggregated.csv'
71
+ raw=urllib.request.urlopen(url).read()
72
+ splits={s:[] for s in ('train','validation','test')}
73
+ for row in csv.DictReader(io.StringIO(raw.decode())):
74
+ if row['label_sexist'] not in ('not sexist','sexist'):
75
+ raise ValueError('Unknown EDOS label')
76
+ split={'train':'train','dev':'validation','test':'test'}[row['split']]
77
+ meta=dict(id=row['rewire_id'],split_group_id=text_key(row['text']),
78
+ category=row['label_category'],vector=row['label_vector'],source_revision=EDOS_REVISION)
79
+ splits[split].append(dict(sentence1=row['text'],sentence2='',labels=row['label_sexist'],
80
+ metadata=json.dumps(meta,sort_keys=True)))
81
+ # Preserve evaluation membership; discard training copies of evaluation texts.
82
+ heldout={text_key(r['sentence1']) for s in ('validation','test') for r in splits[s]}
83
+ before=len(splits['train'])
84
+ splits['train']=[r for r in splits['train'] if text_key(r['sentence1']) not in heldout]
85
+ return write_mirror('edos',splits,'string',dict(conversion_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),source_url=url,revision=EDOS_REVISION,
86
+ source_sha256=hashlib.sha256(raw).hexdigest(),excluded_train_overlap=before-len(splits['train']),
87
+ split_policy='native partitions; training copies of evaluation text removed',license='cc0-1.0'))
88
+
89
+
90
+ def evidence_inference():
91
+ """Evidence Inference v2: full article + intervention/comparator/outcome → effect direction.
92
+
93
+ Join annotations by PromptID AND PMCID, never by article alone. Use verified
94
+ labels, exclude tied votes and upstream known-bad prompts. Evidence spans in
95
+ metadata refer only to the same prompt and winning label. Full article text
96
+ stays in the input so isolated snippets need not identify treatment arms.
97
+ Native article train/validation/test splits are preserved. The upstream code
98
+ and annotations have MIT terms; article-text rights vary and are not relabeled
99
+ MIT. Mirror text/data licensing remains unspecified.
100
+ """
101
+ raw=urllib.request.urlopen(EVIDENCE_URL).read()
102
+ digest=hashlib.sha256(raw).hexdigest()
103
+ if digest != EVIDENCE_SHA256:
104
+ raise ValueError('Evidence Inference archive changed; review before updating the pin')
105
+ script=Path(hf_hub_download('bigbio/evidence_inference','evidence_inference.py',repo_type='dataset',
106
+ revision='35dce6aba1b3eb9eb9af9bdc38ebeda73dad15b9')).read_text()
107
+ skip=set()
108
+ for node in ast.parse(script).body:
109
+ if isinstance(node,ast.Assign) and isinstance(node.targets[0],ast.Name) and node.targets[0].id in {
110
+ 'INCORRECT_PROMPT_IDS','QUESTIONABLE_PROMPT_IDS','SOMEWHAT_MALFORMED_PROMPT_IDS'}:
111
+ skip.update(ast.literal_eval(node.value.args[0]))
112
+ splits={s:[] for s in ('train','validation','test')}; counts=Counter();annotations=defaultdict(list)
113
+ with tarfile.open(fileobj=io.BytesIO(raw)) as compressed:
114
+ payload = {member.name:compressed.extractfile(member).read() for member in compressed if member.isfile()}
115
+ with tarfile.open(fileobj=io.BytesIO(raw)) as archive:
116
+ def read(name):
117
+ return payload[name].decode('utf-8-sig')
118
+ membership={}
119
+ for split in splits:
120
+ ids=set(read(f'splits/{split}_article_ids.txt').split())
121
+ assert not ids.intersection(membership), 'Evidence Inference article overlap'
122
+ membership.update({article:split for article in ids})
123
+ for row in csv.DictReader(io.StringIO(read('annotations_merged.csv'))):
124
+ if row['Valid Label'].lower() in ('true','1'):
125
+ annotations[(row['PromptID'],row['PMCID'])].append(row)
126
+ articles={}
127
+ for prompt in csv.DictReader(io.StringIO(read('prompts_merged.csv'))):
128
+ pid,article=prompt['PromptID'],prompt['PMCID']
129
+ votes=Counter(a['Label Code'] for a in annotations[(pid,article)])
130
+ if int(pid) in skip or not votes or article not in membership:
131
+ counts['excluded/invalid_or_unassigned_prompt'] += 1
132
+ continue
133
+ ranked=votes.most_common()
134
+ if ranked[0][0] not in ('-1','0','1') or len(ranked)>1 and ranked[0][1]==ranked[1][1]:
135
+ counts['excluded/tied_or_invalid_labels'] += 1
136
+ continue
137
+ label=ranked[0][0]
138
+ if article not in articles:
139
+ articles[article]=read(f'txt_files/PMC{article}.txt')
140
+ text=articles[article];spans=set()
141
+ for annotation in annotations[(pid,article)]:
142
+ start,end=int(annotation['Evidence Start']),int(annotation['Evidence End'])
143
+ if annotation['Label Code']==label and annotation['Valid Reasoning'].lower() in ('true','1') and 0<=start<end<=len(text):
144
+ spans.add((start,end))
145
+ question=f"Intervention: {prompt['Intervention']}\nComparator: {prompt['Comparator']}\nOutcome: {prompt['Outcome']}"
146
+ meta=dict(id=pid,split_group_id=article,pmcid=article,prompt_id=pid,votes=dict(votes),
147
+ evidence_spans=[dict(start=a,end=b,text=text[a:b]) for a,b in sorted(spans)])
148
+ splits[membership[article]].append(dict(sentence1=text,sentence2=question,labels=label,
149
+ metadata=json.dumps(meta,sort_keys=True)))
150
+ counts['retained/'+label] += 1
151
+ return write_mirror('evidence-inference',splits,'string',dict(conversion_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),source_url=EVIDENCE_URL,
152
+ archive_sha256=digest,reviewed_exclusions_revision='35dce6aba1b3eb9eb9af9bdc38ebeda73dad15b9',
153
+ known_bad_prompt_ids=sorted(skip),counts=dict(counts),split_policy='native article partitions',
154
+ label_policy='majority verified labels; ties excluded',license='unspecified'))