lewtun HF Staff commited on
Commit
0784fd3
·
verified ·
1 Parent(s): bce6fe1

Copy mid/pipeline from HuggingFaceBio/FineDNA-Mid@663538d

Browse files
mid/pipeline/1_regex_filter.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 1: keep documents that contain DNA, using a regex.
2
+
3
+ This is the V4 strict filter we ran on FineWeb-Edu, FinePDFs, PubMed Central, bioRxiv and Biostars. A document passes when:
4
+ - it mentions at least one molecular-biology keyword (dna, gene, primer, pcr, ...), and
5
+ - it contains a run of 15 or more nucleotide letters (A, T, C, G, U, N; any case) that
6
+ - uses at least 3 different letters, so "AAAAAAAAAAAAAAA" or "NNNN..." alone do not count, and
7
+ - is not inside curly braces, which in scraped text is usually LaTeX rather than a sequence.
8
+
9
+ Run it with datatrove over any parquet dataset with a text column:
10
+
11
+ python 1_regex_filter.py --input hf://datasets/HuggingFaceFW/fineweb-edu/sample/10BT --output ./dna_regex/fineweb_edu
12
+ """
13
+ import argparse
14
+ import re
15
+
16
+ from datatrove.data import Document
17
+ from datatrove.executor import LocalPipelineExecutor
18
+ from datatrove.pipeline.filters.base_filter import BaseFilter
19
+ from datatrove.pipeline.readers import ParquetReader
20
+ from datatrove.pipeline.writers import JsonlWriter
21
+ from datatrove.pipeline.writers.disk_base import DiskWriter
22
+
23
+
24
+ class DNAFilterV4Strict(BaseFilter):
25
+ """
26
+ Strict regex filter for high-confidence DNA/RNA sequences.
27
+
28
+ Requirements:
29
+ - 15+ base sequences
30
+ - 3+ unique bases
31
+ - Biological keywords present
32
+ - Not in LaTeX braces
33
+ """
34
+ name = "🧬 DNAFilterV4Strict"
35
+
36
+ def __init__(self, exclusion_writer: DiskWriter = None):
37
+ super().__init__(exclusion_writer)
38
+ self.bio_terms = {
39
+ 'dna', 'rna', 'nucleotide', 'genome', 'gene',
40
+ 'base pair', 'codon', 'primer', 'pcr', 'amplification',
41
+ 'sequencing', 'nucleic acid', 'oligonucleotide', 'plasmid',
42
+ 'transcription', 'translation', 'mrna', 'ribosome',
43
+ 'trna', 'rrna', 'uracil'
44
+ }
45
+ self.min_keywords = 1
46
+ self.nucleotide_pattern = re.compile(r'[ATCGUN]{15,}', re.IGNORECASE)
47
+
48
+ def _has_mixed_bases(self, seq: str, min_unique: int = 3) -> bool:
49
+ """Check if sequence contains at least min_unique different bases."""
50
+ seq_upper = seq.upper()
51
+ unique_bases = set(c for c in seq_upper if c in 'ATCGUN')
52
+ return len(unique_bases) >= min_unique
53
+
54
+ def _is_in_braces(self, text: str, match_start: int, match_end: int) -> bool:
55
+ """Check if the match is inside curly braces (likely LaTeX)."""
56
+ before = text[max(0, match_start - 100):match_start]
57
+ after = text[match_end:min(len(text), match_end + 100)]
58
+ open_braces = before.count('{') - before.count('}')
59
+ if open_braces > 0 and '}' in after:
60
+ return True
61
+ return False
62
+
63
+ def filter(self, doc: Document) -> bool:
64
+ text = doc.text
65
+ text_lower = text.lower()
66
+
67
+ keyword_count = sum(1 for term in self.bio_terms if term in text_lower)
68
+ if keyword_count < self.min_keywords:
69
+ return False
70
+
71
+ matches = list(self.nucleotide_pattern.finditer(text))
72
+ if not matches:
73
+ return False
74
+
75
+ for match in matches:
76
+ seq = match.group()
77
+ if not self._has_mixed_bases(seq):
78
+ continue
79
+ if self._is_in_braces(text, match.start(), match.end()):
80
+ continue
81
+
82
+ doc.metadata["filter_type"] = "strict_regex"
83
+ doc.metadata["stage"] = 1
84
+ return True
85
+
86
+ return False
87
+
88
+
89
+ if __name__ == "__main__":
90
+ ap = argparse.ArgumentParser(description="Keep documents that contain DNA (V4 strict regex filter).")
91
+ ap.add_argument("--input", required=True, help="folder of parquet files, local or hf://datasets/...")
92
+ ap.add_argument("--output", required=True, help="where to write the kept documents as jsonl.gz")
93
+ ap.add_argument("--text_key", default="text", help="text column (PubMed Central uses article_text)")
94
+ ap.add_argument("--glob", default="**/*.parquet")
95
+ ap.add_argument("--tasks", type=int, default=8)
96
+ a = ap.parse_args()
97
+
98
+ LocalPipelineExecutor(
99
+ pipeline=[
100
+ ParquetReader(a.input, glob_pattern=a.glob, text_key=a.text_key),
101
+ DNAFilterV4Strict(),
102
+ JsonlWriter(a.output, compression="gzip"),
103
+ ],
104
+ tasks=a.tasks,
105
+ workers=a.tasks,
106
+ logging_dir=f"{a.output}/logs",
107
+ ).run()
mid/pipeline/2_p90_split.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 2: split the regex-filtered documents by how long their longest DNA sequence is.
2
+
3
+ Every DNA "word" in a document is found with tag_dna_sequences: a whitespace-delimited token of at least 6 letters that
4
+ is pure A/C/G/T, or IUPAC codes (12+ letters, at most 20% ambiguous), with surrounding punctuation and 5'/3' markers
5
+ stripped. A document whose longest DNA word is at least 39 bp, the 90th percentile of that length across the regex
6
+ data, goes to p90; everything else goes to rest. Short DNA words are mostly primers and motifs; p90 documents carry
7
+ real sequences.
8
+
9
+ python 2_p90_split.py --input ./dna_regex/fineweb_edu --p90 ./p90/fineweb_edu --rest ./rest/fineweb_edu
10
+
11
+ Input and output are jsonl.gz files with a "text" field, as written by step 1. One output file per input file.
12
+ """
13
+ import argparse
14
+ import glob
15
+ import gzip
16
+ import json
17
+ import os
18
+
19
+ from tag_dna_sequences import tag_dna_sequences
20
+
21
+ P90_THRESHOLD = 39 # bp: the 90th percentile of the longest DNA word per document
22
+ MIN_LEN = 6 # bp: shortest token counted as DNA
23
+
24
+
25
+ def longest_dna(text: str) -> int:
26
+ _, _, seqs = tag_dna_sequences(text, min_len=MIN_LEN)
27
+ return max((len(s) for s in seqs), default=0)
28
+
29
+
30
+ def main():
31
+ ap = argparse.ArgumentParser(description="Split DNA-bearing documents into p90 (longest DNA >= 39 bp) and rest.")
32
+ ap.add_argument("--input", required=True, help="folder of jsonl.gz files from step 1")
33
+ ap.add_argument("--p90", required=True, help="output folder for p90 documents")
34
+ ap.add_argument("--rest", required=True, help="output folder for the rest")
35
+ ap.add_argument("--threshold", type=int, default=P90_THRESHOLD)
36
+ a = ap.parse_args()
37
+
38
+ os.makedirs(a.p90, exist_ok=True)
39
+ os.makedirs(a.rest, exist_ok=True)
40
+ n_p90 = n_rest = 0
41
+ for path in sorted(glob.glob(os.path.join(a.input, "**", "*.jsonl.gz"), recursive=True)):
42
+ name = os.path.basename(path)
43
+ with gzip.open(path, "rt", encoding="utf-8") as fin, \
44
+ gzip.open(os.path.join(a.p90, name), "wt", encoding="utf-8") as fp90, \
45
+ gzip.open(os.path.join(a.rest, name), "wt", encoding="utf-8") as frest:
46
+ for line in fin:
47
+ if not line.strip():
48
+ continue
49
+ text = json.loads(line).get("text") or ""
50
+ if longest_dna(text) >= a.threshold:
51
+ fp90.write(line if line.endswith("\n") else line + "\n"); n_p90 += 1
52
+ else:
53
+ frest.write(line if line.endswith("\n") else line + "\n"); n_rest += 1
54
+ print(f"p90: {n_p90:,} documents rest: {n_rest:,} documents")
55
+
56
+
57
+ if __name__ == "__main__":
58
+ main()
mid/pipeline/README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How the FineDNA biology text was found
2
+
3
+ The `bio_*` subsets of FineDNA are web pages, papers and forum posts that contain DNA sequences inside normal text.
4
+ They were found in two steps.
5
+
6
+ ## 1. Regex filter: does the document contain DNA? (`1_regex_filter.py`)
7
+
8
+ We ran this filter over FineWeb-Edu, FinePDFs, PubMed Central, bioRxiv and Biostars. A document is kept when it
9
+
10
+ - contains a run of **15 or more nucleotide letters** (A, T, C, G, U, N, any case),
11
+ - that run uses **at least 3 different letters**, so `AAAAAAAAAAAAAAA` does not count,
12
+ - the run is **not inside curly braces**, which in scraped text is usually LaTeX, and
13
+ - the document mentions **at least one molecular-biology keyword**: dna, rna, nucleotide, genome, gene, base pair,
14
+ codon, primer, pcr, amplification, sequencing, nucleic acid, oligonucleotide, plasmid, transcription,
15
+ translation, mrna, ribosome, trna, rrna or uracil.
16
+
17
+ ```bash
18
+ python 1_regex_filter.py --input hf://datasets/HuggingFaceFW/fineweb-edu/sample/10BT --output ./dna_regex/fineweb_edu
19
+ ```
20
+
21
+ ## 2. p90 split: how long is the DNA? (`2_p90_split.py`)
22
+
23
+ Many regex hits are short: a primer, a restriction site, a motif. Training on documents with real sequences worked
24
+ better, so we measure the **longest DNA word** in each document with `tag_dna_sequences.py`: a whitespace-delimited
25
+ token of at least 6 letters that is pure A/C/G/T (or IUPAC codes, 12+ letters, at most 20% ambiguous), with
26
+ punctuation and 5'/3' markers stripped.
27
+
28
+ - Longest DNA word **at least 39 bp** (the 90th percentile across the regex data): `bio_p90_*`.
29
+ - Everything else: `bio_rest`.
30
+
31
+ ```bash
32
+ python 2_p90_split.py --input ./dna_regex/fineweb_edu --p90 ./p90/fineweb_edu --rest ./rest/fineweb_edu
33
+ ```
34
+
35
+ In the Carbon-X mix, p90 gets as much weight as all of `bio_rest` and is read about seven times; `bio_rest` about
36
+ twice.
37
+
38
+ ## Requirements
39
+
40
+ `pip install datatrove` for step 1. Step 2 needs only the Python standard library and `tag_dna_sequences.py`, which
41
+ sits next to it.
mid/pipeline/tag_dna_sequences.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import List, Tuple, Dict, Any, Optional
3
+
4
+ DNA_TOKEN_RE = re.compile(r"^[ATCGatcg]{6,}$")
5
+ DNA_IUPAC_RE = re.compile(r"^[ATCGNRYKMSWBDHVatcgnrykmswbdhv]{6,}$")
6
+ # For probe/primer strings like 5′-6FAM-ATCG...-MGB-NFQ-3′, split only on dashes.
7
+ DASH_SPLIT_RE = re.compile(r"([-–—])")
8
+ # Leading/trailing punctuation/markers commonly seen around sequences:
9
+ # includes slashes, backslashes, primes (ASCII + unicode), digits (e.g. 5' / 3'),
10
+ # hyphens and unicode dashes.
11
+ PUNCT_EDGE_RE = re.compile(r"^([\\/\(\[\{\"'`′0-9\-–—]*)(.*?)([\\/\)\]\}\"'`′0-9,\;:\.\!\?\-–—]*)$")
12
+
13
+
14
+ def _truncate_to_k(seq: str, k: int = 6) -> str:
15
+ """Truncate sequence to the largest multiple of k that is <= len(seq)."""
16
+ return seq[: (len(seq) // k) * k]
17
+
18
+
19
+ def tag_dna_sequences(
20
+ text: str,
21
+ min_len: int = 6,
22
+ max_ambig_frac: float = 0.2,
23
+ truncate_to_k: int = 0,
24
+ ) -> Tuple[str, List[int], List[str]]:
25
+ """
26
+ Tag DNA-like tokens in text with <dna>...</dna>.
27
+ Criteria:
28
+ - Token must be a single whitespace-delimited word (after stripping edge punctuation)
29
+ - Token must be only A/T/C/G (case-insensitive) OR IUPAC codes (len >= 12) with ambiguity <= max_ambig_frac
30
+ - Token length >= min_len
31
+
32
+ Args:
33
+ truncate_to_k: if > 0, truncate each tagged sequence to the nearest
34
+ multiple of k before wrapping. This avoids tokenizer A-padding for
35
+ sequences whose length is not a multiple of k (e.g. truncate_to_k=6
36
+ turns TGAGTACT→TGAGTA before tagging).
37
+
38
+ Returns:
39
+ tagged_text, dna_word_ids, dna_sequences
40
+ dna_word_ids are indices among non-whitespace tokens (0-based)
41
+ """
42
+ if not text:
43
+ return text, [], []
44
+
45
+ # Preserve original whitespace by splitting into tokens + separators
46
+ parts = re.split(r"(\s+)", text)
47
+
48
+ dna_word_ids: List[int] = []
49
+ dna_sequences: List[str] = []
50
+
51
+ word_index = 0
52
+ for i, part in enumerate(parts):
53
+ if not part or part.isspace():
54
+ continue
55
+
56
+ # Strip leading/trailing punctuation for matching only
57
+ lead, core, trail = part, part, ""
58
+ m = PUNCT_EDGE_RE.match(part)
59
+ if m:
60
+ lead, core, trail = m.group(1), m.group(2), m.group(3)
61
+
62
+ if core and len(core) >= min_len:
63
+ tagged_any = False
64
+
65
+ if DNA_TOKEN_RE.match(core):
66
+ core_up = core.upper()
67
+ if truncate_to_k > 0:
68
+ core_up = _truncate_to_k(core_up, truncate_to_k)
69
+ if len(core_up) >= min_len:
70
+ parts[i] = f"{lead}<dna>{core_up}</dna>{trail}"
71
+ dna_sequences.append(core_up)
72
+ tagged_any = True
73
+ elif DNA_IUPAC_RE.match(core):
74
+ core_up = core.upper()
75
+ ambig_count = sum(1 for c in core_up if c not in {"A", "T", "C", "G"})
76
+ ambig_frac = ambig_count / len(core_up)
77
+ if len(core_up) >= 12 and ambig_frac <= max_ambig_frac:
78
+ if truncate_to_k > 0:
79
+ core_up = _truncate_to_k(core_up, truncate_to_k)
80
+ if len(core_up) >= min_len:
81
+ parts[i] = f"{lead}<dna>{core_up}</dna>{trail}"
82
+ dna_sequences.append(core_up)
83
+ tagged_any = True
84
+ elif DASH_SPLIT_RE.search(core):
85
+ subparts = DASH_SPLIT_RE.split(core)
86
+ rebuilt = []
87
+ for sp in subparts:
88
+ if not sp:
89
+ continue
90
+ if DASH_SPLIT_RE.fullmatch(sp):
91
+ rebuilt.append(sp)
92
+ continue
93
+ if len(sp) < min_len:
94
+ rebuilt.append(sp)
95
+ continue
96
+ if DNA_TOKEN_RE.match(sp):
97
+ sp_up = sp.upper()
98
+ if truncate_to_k > 0:
99
+ sp_up = _truncate_to_k(sp_up, truncate_to_k)
100
+ if len(sp_up) >= min_len:
101
+ rebuilt.append(f"<dna>{sp_up}</dna>")
102
+ dna_sequences.append(sp_up)
103
+ tagged_any = True
104
+ else:
105
+ rebuilt.append(sp)
106
+ elif DNA_IUPAC_RE.match(sp):
107
+ sp_up = sp.upper()
108
+ ambig_count = sum(1 for c in sp_up if c not in {"A", "T", "C", "G"})
109
+ ambig_frac = ambig_count / len(sp_up)
110
+ if len(sp_up) >= 12 and ambig_frac <= max_ambig_frac:
111
+ if truncate_to_k > 0:
112
+ sp_up = _truncate_to_k(sp_up, truncate_to_k)
113
+ if len(sp_up) >= min_len:
114
+ rebuilt.append(f"<dna>{sp_up}</dna>")
115
+ dna_sequences.append(sp_up)
116
+ tagged_any = True
117
+ else:
118
+ rebuilt.append(sp)
119
+ else:
120
+ rebuilt.append(sp)
121
+ else:
122
+ rebuilt.append(sp)
123
+ if tagged_any:
124
+ parts[i] = f"{lead}{''.join(rebuilt)}{trail}"
125
+
126
+ if tagged_any:
127
+ dna_word_ids.append(word_index)
128
+
129
+ word_index += 1
130
+
131
+ return "".join(parts), dna_word_ids, dna_sequences
132
+
133
+
134
+ def tag_dna_sequences_batch(
135
+ batch: Dict[str, List[str]],
136
+ text_key: str = "text",
137
+ min_len: int = 6,
138
+ max_ambig_frac: float = 0.2,
139
+ ) -> Dict[str, Any]:
140
+ texts = batch[text_key]
141
+ tagged_texts = []
142
+ all_ids = []
143
+ all_seqs = []
144
+
145
+ for text in texts:
146
+ tagged, ids, seqs = tag_dna_sequences(
147
+ text,
148
+ min_len=min_len,
149
+ max_ambig_frac=max_ambig_frac,
150
+ )
151
+ tagged_texts.append(tagged)
152
+ all_ids.append(ids)
153
+ all_seqs.append(seqs)
154
+
155
+ return {
156
+ f"{text_key}_tagged": tagged_texts,
157
+ "dna_word_ids": all_ids,
158
+ "dna_sequences": all_seqs,
159
+ }
160
+
161
+
162
+ if __name__ == "__main__":
163
+ # Quick sanity tests (local, no dataset)
164
+ examples = [
165
+ "This is ATCGAT and ATCGATCG with words.",
166
+ "codon ATG should not be tagged if min_len=6.",
167
+ "lowercase atcgat should be tagged.",
168
+ r"T\. miR\148\F: \CAAGCACGAT TAGCATTTGA\; miR\148\R: \TAGAAAGCT TTCGAGACAA\.",
169
+ "5'ATCGATCG3' and 5′ATCGATCG3′ should be tagged.",
170
+ "Punctuation ATCGAT, should be tagged.",
171
+ "Probe 5′-6FAM-ATCGATCG-3′ should tag the DNA part.",
172
+ "Mix: ATCGATCG ATCGATx ATCGATCGAT",
173
+ "Multiple spaces ATCGAT and newlines\nATCGATCG",
174
+ "IUPAC ATCGNNRY should NOT be tagged at max_ambig_frac=0.2.",
175
+ ]
176
+
177
+ for ex in examples:
178
+ tagged, ids, seqs = tag_dna_sequences(ex, min_len=6)
179
+ print("---")
180
+ print("IN: ", ex)
181
+ print("OUT:", tagged)
182
+ print("IDS:", ids)
183
+ print("SEQ:", seqs)